diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_feature_extraction_pop2piano.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_feature_extraction_pop2piano.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc424fbf6e0dc4fde71c68711abf87753949c73 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_feature_extraction_pop2piano.py @@ -0,0 +1,291 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 os +import tempfile +import unittest + +import numpy as np +from datasets import load_dataset + +from transformers.testing_utils import ( + check_json_file_has_correct_format, + require_essentia, + require_librosa, + require_scipy, + require_tf, + require_torch, +) +from transformers.utils.import_utils import ( + is_essentia_available, + is_librosa_available, + is_scipy_available, + is_torch_available, +) + +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +requirements_available = ( + is_torch_available() and is_essentia_available() and is_scipy_available() and is_librosa_available() +) + +if requirements_available: + import torch + + from transformers import Pop2PianoFeatureExtractor + + +class Pop2PianoFeatureExtractionTester(unittest.TestCase): + def __init__( + self, + parent, + n_bars=2, + sample_rate=22050, + use_mel=True, + padding_value=0, + vocab_size_special=4, + vocab_size_note=128, + vocab_size_velocity=2, + vocab_size_time=100, + ): + self.parent = parent + self.n_bars = n_bars + self.sample_rate = sample_rate + self.use_mel = use_mel + self.padding_value = padding_value + self.vocab_size_special = vocab_size_special + self.vocab_size_note = vocab_size_note + self.vocab_size_velocity = vocab_size_velocity + self.vocab_size_time = vocab_size_time + + def prepare_feat_extract_dict(self): + return { + "n_bars": self.n_bars, + "sample_rate": self.sample_rate, + "use_mel": self.use_mel, + "padding_value": self.padding_value, + "vocab_size_special": self.vocab_size_special, + "vocab_size_note": self.vocab_size_note, + "vocab_size_velocity": self.vocab_size_velocity, + "vocab_size_time": self.vocab_size_time, + } + + +@require_torch +@require_essentia +@require_librosa +@require_scipy +class Pop2PianoFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = Pop2PianoFeatureExtractor if requirements_available else None + + def setUp(self): + self.feat_extract_tester = Pop2PianoFeatureExtractionTester(self) + + def test_feat_extract_from_and_save_pretrained(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = feat_extract_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + mel_1 = feat_extract_first.use_mel + mel_2 = feat_extract_second.use_mel + self.assertTrue(np.allclose(mel_1, mel_2)) + self.assertEqual(dict_first, dict_second) + + def test_feat_extract_to_json_file(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "feat_extract.json") + feat_extract_first.to_json_file(json_file_path) + feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + mel_1 = feat_extract_first.use_mel + mel_2 = feat_extract_second.use_mel + self.assertTrue(np.allclose(mel_1, mel_2)) + self.assertEqual(dict_first, dict_second) + + def test_call(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_input = np.zeros([1000000], dtype=np.float32) + + input_features = feature_extractor(speech_input, sampling_rate=16_000, return_tensors="np") + self.assertTrue(input_features.input_features.ndim == 3) + self.assertEqual(input_features.input_features.shape[-1], 512) + + self.assertTrue(input_features.beatsteps.ndim == 2) + self.assertTrue(input_features.extrapolated_beatstep.ndim == 2) + + def test_integration(self): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + speech_samples = ds.sort("id").select([0])["audio"] + input_speech = [x["array"] for x in speech_samples][0] + sampling_rate = [x["sampling_rate"] for x in speech_samples][0] + feaure_extractor = Pop2PianoFeatureExtractor.from_pretrained("sweetcocoa/pop2piano") + input_features = feaure_extractor( + input_speech, sampling_rate=sampling_rate, return_tensors="pt" + ).input_features + + EXPECTED_INPUT_FEATURES = torch.tensor( + [[-7.1493, -6.8701, -4.3214], [-5.9473, -5.7548, -3.8438], [-6.1324, -5.9018, -4.3778]] + ) + self.assertTrue(torch.allclose(input_features[0, :3, :3], EXPECTED_INPUT_FEATURES, atol=1e-4)) + + def test_attention_mask(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_input1 = np.zeros([1_000_000], dtype=np.float32) + speech_input2 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32) + input_features = feature_extractor( + [speech_input1, speech_input2], + sampling_rate=[44_100, 16_000], + return_tensors="np", + return_attention_mask=True, + ) + + self.assertTrue(hasattr(input_features, "attention_mask")) + + # check shapes + self.assertTrue(input_features["attention_mask"].ndim == 2) + self.assertEqual(input_features["attention_mask_beatsteps"].shape[0], 2) + self.assertEqual(input_features["attention_mask_extrapolated_beatstep"].shape[0], 2) + + # check if they are any values except 0 and 1 + self.assertTrue(np.max(input_features["attention_mask"]) == 1) + self.assertTrue(np.max(input_features["attention_mask_beatsteps"]) == 1) + self.assertTrue(np.max(input_features["attention_mask_extrapolated_beatstep"]) == 1) + + self.assertTrue(np.min(input_features["attention_mask"]) == 0) + self.assertTrue(np.min(input_features["attention_mask_beatsteps"]) == 0) + self.assertTrue(np.min(input_features["attention_mask_extrapolated_beatstep"]) == 0) + + def test_batch_feature(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_input1 = np.zeros([1_000_000], dtype=np.float32) + speech_input2 = np.ones([2_000_000], dtype=np.float32) + speech_input3 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32) + + input_features = feature_extractor( + [speech_input1, speech_input2, speech_input3], + sampling_rate=[44_100, 16_000, 48_000], + return_attention_mask=True, + ) + + self.assertEqual(len(input_features["input_features"].shape), 3) + # check shape + self.assertEqual(input_features["beatsteps"].shape[0], 3) + self.assertEqual(input_features["extrapolated_beatstep"].shape[0], 3) + + def test_batch_feature_np(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_input1 = np.zeros([1_000_000], dtype=np.float32) + speech_input2 = np.ones([2_000_000], dtype=np.float32) + speech_input3 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32) + + input_features = feature_extractor( + [speech_input1, speech_input2, speech_input3], + sampling_rate=[44_100, 16_000, 48_000], + return_tensors="np", + return_attention_mask=True, + ) + + # check np array or not + self.assertEqual(type(input_features["input_features"]), np.ndarray) + + # check shape + self.assertEqual(len(input_features["input_features"].shape), 3) + + def test_batch_feature_pt(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_input1 = np.zeros([1_000_000], dtype=np.float32) + speech_input2 = np.ones([2_000_000], dtype=np.float32) + speech_input3 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32) + + input_features = feature_extractor( + [speech_input1, speech_input2, speech_input3], + sampling_rate=[44_100, 16_000, 48_000], + return_tensors="pt", + return_attention_mask=True, + ) + + # check pt tensor or not + self.assertEqual(type(input_features["input_features"]), torch.Tensor) + + # check shape + self.assertEqual(len(input_features["input_features"].shape), 3) + + @require_tf + def test_batch_feature_tf(self): + import tensorflow as tf + + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_input1 = np.zeros([1_000_000], dtype=np.float32) + speech_input2 = np.ones([2_000_000], dtype=np.float32) + speech_input3 = np.random.randint(low=0, high=10, size=500_000).astype(np.float32) + + input_features = feature_extractor( + [speech_input1, speech_input2, speech_input3], + sampling_rate=[44_100, 16_000, 48_000], + return_tensors="tf", + return_attention_mask=True, + ) + + # check tf tensor or not + self.assertTrue(tf.is_tensor(input_features["input_features"])) + + # check shape + self.assertEqual(len(input_features["input_features"].shape), 3) + + @unittest.skip( + "Pop2PianoFeatureExtractor does not supports padding externally (while processing audios in batches padding is automatically applied to max_length)" + ) + def test_padding_accepts_tensors_pt(self): + pass + + @unittest.skip( + "Pop2PianoFeatureExtractor does not supports padding externally (while processing audios in batches padding is automatically applied to max_length)" + ) + def test_padding_accepts_tensors_tf(self): + pass + + @unittest.skip( + "Pop2PianoFeatureExtractor does not supports padding externally (while processing audios in batches padding is automatically applied to max_length)" + ) + def test_padding_from_list(self): + pass + + @unittest.skip( + "Pop2PianoFeatureExtractor does not supports padding externally (while processing audios in batches padding is automatically applied to max_length)" + ) + def test_padding_from_array(self): + pass + + @unittest.skip("Pop2PianoFeatureExtractor does not support truncation") + def test_attention_mask_with_truncation(self): + pass + + @unittest.skip("Pop2PianoFeatureExtractor does not supports truncation") + def test_truncation_from_array(self): + pass + + @unittest.skip("Pop2PianoFeatureExtractor does not supports truncation") + def test_truncation_from_list(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_modeling_pop2piano.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_modeling_pop2piano.py new file mode 100644 index 0000000000000000000000000000000000000000..d19ddc10e153fcc8d2c7410bf30f3430763c7a11 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_modeling_pop2piano.py @@ -0,0 +1,782 @@ +# coding=utf-8 +# Copyright 2023 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 Pop2Piano model. """ + +import copy +import tempfile +import unittest + +import numpy as np +from datasets import load_dataset + +from transformers import Pop2PianoConfig +from transformers.feature_extraction_utils import BatchFeature +from transformers.testing_utils import ( + require_essentia, + require_librosa, + require_onnx, + require_scipy, + require_torch, + slow, + torch_device, +) +from transformers.utils import is_essentia_available, is_librosa_available, is_scipy_available, is_torch_available + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import Pop2PianoForConditionalGeneration + from transformers.models.pop2piano.modeling_pop2piano import POP2PIANO_PRETRAINED_MODEL_ARCHIVE_LIST + from transformers.pytorch_utils import is_torch_1_8_0 + +else: + is_torch_1_8_0 = False + + +@require_torch +class Pop2PianoModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + decoder_seq_length=9, + # For common tests + is_training=False, + use_attention_mask=True, + use_labels=True, + hidden_size=64, + num_hidden_layers=5, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + dropout_rate=0.1, + initializer_factor=0.002, + eos_token_id=1, + pad_token_id=0, + decoder_start_token_id=0, + scope=None, + decoder_layers=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.scope = None + self.decoder_layers = decoder_layers + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + attention_mask = None + decoder_attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2) + + lm_labels = ( + ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) if self.use_labels else None + ) + + return self.get_config(), input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels + + def get_pipeline_config(self): + return Pop2PianoConfig( + vocab_size=166, # Pop2Piano forces 100 extra tokens + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ) + + def get_config(self): + return Pop2PianoConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ) + + def check_prepare_lm_labels_via_shift_left( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = Pop2PianoForConditionalGeneration(config=config) + model.to(torch_device) + model.eval() + + # make sure that lm_labels are correctly padded from the right + lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id) + + # add causal pad token mask + triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not() + lm_labels.masked_fill_(triangular_mask, self.pad_token_id) + decoder_input_ids = model._shift_right(lm_labels) + + for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)): + # first item + self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id) + if i < decoder_input_ids_slice.shape[-1]: + if i < decoder_input_ids.shape[-1] - 1: + # items before diagonal + self.parent.assertListEqual( + decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist() + ) + # pad items after diagonal + if i < decoder_input_ids.shape[-1] - 2: + self.parent.assertListEqual( + decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist() + ) + else: + # all items after square + self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist()) + + def create_and_check_model( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = Pop2PianoForConditionalGeneration(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) + decoder_past = result.past_key_values + encoder_output = result.encoder_last_hidden_state + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size)) + # There should be `num_layers` key value embeddings stored in decoder_past + self.parent.assertEqual(len(decoder_past), config.num_layers) + # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple + self.parent.assertEqual(len(decoder_past[0]), 4) + + def create_and_check_with_lm_head( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = Pop2PianoForConditionalGeneration(config=config).to(torch_device).eval() + outputs = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + labels=lm_labels, + ) + self.parent.assertEqual(len(outputs), 4) + self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size)) + self.parent.assertEqual(outputs["loss"].size(), ()) + + def create_and_check_decoder_model_past( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = Pop2PianoForConditionalGeneration(config=config).get_decoder().to(torch_device).eval() + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_decoder_model_attention_mask_past( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = Pop2PianoForConditionalGeneration(config=config).get_decoder() + model.to(torch_device) + model.eval() + + # create attention mask + attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) + + half_seq_length = input_ids.shape[-1] // 2 + attn_mask[:, half_seq_length:] = 0 + + # first forward pass + output, past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True).to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1) + input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens + + # append to next input_ids and attn_mask + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + attn_mask = torch.cat( + [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)], + dim=1, + ) + + # get two different outputs + output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values, attention_mask=attn_mask)[ + "last_hidden_state" + ] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = Pop2PianoForConditionalGeneration(config=config).get_decoder().to(torch_device).eval() + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([attention_mask, next_mask], dim=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # 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)) + + def create_and_check_generate_with_past_key_values( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = Pop2PianoForConditionalGeneration(config=config).to(torch_device).eval() + torch.manual_seed(0) + output_without_past_cache = model.generate( + input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False + ) + torch.manual_seed(0) + output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True) + self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache)) + + def create_and_check_model_fp16_forward( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = Pop2PianoForConditionalGeneration(config=config).to(torch_device).half().eval() + output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)[ + "encoder_last_hidden_state" + ] + self.parent.assertFalse(torch.isnan(output).any().item()) + + def create_and_check_encoder_decoder_shared_weights( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + for model_class in [Pop2PianoForConditionalGeneration]: + torch.manual_seed(0) + model = model_class(config=config).to(torch_device).eval() + # load state dict copies weights but does not tie them + model.encoder.load_state_dict(model.decoder.state_dict(), strict=False) + + torch.manual_seed(0) + tied_config = copy.deepcopy(config) + tied_config.tie_encoder_decoder = True + tied_model = model_class(config=tied_config).to(torch_device).eval() + + model_result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + tied_model_result = tied_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + # check that models has less parameters + self.parent.assertLess( + sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters()) + ) + random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item() + + # check that outputs are equal + self.parent.assertTrue( + torch.allclose( + model_result[0][0, :, random_slice_idx], tied_model_result[0][0, :, random_slice_idx], atol=1e-4 + ) + ) + + # check that outputs after saving and loading are equal + with tempfile.TemporaryDirectory() as tmpdirname: + tied_model.save_pretrained(tmpdirname) + tied_model = model_class.from_pretrained(tmpdirname) + tied_model.to(torch_device) + tied_model.eval() + + # check that models has less parameters + self.parent.assertLess( + sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters()) + ) + random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item() + + tied_model_result = tied_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + # check that outputs are equal + self.parent.assertTrue( + torch.allclose( + model_result[0][0, :, random_slice_idx], + tied_model_result[0][0, :, random_slice_idx], + atol=1e-4, + ) + ) + + def check_resize_embeddings_pop2piano_v1_1( + self, + config, + ): + prev_vocab_size = config.vocab_size + + config.tie_word_embeddings = False + model = Pop2PianoForConditionalGeneration(config=config).to(torch_device).eval() + model.resize_token_embeddings(prev_vocab_size - 10) + + self.parent.assertEqual(model.get_input_embeddings().weight.shape[0], prev_vocab_size - 10) + self.parent.assertEqual(model.get_output_embeddings().weight.shape[0], prev_vocab_size - 10) + self.parent.assertEqual(model.config.vocab_size, prev_vocab_size - 10) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "use_cache": False, + } + return config, inputs_dict + + +@require_torch +class Pop2PianoModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (Pop2PianoForConditionalGeneration,) if is_torch_available() else () + all_generative_model_classes = () + pipeline_model_mapping = ( + {"automatic-speech-recognition": Pop2PianoForConditionalGeneration} if is_torch_available() else {} + ) + all_parallelizable_model_classes = () + fx_compatible = False + test_pruning = False + test_resize_embeddings = True + test_model_parallel = False + is_encoder_decoder = True + + def setUp(self): + self.model_tester = Pop2PianoModelTester(self) + self.config_tester = ConfigTester(self, config_class=Pop2PianoConfig, d_model=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_shift_right(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_v1_1(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + # check that gated gelu feed forward and different word embeddings work + config = config_and_inputs[0] + config.tie_word_embeddings = False + config.feed_forward_proj = "gated-gelu" + self.model_tester.create_and_check_model(config, *config_and_inputs[1:]) + + def test_config_and_model_silu_gated(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config = config_and_inputs[0] + config.feed_forward_proj = "gated-silu" + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_with_lm_head(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_with_lm_head(*config_and_inputs) + + def test_decoder_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_past(*config_and_inputs) + + def test_decoder_model_past_with_attn_mask(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs) + + def test_decoder_model_past_with_3d_attn_mask(self): + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = self.model_tester.prepare_config_and_inputs() + + attention_mask = ids_tensor( + [self.model_tester.batch_size, self.model_tester.encoder_seq_length, self.model_tester.encoder_seq_length], + vocab_size=2, + ) + decoder_attention_mask = ids_tensor( + [self.model_tester.batch_size, self.model_tester.decoder_seq_length, self.model_tester.decoder_seq_length], + vocab_size=2, + ) + + self.model_tester.create_and_check_decoder_model_attention_mask_past( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) + + 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_shared_weights(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs) + + @unittest.skipIf(torch_device == "cpu", "Cant do half precision") + def test_model_fp16_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs) + + def test_v1_1_resize_embeddings(self): + config = self.model_tester.prepare_config_and_inputs()[0] + self.model_tester.check_resize_embeddings_pop2piano_v1_1(config) + + @slow + def test_model_from_pretrained(self): + for model_name in POP2PIANO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = Pop2PianoForConditionalGeneration.from_pretrained(model_name) + self.assertIsNotNone(model) + + @require_onnx + @unittest.skipIf( + is_torch_1_8_0, + reason="Test has a segmentation fault on torch 1.8.0", + ) + def test_export_to_onnx(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + model = Pop2PianoForConditionalGeneration(config_and_inputs[0]).to(torch_device) + with tempfile.TemporaryDirectory() as tmpdirname: + torch.onnx.export( + model, + (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]), + f"{tmpdirname}/Pop2Piano_test.onnx", + export_params=True, + opset_version=9, + input_names=["input_ids", "decoder_input_ids"], + ) + + def test_pass_with_input_features(self): + input_features = BatchFeature( + { + "input_features": torch.rand((75, 100, 512)).type(torch.float32), + "beatsteps": torch.randint(size=(1, 955), low=0, high=100).type(torch.float32), + "extrapolated_beatstep": torch.randint(size=(1, 900), low=0, high=100).type(torch.float32), + } + ) + model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano") + model_opts = model.generate(input_features=input_features["input_features"], return_dict_in_generate=True) + + self.assertEqual(model_opts.sequences.ndim, 2) + + def test_pass_with_batched_input_features(self): + input_features = BatchFeature( + { + "input_features": torch.rand((220, 70, 512)).type(torch.float32), + "beatsteps": torch.randint(size=(5, 955), low=0, high=100).type(torch.float32), + "extrapolated_beatstep": torch.randint(size=(5, 900), low=0, high=100).type(torch.float32), + "attention_mask": torch.concatenate( + [ + torch.ones([120, 70], dtype=torch.int32), + torch.zeros([1, 70], dtype=torch.int32), + torch.ones([50, 70], dtype=torch.int32), + torch.zeros([1, 70], dtype=torch.int32), + torch.ones([47, 70], dtype=torch.int32), + torch.zeros([1, 70], dtype=torch.int32), + ], + axis=0, + ), + "attention_mask_beatsteps": torch.ones((5, 955)).type(torch.int32), + "attention_mask_extrapolated_beatstep": torch.ones((5, 900)).type(torch.int32), + } + ) + model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano") + model_opts = model.generate( + input_features=input_features["input_features"], + attention_mask=input_features["attention_mask"], + return_dict_in_generate=True, + ) + + self.assertEqual(model_opts.sequences.ndim, 2) + + +@require_torch +class Pop2PianoModelIntegrationTests(unittest.TestCase): + @slow + def test_mel_conditioner_integration(self): + composer = "composer1" + model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano") + input_embeds = torch.ones([10, 100, 512]) + + composer_value = model.generation_config.composer_to_feature_token[composer] + composer_value = torch.tensor(composer_value) + composer_value = composer_value.repeat(input_embeds.size(0)) + outputs = model.mel_conditioner( + input_embeds, composer_value, min(model.generation_config.composer_to_feature_token.values()) + ) + + # check shape + self.assertEqual(outputs.size(), torch.Size([10, 101, 512])) + + # check values + EXPECTED_OUTPUTS = torch.tensor( + [[1.0475305318832397, 0.29052114486694336, -0.47778210043907166], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] + ) + + self.assertTrue(torch.allclose(outputs[0, :3, :3], EXPECTED_OUTPUTS, atol=1e-4)) + + @slow + @require_essentia + @require_librosa + @require_scipy + def test_full_model_integration(self): + if is_librosa_available() and is_scipy_available() and is_essentia_available() and is_torch_available(): + from transformers import Pop2PianoProcessor + + speech_input1 = np.zeros([1_000_000], dtype=np.float32) + sampling_rate = 44_100 + + processor = Pop2PianoProcessor.from_pretrained("sweetcocoa/pop2piano") + input_features = processor.feature_extractor( + speech_input1, sampling_rate=sampling_rate, return_tensors="pt" + ) + + model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano") + outputs = model.generate( + input_features=input_features["input_features"], return_dict_in_generate=True + ).sequences + + # check for shapes + self.assertEqual(outputs.size(0), 70) + + # check for values + self.assertEqual(outputs[0, :2].detach().cpu().numpy().tolist(), [0, 1]) + + # This is the test for a real music from K-Pop genre. + @slow + @require_essentia + @require_librosa + @require_scipy + def test_real_music(self): + if is_librosa_available() and is_scipy_available() and is_essentia_available() and is_torch_available(): + from transformers import Pop2PianoFeatureExtractor, Pop2PianoTokenizer + + model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano") + model.eval() + feature_extractor = Pop2PianoFeatureExtractor.from_pretrained("sweetcocoa/pop2piano") + tokenizer = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano") + ds = load_dataset("sweetcocoa/pop2piano_ci", split="test") + + output_fe = feature_extractor( + ds["audio"][0]["array"], sampling_rate=ds["audio"][0]["sampling_rate"], return_tensors="pt" + ) + output_model = model.generate(input_features=output_fe["input_features"], composer="composer1") + output_tokenizer = tokenizer.batch_decode(token_ids=output_model, feature_extractor_output=output_fe) + pretty_midi_object = output_tokenizer["pretty_midi_objects"][0] + + # Checking if no of notes are same + self.assertEqual(len(pretty_midi_object.instruments[0].notes), 59) + predicted_timings = [] + for i in pretty_midi_object.instruments[0].notes: + predicted_timings.append(i.start) + + # Checking note start timings(first 6) + EXPECTED_START_TIMINGS = [ + 0.4876190423965454, + 0.7314285635948181, + 0.9752380847930908, + 1.4396371841430664, + 1.6718367338180542, + 1.904036283493042, + ] + + np.allclose(EXPECTED_START_TIMINGS, predicted_timings[:6]) + + # Checking note end timings(last 6) + EXPECTED_END_TIMINGS = [ + 12.341403007507324, + 12.567797183990479, + 12.567797183990479, + 12.567797183990479, + 12.794191360473633, + 12.794191360473633, + ] + + np.allclose(EXPECTED_END_TIMINGS, predicted_timings[-6:]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_processor_pop2piano.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_processor_pop2piano.py new file mode 100644 index 0000000000000000000000000000000000000000..06a8bacfd8a45cc8dcdd867c9209d4efd4dd8f10 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_processor_pop2piano.py @@ -0,0 +1,264 @@ +# Copyright 2023 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 shutil +import tempfile +import unittest + +import numpy as np +import pytest +from datasets import load_dataset + +from transformers.testing_utils import ( + require_essentia, + require_librosa, + require_pretty_midi, + require_scipy, + require_torch, +) +from transformers.tokenization_utils import BatchEncoding +from transformers.utils.import_utils import ( + is_essentia_available, + is_librosa_available, + is_pretty_midi_available, + is_scipy_available, + is_torch_available, +) + + +requirements_available = ( + is_torch_available() + and is_essentia_available() + and is_scipy_available() + and is_librosa_available() + and is_pretty_midi_available() +) + +if requirements_available: + import pretty_midi + + from transformers import ( + Pop2PianoFeatureExtractor, + Pop2PianoForConditionalGeneration, + Pop2PianoProcessor, + Pop2PianoTokenizer, + ) + + +@require_scipy +@require_torch +@require_librosa +@require_essentia +@require_pretty_midi +class Pop2PianoProcessorTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + feature_extractor = Pop2PianoFeatureExtractor.from_pretrained("sweetcocoa/pop2piano") + tokenizer = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano") + processor = Pop2PianoProcessor(feature_extractor, tokenizer) + + processor.save_pretrained(self.tmpdirname) + + def get_tokenizer(self, **kwargs): + return Pop2PianoTokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def get_feature_extractor(self, **kwargs): + return Pop2PianoFeatureExtractor.from_pretrained(self.tmpdirname, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_save_load_pretrained_additional_features(self): + processor = Pop2PianoProcessor( + tokenizer=self.get_tokenizer(), + feature_extractor=self.get_feature_extractor(), + ) + processor.save_pretrained(self.tmpdirname) + + tokenizer_add_kwargs = self.get_tokenizer( + unk_token="-1", + eos_token="1", + pad_token="0", + bos_token="2", + ) + feature_extractor_add_kwargs = self.get_feature_extractor() + + processor = Pop2PianoProcessor.from_pretrained( + self.tmpdirname, + unk_token="-1", + eos_token="1", + pad_token="0", + bos_token="2", + ) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) + self.assertIsInstance(processor.tokenizer, Pop2PianoTokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.feature_extractor, Pop2PianoFeatureExtractor) + + def get_inputs(self): + """get inputs for both feature extractor and tokenizer""" + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + speech_samples = ds.sort("id").select([0])["audio"] + input_speech = [x["array"] for x in speech_samples][0] + sampling_rate = [x["sampling_rate"] for x in speech_samples][0] + + feature_extractor_outputs = self.get_feature_extractor()( + audio=input_speech, sampling_rate=sampling_rate, return_tensors="pt" + ) + model = Pop2PianoForConditionalGeneration.from_pretrained("sweetcocoa/pop2piano") + token_ids = model.generate(input_features=feature_extractor_outputs["input_features"], composer="composer1") + dummy_notes = [ + [ + pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77), + pretty_midi.Note(start=0.673379, end=0.905578, pitch=73, velocity=77), + pretty_midi.Note(start=0.905578, end=2.159456, pitch=73, velocity=77), + pretty_midi.Note(start=1.114558, end=2.159456, pitch=78, velocity=77), + pretty_midi.Note(start=1.323537, end=1.532517, pitch=80, velocity=77), + ], + [ + pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77), + ], + ] + + return input_speech, sampling_rate, token_ids, dummy_notes + + def test_feature_extractor(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Pop2PianoProcessor( + tokenizer=tokenizer, + feature_extractor=feature_extractor, + ) + + input_speech, sampling_rate, _, _ = self.get_inputs() + + feature_extractor_outputs = feature_extractor( + audio=input_speech, sampling_rate=sampling_rate, return_tensors="np" + ) + processor_outputs = processor(audio=input_speech, sampling_rate=sampling_rate, return_tensors="np") + + for key in feature_extractor_outputs.keys(): + self.assertTrue(np.allclose(feature_extractor_outputs[key], processor_outputs[key], atol=1e-4)) + + def test_processor_batch_decode(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Pop2PianoProcessor( + tokenizer=tokenizer, + feature_extractor=feature_extractor, + ) + + audio, sampling_rate, token_ids, _ = self.get_inputs() + feature_extractor_output = feature_extractor(audio=audio, sampling_rate=sampling_rate, return_tensors="pt") + + encoded_processor = processor.batch_decode( + token_ids=token_ids, + feature_extractor_output=feature_extractor_output, + return_midi=True, + ) + + encoded_tokenizer = tokenizer.batch_decode( + token_ids=token_ids, + feature_extractor_output=feature_extractor_output, + return_midi=True, + ) + # check start timings + encoded_processor_start_timings = [token.start for token in encoded_processor["notes"]] + encoded_tokenizer_start_timings = [token.start for token in encoded_tokenizer["notes"]] + self.assertListEqual(encoded_processor_start_timings, encoded_tokenizer_start_timings) + + # check end timings + encoded_processor_end_timings = [token.end for token in encoded_processor["notes"]] + encoded_tokenizer_end_timings = [token.end for token in encoded_tokenizer["notes"]] + self.assertListEqual(encoded_processor_end_timings, encoded_tokenizer_end_timings) + + # check pitch + encoded_processor_pitch = [token.pitch for token in encoded_processor["notes"]] + encoded_tokenizer_pitch = [token.pitch for token in encoded_tokenizer["notes"]] + self.assertListEqual(encoded_processor_pitch, encoded_tokenizer_pitch) + + # check velocity + encoded_processor_velocity = [token.velocity for token in encoded_processor["notes"]] + encoded_tokenizer_velocity = [token.velocity for token in encoded_tokenizer["notes"]] + self.assertListEqual(encoded_processor_velocity, encoded_tokenizer_velocity) + + def test_tokenizer_call(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Pop2PianoProcessor( + tokenizer=tokenizer, + feature_extractor=feature_extractor, + ) + + _, _, _, notes = self.get_inputs() + + encoded_processor = processor( + notes=notes, + ) + + self.assertTrue(isinstance(encoded_processor, BatchEncoding)) + + def test_processor(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Pop2PianoProcessor( + tokenizer=tokenizer, + feature_extractor=feature_extractor, + ) + + audio, sampling_rate, _, notes = self.get_inputs() + + inputs = processor( + audio=audio, + sampling_rate=sampling_rate, + notes=notes, + ) + + self.assertListEqual( + list(inputs.keys()), + ["input_features", "beatsteps", "extrapolated_beatstep", "token_ids"], + ) + + # test if it raises when no input is passed + with pytest.raises(ValueError): + processor() + + def test_model_input_names(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Pop2PianoProcessor( + tokenizer=tokenizer, + feature_extractor=feature_extractor, + ) + + audio, sampling_rate, _, notes = self.get_inputs() + feature_extractor(audio, sampling_rate, return_tensors="pt") + + inputs = processor( + audio=audio, + sampling_rate=sampling_rate, + notes=notes, + ) + self.assertListEqual( + list(inputs.keys()), + ["input_features", "beatsteps", "extrapolated_beatstep", "token_ids"], + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_tokenization_pop2piano.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_tokenization_pop2piano.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5301b8f3bfbfb55c8975d8d9e94c3ea86b208c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pop2piano/test_tokenization_pop2piano.py @@ -0,0 +1,415 @@ +# coding=utf-8 +# Copyright 2023 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. +""" +Please note that Pop2PianoTokenizer is too far from our usual tokenizers and thus cannot use the TokenizerTesterMixin class. +""" + +import os +import pickle +import shutil +import tempfile +import unittest + +from transformers.feature_extraction_utils import BatchFeature +from transformers.testing_utils import ( + is_pretty_midi_available, + is_torch_available, + require_pretty_midi, + require_torch, +) +from transformers.tokenization_utils import BatchEncoding + + +if is_torch_available(): + import torch + + +requirements_available = is_torch_available() and is_pretty_midi_available() +if requirements_available: + import pretty_midi + + from transformers import Pop2PianoTokenizer + + +@require_torch +@require_pretty_midi +class Pop2PianoTokenizerTest(unittest.TestCase): + def setUp(self): + super().setUp() + self.tokenizer = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano") + + def get_input_notes(self): + notes = [ + [ + pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77), + pretty_midi.Note(start=0.673379, end=0.905578, pitch=73, velocity=77), + pretty_midi.Note(start=0.905578, end=2.159456, pitch=73, velocity=77), + pretty_midi.Note(start=1.114558, end=2.159456, pitch=78, velocity=77), + pretty_midi.Note(start=1.323537, end=1.532517, pitch=80, velocity=77), + ], + [ + pretty_midi.Note(start=0.441179, end=2.159456, pitch=70, velocity=77), + ], + ] + + return notes + + def test_call(self): + notes = self.get_input_notes() + + output = self.tokenizer( + notes, + return_tensors="pt", + padding="max_length", + truncation=True, + max_length=10, + return_attention_mask=True, + ) + + # check the output type + self.assertTrue(isinstance(output, BatchEncoding)) + + # check the values + expected_output_token_ids = torch.tensor( + [[134, 133, 74, 135, 77, 132, 77, 133, 77, 82], [134, 133, 74, 136, 132, 74, 134, 134, 134, 134]] + ) + expected_output_attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]]) + + self.assertTrue(torch.allclose(output["token_ids"], expected_output_token_ids, atol=1e-4)) + self.assertTrue(torch.allclose(output["attention_mask"], expected_output_attention_mask, atol=1e-4)) + + def test_batch_decode(self): + # test batch decode with model, feature-extractor outputs(beatsteps, extrapolated_beatstep) + + # Please note that this test does not test the accuracy of the outputs, instead it is designed to make sure that + # the tokenizer's batch_decode can deal with attention_mask in feature-extractor outputs. For the accuracy check + # please see the `test_batch_decode_outputs` test. + + model_output = torch.concatenate( + [ + torch.randint(size=[120, 96], low=0, high=70, dtype=torch.long), + torch.zeros(size=[1, 96], dtype=torch.long), + torch.randint(size=[50, 96], low=0, high=40, dtype=torch.long), + torch.zeros(size=[1, 96], dtype=torch.long), + ], + axis=0, + ) + input_features = BatchFeature( + { + "beatsteps": torch.ones([2, 955]), + "extrapolated_beatstep": torch.ones([2, 1000]), + "attention_mask": torch.concatenate( + [ + torch.ones([120, 96], dtype=torch.long), + torch.zeros([1, 96], dtype=torch.long), + torch.ones([50, 96], dtype=torch.long), + torch.zeros([1, 96], dtype=torch.long), + ], + axis=0, + ), + "attention_mask_beatsteps": torch.ones([2, 955]), + "attention_mask_extrapolated_beatstep": torch.ones([2, 1000]), + } + ) + + output = self.tokenizer.batch_decode(token_ids=model_output, feature_extractor_output=input_features)[ + "pretty_midi_objects" + ] + + # check length + self.assertTrue(len(output) == 2) + + # check object type + self.assertTrue(isinstance(output[0], pretty_midi.pretty_midi.PrettyMIDI)) + self.assertTrue(isinstance(output[1], pretty_midi.pretty_midi.PrettyMIDI)) + + def test_batch_decode_outputs(self): + # test batch decode with model, feature-extractor outputs(beatsteps, extrapolated_beatstep) + + # Please note that this test tests the accuracy of the outputs of the tokenizer's `batch_decode` method. + + model_output = torch.tensor( + [ + [134, 133, 74, 135, 77, 82, 84, 136, 132, 74, 77, 82, 84], + [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], + ] + ) + input_features = BatchEncoding( + { + "beatsteps": torch.tensor([[0.0697, 0.1103, 0.1509, 0.1916]]), + "extrapolated_beatstep": torch.tensor([[0.0000, 0.0406, 0.0813, 0.1219]]), + } + ) + + output = self.tokenizer.batch_decode(token_ids=model_output, feature_extractor_output=input_features) + + # check outputs + self.assertEqual(len(output["notes"]), 4) + + predicted_start_timings, predicted_end_timings = [], [] + for i in output["notes"]: + predicted_start_timings.append(i.start) + predicted_end_timings.append(i.end) + + # Checking note start timings + expected_start_timings = torch.tensor( + [ + 0.069700, + 0.110300, + 0.110300, + 0.110300, + ] + ) + predicted_start_timings = torch.tensor(predicted_start_timings) + + self.assertTrue(torch.allclose(expected_start_timings, predicted_start_timings, atol=1e-4)) + + # Checking note end timings + expected_end_timings = torch.tensor( + [ + 0.191600, + 0.191600, + 0.191600, + 0.191600, + ] + ) + predicted_end_timings = torch.tensor(predicted_end_timings) + + self.assertTrue(torch.allclose(expected_end_timings, predicted_end_timings, atol=1e-4)) + + def test_get_vocab(self): + vocab_dict = self.tokenizer.get_vocab() + self.assertIsInstance(vocab_dict, dict) + self.assertGreaterEqual(len(self.tokenizer), len(vocab_dict)) + + vocab = [self.tokenizer.convert_ids_to_tokens(i) for i in range(len(self.tokenizer))] + self.assertEqual(len(vocab), len(self.tokenizer)) + + self.tokenizer.add_tokens(["asdfasdfasdfasdf"]) + vocab = [self.tokenizer.convert_ids_to_tokens(i) for i in range(len(self.tokenizer))] + self.assertEqual(len(vocab), len(self.tokenizer)) + + def test_save_and_load_tokenizer(self): + tmpdirname = tempfile.mkdtemp() + + sample_notes = self.get_input_notes() + + self.tokenizer.add_tokens(["bim", "bambam"]) + additional_special_tokens = self.tokenizer.additional_special_tokens + additional_special_tokens.append("new_additional_special_token") + self.tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens}) + before_token_ids = self.tokenizer(sample_notes)["token_ids"] + before_vocab = self.tokenizer.get_vocab() + self.tokenizer.save_pretrained(tmpdirname) + + after_tokenizer = self.tokenizer.__class__.from_pretrained(tmpdirname) + after_token_ids = after_tokenizer(sample_notes)["token_ids"] + after_vocab = after_tokenizer.get_vocab() + self.assertDictEqual(before_vocab, after_vocab) + self.assertListEqual(before_token_ids, after_token_ids) + self.assertIn("bim", after_vocab) + self.assertIn("bambam", after_vocab) + self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens) + + shutil.rmtree(tmpdirname) + + def test_pickle_tokenizer(self): + tmpdirname = tempfile.mkdtemp() + + notes = self.get_input_notes() + subwords = self.tokenizer(notes)["token_ids"] + + filename = os.path.join(tmpdirname, "tokenizer.bin") + with open(filename, "wb") as handle: + pickle.dump(self.tokenizer, handle) + + with open(filename, "rb") as handle: + tokenizer_new = pickle.load(handle) + + subwords_loaded = tokenizer_new(notes)["token_ids"] + + self.assertListEqual(subwords, subwords_loaded) + + def test_padding_side_in_kwargs(self): + tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", padding_side="left") + self.assertEqual(tokenizer_p.padding_side, "left") + + tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", padding_side="right") + self.assertEqual(tokenizer_p.padding_side, "right") + + self.assertRaises( + ValueError, + Pop2PianoTokenizer.from_pretrained, + "sweetcocoa/pop2piano", + padding_side="unauthorized", + ) + + def test_truncation_side_in_kwargs(self): + tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", truncation_side="left") + self.assertEqual(tokenizer_p.truncation_side, "left") + + tokenizer_p = Pop2PianoTokenizer.from_pretrained("sweetcocoa/pop2piano", truncation_side="right") + self.assertEqual(tokenizer_p.truncation_side, "right") + + self.assertRaises( + ValueError, + Pop2PianoTokenizer.from_pretrained, + "sweetcocoa/pop2piano", + truncation_side="unauthorized", + ) + + def test_right_and_left_padding(self): + tokenizer = self.tokenizer + notes = self.get_input_notes() + notes = notes[0] + max_length = 20 + + padding_idx = tokenizer.pad_token_id + + # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "right" + padded_notes = tokenizer(notes, padding="max_length", max_length=max_length)["token_ids"] + padded_notes_length = len(padded_notes) + notes_without_padding = tokenizer(notes, padding="do_not_pad")["token_ids"] + padding_size = max_length - len(notes_without_padding) + + self.assertEqual(padded_notes_length, max_length) + self.assertEqual(notes_without_padding + [padding_idx] * padding_size, padded_notes) + + # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "left" + padded_notes = tokenizer(notes, padding="max_length", max_length=max_length)["token_ids"] + padded_notes_length = len(padded_notes) + notes_without_padding = tokenizer(notes, padding="do_not_pad")["token_ids"] + padding_size = max_length - len(notes_without_padding) + + self.assertEqual(padded_notes_length, max_length) + self.assertEqual([padding_idx] * padding_size + notes_without_padding, padded_notes) + + # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding' + notes_without_padding = tokenizer(notes)["token_ids"] + + tokenizer.padding_side = "right" + padded_notes_right = tokenizer(notes, padding=False)["token_ids"] + self.assertEqual(len(padded_notes_right), len(notes_without_padding)) + self.assertEqual(padded_notes_right, notes_without_padding) + + tokenizer.padding_side = "left" + padded_notes_left = tokenizer(notes, padding="longest")["token_ids"] + self.assertEqual(len(padded_notes_left), len(notes_without_padding)) + self.assertEqual(padded_notes_left, notes_without_padding) + + tokenizer.padding_side = "right" + padded_notes_right = tokenizer(notes, padding="longest")["token_ids"] + self.assertEqual(len(padded_notes_right), len(notes_without_padding)) + self.assertEqual(padded_notes_right, notes_without_padding) + + tokenizer.padding_side = "left" + padded_notes_left = tokenizer(notes, padding=False)["token_ids"] + self.assertEqual(len(padded_notes_left), len(notes_without_padding)) + self.assertEqual(padded_notes_left, notes_without_padding) + + def test_right_and_left_truncation(self): + tokenizer = self.tokenizer + notes = self.get_input_notes() + notes = notes[0] + truncation_size = 3 + + # RIGHT TRUNCATION - Check that it correctly truncates when a maximum length is specified along with the truncation flag set to True + tokenizer.truncation_side = "right" + full_encoded_notes = tokenizer(notes)["token_ids"] + full_encoded_notes_length = len(full_encoded_notes) + truncated_notes = tokenizer(notes, max_length=full_encoded_notes_length - truncation_size, truncation=True)[ + "token_ids" + ] + self.assertEqual(full_encoded_notes_length, len(truncated_notes) + truncation_size) + self.assertEqual(full_encoded_notes[:-truncation_size], truncated_notes) + + # LEFT TRUNCATION - Check that it correctly truncates when a maximum length is specified along with the truncation flag set to True + tokenizer.truncation_side = "left" + full_encoded_notes = tokenizer(notes)["token_ids"] + full_encoded_notes_length = len(full_encoded_notes) + truncated_notes = tokenizer(notes, max_length=full_encoded_notes_length - truncation_size, truncation=True)[ + "token_ids" + ] + self.assertEqual(full_encoded_notes_length, len(truncated_notes) + truncation_size) + self.assertEqual(full_encoded_notes[truncation_size:], truncated_notes) + + # RIGHT & LEFT TRUNCATION - Check that nothing is done for 'longest' and 'no_truncation' + tokenizer.truncation_side = "right" + truncated_notes_right = tokenizer(notes, truncation=True)["token_ids"] + self.assertEqual(full_encoded_notes_length, len(truncated_notes_right)) + self.assertEqual(full_encoded_notes, truncated_notes_right) + + tokenizer.truncation_side = "left" + truncated_notes_left = tokenizer(notes, truncation="longest_first")["token_ids"] + self.assertEqual(len(truncated_notes_left), full_encoded_notes_length) + self.assertEqual(truncated_notes_left, full_encoded_notes) + + tokenizer.truncation_side = "right" + truncated_notes_right = tokenizer(notes, truncation="longest_first")["token_ids"] + self.assertEqual(len(truncated_notes_right), full_encoded_notes_length) + self.assertEqual(truncated_notes_right, full_encoded_notes) + + tokenizer.truncation_side = "left" + truncated_notes_left = tokenizer(notes, truncation=True)["token_ids"] + self.assertEqual(len(truncated_notes_left), full_encoded_notes_length) + self.assertEqual(truncated_notes_left, full_encoded_notes) + + def test_padding_to_multiple_of(self): + notes = self.get_input_notes() + + if self.tokenizer.pad_token is None: + self.skipTest("No padding token.") + else: + normal_tokens = self.tokenizer(notes[0], padding=True, pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + normal_tokens = self.tokenizer(notes[0], pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # Should also work with truncation + normal_tokens = self.tokenizer(notes[0], padding=True, truncation=True, pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # truncation to something which is not a multiple of pad_to_multiple_of raises an error + self.assertRaises( + ValueError, + self.tokenizer.__call__, + notes[0], + padding=True, + truncation=True, + max_length=12, + pad_to_multiple_of=8, + ) + + def test_padding_with_attention_mask(self): + if self.tokenizer.pad_token is None: + self.skipTest("No padding token.") + if "attention_mask" not in self.tokenizer.model_input_names: + self.skipTest("This model does not use attention mask.") + + features = [ + {"token_ids": [1, 2, 3, 4, 5, 6], "attention_mask": [1, 1, 1, 1, 1, 0]}, + {"token_ids": [1, 2, 3], "attention_mask": [1, 1, 0]}, + ] + padded_features = self.tokenizer.pad(features) + if self.tokenizer.padding_side == "right": + self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0]]) + else: + self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0]]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_modeling_prophetnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_modeling_prophetnet.py new file mode 100644 index 0000000000000000000000000000000000000000..eee03134d34ea519e104ff9513901f670eb56882 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_modeling_prophetnet.py @@ -0,0 +1,1332 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team, The Microsoft Research team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import tempfile +import unittest + +from transformers import ProphetNetConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + ProphetNetDecoder, + ProphetNetEncoder, + ProphetNetForCausalLM, + ProphetNetForConditionalGeneration, + ProphetNetModel, + ProphetNetTokenizer, + ) + from transformers.modeling_outputs import BaseModelOutput + + +class ProphetNetModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + hidden_size=16, + encoder_seq_length=7, + decoder_seq_length=9, + # For common tests + is_training=True, + use_attention_mask=True, + use_labels=True, + decoder_start_token_id=0, + encoder_ffn_dim=32, + num_encoder_layers=2, + num_encoder_attention_heads=4, + decoder_ffn_dim=32, + num_decoder_layers=2, + num_decoder_attention_heads=4, + max_position_embeddings=30, + is_encoder_decoder=True, + pad_token_id=0, + bos_token_id=1, + eos_token_id=2, + ngram=2, + num_buckets=32, + relative_max_distance=128, + disable_ngram_loss=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_labels = use_labels + + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.num_hidden_layers = num_decoder_layers + self.num_encoder_layers = num_encoder_layers + self.num_decoder_layers = num_decoder_layers + self.decoder_ffn_dim = decoder_ffn_dim + self.encoder_ffn_dim = encoder_ffn_dim + self.num_attention_heads = num_decoder_attention_heads + self.num_encoder_attention_heads = num_encoder_attention_heads + self.num_decoder_attention_heads = num_decoder_attention_heads + self.eos_token_id = eos_token_id + self.bos_token_id = bos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.ngram = ngram + self.num_buckets = num_buckets + self.relative_max_distance = relative_max_distance + self.disable_ngram_loss = disable_ngram_loss + self.max_position_embeddings = max_position_embeddings + self.is_encoder_decoder = is_encoder_decoder + + self.scope = None + self.decoder_key_length = decoder_seq_length + self.base_model_out_len = 7 + self.num_hidden_states_types = 3 # encoder, decoder_main, decoder_ngram + self.decoder_attention_idx = 2 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + attention_mask = None + decoder_attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2) + + lm_labels = None + if self.use_labels: + lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + config = self.get_config() + + return ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) + + def get_config(self): + return ProphetNetConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_encoder_layers=self.num_encoder_layers, + num_decoder_layers=self.num_decoder_layers, + decoder_ffn_dim=self.decoder_ffn_dim, + encoder_ffn_dim=self.encoder_ffn_dim, + num_encoder_attention_heads=self.num_encoder_attention_heads, + num_decoder_attention_heads=self.num_decoder_attention_heads, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ngram=self.ngram, + num_buckets=self.num_buckets, + relative_max_distance=self.relative_max_distance, + disable_ngram_loss=self.disable_ngram_loss, + max_position_embeddings=self.max_position_embeddings, + is_encoder_decoder=self.is_encoder_decoder, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = self.prepare_config_and_inputs() + + encoder_hidden_states = floats_tensor([self.batch_size, self.encoder_seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + + return ( + config, + decoder_input_ids, + decoder_attention_mask, + encoder_hidden_states, + encoder_attention_mask, + lm_labels, + ) + + def check_prepare_lm_labels_via_shift_left( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = ProphetNetModel(config=config) + model.to(torch_device) + model.eval() + + # make sure that lm_labels are correctly padded from the right + lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id) + + # add casaul pad token mask + triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not() + lm_labels.masked_fill_(triangular_mask, self.pad_token_id) + decoder_input_ids = model._shift_right(lm_labels) + + for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)): + # first item + self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id) + if i < decoder_input_ids_slice.shape[-1]: + if i < decoder_input_ids.shape[-1] - 1: + # items before diagonal + self.parent.assertListEqual( + decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist() + ) + # pad items after diagonal + if i < decoder_input_ids.shape[-1] - 2: + self.parent.assertListEqual( + decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist() + ) + else: + # all items after square + self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist()) + + def create_and_check_model( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = ProphetNetModel(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) + decoder_output = result.last_hidden_state + decoder_past = result.past_key_values + encoder_output = result.encoder_last_hidden_state + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size)) + self.parent.assertEqual(decoder_output.size(), (self.batch_size, self.decoder_seq_length, self.hidden_size)) + # There should be `num_layers` key value embeddings stored in decoder_past + self.parent.assertEqual(len(decoder_past), config.num_decoder_layers) + # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple + self.parent.assertEqual(len(decoder_past[0]), 4) # cross-attention + uni-directional self-attention + + def create_and_check_with_lm_head( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = ProphetNetForConditionalGeneration(config=config).to(torch_device).eval() + outputs = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + labels=lm_labels, + ) + self.parent.assertEqual(len(outputs), 5) + self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size)) + self.parent.assertEqual(outputs["loss"].size(), ()) + + def create_and_check_causal_lm_decoder( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = ProphetNetForCausalLM(config=config).to(torch_device).eval() + outputs = model( + input_ids=decoder_input_ids, + attention_mask=decoder_attention_mask, + labels=lm_labels, + ) + self.parent.assertEqual(len(outputs), 4) + self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size)) + self.parent.assertEqual(outputs["loss"].size(), ()) + + def create_and_check_generate_with_past_key_value_states( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = ProphetNetForConditionalGeneration(config=config).to(torch_device).eval() + torch.manual_seed(0) + output_without_past_cache = model.generate( + input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False + ) + torch.manual_seed(0) + output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True) + self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache)) + + def create_and_check_decoder_generate_with_past_key_value_states( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = ProphetNetForCausalLM(config=config).to(torch_device).eval() + torch.manual_seed(0) + output_without_past_cache = model.generate( + input_ids[:1], num_beams=2, max_length=10, do_sample=True, use_cache=False + ) + torch.manual_seed(0) + output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=10, do_sample=True) + self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache)) + + def create_and_check_model_fp16_forward( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = ProphetNetModel(config=config).to(torch_device).half().eval() + output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)["last_hidden_state"] + self.parent.assertFalse(torch.isnan(output).any().item()) + + def create_and_check_encoder_decoder_shared_weights( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + for model_class in [ProphetNetModel, ProphetNetForConditionalGeneration]: + torch.manual_seed(0) + model = model_class(config=config).to(torch_device).eval() + # load state dict copies weights but does not tie them + + if model_class == ProphetNetForConditionalGeneration: + model.prophetnet.encoder.load_state_dict(model.prophetnet.decoder.state_dict(), strict=False) + else: + model.encoder.load_state_dict(model.decoder.state_dict(), strict=False) + + torch.manual_seed(0) + tied_config = copy.deepcopy(config) + tied_config.tie_encoder_decoder = True + tied_model = model_class(config=tied_config).to(torch_device).eval() + + model_result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + tied_model_result = tied_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + # check that models has less parameters + self.parent.assertLess( + sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters()) + ) + random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item() + + # check that outputs are equal + self.parent.assertTrue( + torch.allclose( + model_result[0][0, :, random_slice_idx], tied_model_result[0][0, :, random_slice_idx], atol=1e-4 + ) + ) + + # check that outputs after saving and loading are equal + with tempfile.TemporaryDirectory() as tmpdirname: + tied_model.save_pretrained(tmpdirname) + tied_model = model_class.from_pretrained(tmpdirname) + tied_model.to(torch_device) + tied_model.eval() + + # check that models has less parameters + self.parent.assertLess( + sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters()) + ) + random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item() + + tied_model_result = tied_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + # check that outputs are equal + self.parent.assertTrue( + torch.allclose( + model_result[0][0, :, random_slice_idx], + tied_model_result[0][0, :, random_slice_idx], + atol=1e-4, + ) + ) + + def check_fast_integration( + self, + config, + *args, + ): + input_ids = torch.tensor([[7, 4, 78, 0, 24, 52, 43]], device=torch_device, dtype=torch.long) + decoder_input_ids = torch.tensor([[12, 62, 25, 11, 47, 15, 14]], device=torch_device, dtype=torch.long) + attention_mask = torch.tensor([[1, 1, 1, 0, 1, 0, 0]], device=torch_device, dtype=torch.long) + decoder_attention_mask = torch.tensor([[1, 1, 1, 0, 0, 1, 0]], device=torch_device, dtype=torch.long) + lm_labels = torch.tensor([[62, 25, 11, 47, 15, 14, 24]], device=torch_device, dtype=torch.long) + torch.manual_seed(0) + config.ngram = 4 + model = ProphetNetForConditionalGeneration(config=config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + labels=lm_labels, + ) + self.parent.assertTrue(torch.allclose(result.loss, torch.tensor(4.5892, device=torch_device), atol=1e-3)) + + expected_logit_slice = torch.tensor( + [-0.0184, 0.0758, -0.0543, -0.0093, 0.0050, -0.0660, -0.1453], device=torch_device + ) + self.parent.assertTrue(torch.allclose(result.logits[0, :, 1], expected_logit_slice, atol=1e-3)) + + def check_model_with_attn_mask(self, config, input_ids, decoder_input_ids, *args): + model = ProphetNetModel(config=config) + model.to(torch_device) + model.eval() + + outputs_no_mask = model(input_ids=input_ids[:, :5], decoder_input_ids=decoder_input_ids[:, :5]) + attention_mask = torch.ones_like(input_ids) + decoder_attention_mask = torch.ones_like(decoder_input_ids) + + attention_mask[:, 5:] = 0 + + outputs_with_mask = model( + input_ids=input_ids, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + # check encoder + self.parent.assertTrue( + torch.allclose( + outputs_no_mask.encoder_last_hidden_state[0, :, 0], + outputs_with_mask.encoder_last_hidden_state[0, :5, 0], + atol=1e-3, + ) + ) + + # check decoder + # main stream + self.parent.assertTrue( + torch.allclose( + outputs_no_mask.last_hidden_state[0, :, 0], outputs_with_mask.last_hidden_state[0, :5, 0], atol=1e-3 + ) + ) + # predict stream + self.parent.assertTrue( + torch.allclose( + outputs_no_mask.last_hidden_state_ngram[0, :5, 0], + outputs_with_mask.last_hidden_state_ngram[0, :5, 0], + atol=1e-2, + ) + ) + + def check_causal_lm_from_pretrained( + self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, *args + ): + model = ProphetNetForConditionalGeneration(config).to(torch_device).eval() + + with tempfile.TemporaryDirectory() as tmp_dirname: + model.save_pretrained(tmp_dirname) + decoder = ProphetNetForCausalLM.from_pretrained(tmp_dirname).to(torch_device) + + encoder_hidden_states = model.prophetnet.encoder(input_ids).last_hidden_state + + model_outputs = model( + encoder_outputs=BaseModelOutput(last_hidden_state=encoder_hidden_states), + decoder_input_ids=decoder_input_ids, + ) + dec_outputs = decoder(encoder_hidden_states=encoder_hidden_states, input_ids=decoder_input_ids) + + self.parent.assertTrue( + torch.allclose( + model_outputs.logits[0, :5], + dec_outputs.logits[0, :5], + atol=1e-3, + ) + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "use_cache": False, + } + return config, inputs_dict + + +class ProphetNetStandaloneDecoderModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + hidden_size=16, + encoder_seq_length=7, + decoder_seq_length=7, + # For common tests + is_training=True, + is_decoder=True, + use_attention_mask=True, + add_cross_attention=False, + use_cache=False, + use_labels=True, + decoder_start_token_id=0, + encoder_ffn_dim=32, + num_encoder_layers=2, + num_encoder_attention_heads=4, + decoder_ffn_dim=32, + num_decoder_layers=2, + num_decoder_attention_heads=4, + max_position_embeddings=30, + is_encoder_decoder=False, + pad_token_id=0, + bos_token_id=1, + eos_token_id=2, + ngram=2, + num_buckets=32, + relative_max_distance=128, + disable_ngram_loss=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_labels = use_labels + + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.num_hidden_layers = num_decoder_layers + self.num_encoder_layers = num_encoder_layers + self.num_decoder_layers = num_decoder_layers + self.decoder_ffn_dim = decoder_ffn_dim + self.encoder_ffn_dim = encoder_ffn_dim + self.num_attention_heads = num_decoder_attention_heads + self.num_encoder_attention_heads = num_encoder_attention_heads + self.num_decoder_attention_heads = num_decoder_attention_heads + self.eos_token_id = eos_token_id + self.bos_token_id = bos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.ngram = ngram + self.num_buckets = num_buckets + self.relative_max_distance = relative_max_distance + self.use_cache = use_cache + self.disable_ngram_loss = disable_ngram_loss + self.max_position_embeddings = max_position_embeddings + self.add_cross_attention = add_cross_attention + self.is_encoder_decoder = is_encoder_decoder + + self.scope = None + self.decoder_key_length = decoder_seq_length + self.base_model_out_len = 2 + self.num_hidden_states_types = 2 # decoder_main, decoder_ngram + self.decoder_attention_idx = 1 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + + lm_labels = None + if self.use_labels: + lm_labels = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + + config = ProphetNetConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_encoder_layers=self.num_encoder_layers, + num_decoder_layers=self.num_decoder_layers, + decoder_ffn_dim=self.decoder_ffn_dim, + encoder_ffn_dim=self.encoder_ffn_dim, + num_encoder_attention_heads=self.num_encoder_attention_heads, + num_decoder_attention_heads=self.num_decoder_attention_heads, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + use_cache=self.use_cache, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ngram=self.ngram, + num_buckets=self.num_buckets, + relative_max_distance=self.relative_max_distance, + disable_ngram_loss=self.disable_ngram_loss, + max_position_embeddings=self.max_position_embeddings, + add_cross_attention=self.add_cross_attention, + is_encoder_decoder=self.is_encoder_decoder, + ) + + return ( + config, + input_ids, + attention_mask, + lm_labels, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + attention_mask, + lm_labels, + ) = self.prepare_config_and_inputs() + + encoder_hidden_states = floats_tensor([self.batch_size, self.encoder_seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + + return ( + config, + input_ids, + attention_mask, + encoder_hidden_states, + encoder_attention_mask, + lm_labels, + ) + + def create_and_check_decoder_model_past( + self, + config, + input_ids, + attention_mask, + lm_labels, + ): + config.use_cache = True + model = ProphetNetDecoder(config=config).to(torch_device).eval() + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + past_key_values = outputs["past_key_values"] + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3) + + def create_and_check_decoder_model_attention_mask_past( + self, + config, + input_ids, + attention_mask, + lm_labels, + ): + model = ProphetNetDecoder(config=config).to(torch_device).eval() + + # create attention mask + attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) + + half_seq_length = input_ids.shape[-1] // 2 + attn_mask[:, half_seq_length:] = 0 + + # first forward pass + past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"] + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1) + input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens + + # append to next input_ids and attn_mask + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + attn_mask = torch.cat( + [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)], + dim=1, + ) + + # get two different outputs + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-2) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + attention_mask, + lm_labels, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + +class ProphetNetStandaloneEncoderModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + hidden_size=16, + encoder_seq_length=7, + decoder_seq_length=7, + # For common tests + is_training=True, + is_decoder=False, + use_attention_mask=True, + add_cross_attention=False, + use_cache=False, + use_labels=True, + decoder_start_token_id=0, + encoder_ffn_dim=32, + num_encoder_layers=2, + num_encoder_attention_heads=4, + decoder_ffn_dim=32, + num_decoder_layers=2, + num_decoder_attention_heads=4, + max_position_embeddings=30, + is_encoder_decoder=False, + pad_token_id=0, + bos_token_id=1, + eos_token_id=2, + num_buckets=32, + relative_max_distance=128, + disable_ngram_loss=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_labels = use_labels + + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.num_hidden_layers = num_decoder_layers + self.num_encoder_layers = num_encoder_layers + self.num_decoder_layers = num_decoder_layers + self.decoder_ffn_dim = decoder_ffn_dim + self.encoder_ffn_dim = encoder_ffn_dim + self.num_attention_heads = num_decoder_attention_heads + self.num_encoder_attention_heads = num_encoder_attention_heads + self.num_decoder_attention_heads = num_decoder_attention_heads + self.eos_token_id = eos_token_id + self.bos_token_id = bos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.num_buckets = num_buckets + self.relative_max_distance = relative_max_distance + self.use_cache = use_cache + self.disable_ngram_loss = disable_ngram_loss + self.max_position_embeddings = max_position_embeddings + self.add_cross_attention = add_cross_attention + self.is_encoder_decoder = is_encoder_decoder + + self.scope = None + self.decoder_key_length = decoder_seq_length + self.base_model_out_len = 1 + self.num_hidden_states_types = 1 + self.decoder_attention_idx = 1 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + + config = ProphetNetConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_encoder_layers=self.num_encoder_layers, + num_decoder_layers=self.num_decoder_layers, + decoder_ffn_dim=self.decoder_ffn_dim, + encoder_ffn_dim=self.encoder_ffn_dim, + num_encoder_attention_heads=self.num_encoder_attention_heads, + num_decoder_attention_heads=self.num_decoder_attention_heads, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + use_cache=self.use_cache, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + num_buckets=self.num_buckets, + relative_max_distance=self.relative_max_distance, + disable_ngram_loss=self.disable_ngram_loss, + max_position_embeddings=self.max_position_embeddings, + add_cross_attention=self.add_cross_attention, + is_encoder_decoder=self.is_encoder_decoder, + ) + + return ( + config, + input_ids, + attention_mask, + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + attention_mask, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + +@require_torch +class ProphetNetModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (ProphetNetModel, ProphetNetForConditionalGeneration) if is_torch_available() else () + all_generative_model_classes = (ProphetNetForConditionalGeneration,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "conversational": ProphetNetForConditionalGeneration, + "feature-extraction": ProphetNetModel, + "summarization": ProphetNetForConditionalGeneration, + "text-generation": ProphetNetForCausalLM, + "text2text-generation": ProphetNetForConditionalGeneration, + "translation": ProphetNetForConditionalGeneration, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_resize_embeddings = False + is_encoder_decoder = True + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "TextGenerationPipelineTests": + # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. + # `ProphetNetConfig` was never used in pipeline tests: cannot create a simple + # tokenizer. + return True + + return False + + def setUp(self): + self.model_tester = ProphetNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=ProphetNetConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_lm_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_with_lm_head(*config_and_inputs) + + def test_only_decoder_causal_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_decoder(*config_and_inputs) + + def test_fast_integration(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_fast_integration(*config_and_inputs) + + def test_shared_weights(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs) + + def test_shift_labels_via_shift_left(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs) + + @unittest.skip("Flaky test with no simple resolution. TODO Fix me @patrickvonplaten") + def test_decoder_model_generate(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_generate_with_past_key_value_states(*config_and_inputs) + + def test_encoder_decoder_model_generate(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_generate_with_past_key_value_states(*config_and_inputs) + + def test_attn_mask_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_model_with_attn_mask(*config_and_inputs) + + def test_config_save(self): + config = self.model_tester.prepare_config_and_inputs()[0] + config.add_cross_attention = False + with tempfile.TemporaryDirectory() as tmp_dirname: + config.save_pretrained(tmp_dirname) + config = ProphetNetConfig.from_pretrained(tmp_dirname) + + self.assertFalse(config.add_cross_attention) + + def test_causal_lm_from_pretrained(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_causal_lm_from_pretrained(*config_and_inputs) + + @unittest.skipIf(torch_device == "cpu", "Cant do half precision") + def test_fp16_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs) + + # methods overwrite method in `test_modeling_common.py` + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + chunk_length = getattr(self.model_tester, "chunk_length", None) + if chunk_length is not None and hasattr(self.model_tester, "num_hashes"): + encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + if chunk_length is not None: + self.assertListEqual( + list(attentions[0].shape[-4:]), + [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length], + ) + else: + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + out_len = len(outputs) + + correct_outlen = 7 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + (self.model_tester.ngram + 1) * decoder_seq_length, + encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + elif self.is_encoder_decoder: + added_hidden_states = 2 + else: + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + if chunk_length is not None: + self.assertListEqual( + list(self_attentions[0].shape[-4:]), + [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length], + ) + else: + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + def test_retain_grad_hidden_states_attentions(self): + # decoder cannot keep gradients + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs = model(**inputs) + output = outputs[0] + + encoder_hidden_states = outputs.encoder_hidden_states[0] + encoder_attentions = outputs.encoder_attentions[0] + encoder_hidden_states.retain_grad() + encoder_attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(encoder_hidden_states.grad) + self.assertIsNotNone(encoder_attentions.grad) + + def test_generate_with_head_masking(self): + """Generating with head_masking has not been implemented for ProphetNet models yet.""" + pass + + +@require_torch +class ProphetNetStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): + all_model_classes = (ProphetNetDecoder, ProphetNetForCausalLM) if is_torch_available() else () + all_generative_model_classes = (ProphetNetForCausalLM,) if is_torch_available() else () + test_pruning = False + + test_resize_embeddings = False + is_encoder_decoder = False + + def setUp(self): + self.model_tester = ProphetNetStandaloneDecoderModelTester(self, is_training=False) + self.config_tester = ConfigTester(self, config_class=ProphetNetConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_decoder_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_past(*config_and_inputs) + + def test_decoder_model_attn_mask_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs) + + def test_retain_grad_hidden_states_attentions(self): + # decoder cannot keep gradients + return + + @unittest.skip("The model doesn't support left padding") # and it's not used enough to be worth fixing :) + def test_left_padding_compatibility(self): + pass + + +@require_torch +class ProphetNetStandaloneEncoderModelTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (ProphetNetEncoder,) if is_torch_available() else () + test_pruning = False + + test_resize_embeddings = False + is_encoder_decoder = False + + def setUp(self): + self.model_tester = ProphetNetStandaloneEncoderModelTester(self, is_training=False) + self.config_tester = ConfigTester(self, config_class=ProphetNetConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + +@require_torch +class ProphetNetModelIntegrationTest(unittest.TestCase): + @slow + def test_pretrained_checkpoint_hidden_states(self): + model = ProphetNetForConditionalGeneration.from_pretrained("microsoft/prophetnet-large-uncased") + model.to(torch_device) + + # encoder-decoder outputs + encoder_ids = torch.tensor( + [ + [ + 2871, + 102, + 2048, + 3176, + 2780, + 1997, + 2871, + 26727, + 2169, + 2097, + 12673, + 1996, + 8457, + 2006, + 2049, + 8240, + 2859, + 2799, + 1012, + 2023, + 6512, + 2038, + 2174, + 13977, + 2195, + 25962, + 1012, + 102, + ] + ] + ).to(torch_device) + + decoder_prev_ids = torch.tensor([[102, 2129, 2116, 2372, 2024, 2006, 2169, 1997, 2122, 2048, 2780, 1029]]).to( + torch_device + ) + output = model( + input_ids=encoder_ids, + attention_mask=None, + encoder_outputs=None, + decoder_input_ids=decoder_prev_ids, + ) + output_predited_logits = output[0] + expected_shape = torch.Size((1, 12, 30522)) + self.assertEqual(output_predited_logits.shape, expected_shape) + expected_slice = torch.tensor( + [[[-7.7729, -8.0343, -8.26001], [-7.74213, -7.8629, -8.6000], [-7.7328, -7.8269, -8.5264]]] + ).to(torch_device) + # self.assertTrue(torch.allclose(output_predited_logits[:, :3, :3], expected_slice, atol=1e-4)) + assert torch.allclose(output_predited_logits[:, :3, :3], expected_slice, atol=1e-4) + + # encoder outputs + encoder_outputs = model.prophetnet.encoder(encoder_ids)[0] + expected_encoder_outputs_slice = torch.tensor( + [[[-0.2526, -0.1951, -0.2185], [-0.8923, 0.2992, -0.4623], [-0.4585, 0.0165, -0.6652]]] + ).to(torch_device) + expected_shape_encoder = torch.Size((1, 28, 1024)) + self.assertEqual(encoder_outputs.shape, expected_shape_encoder) + # self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3], expected_encoder_outputs_slice, atol=1e-4)) + assert torch.allclose(encoder_outputs[:, :3, :3], expected_encoder_outputs_slice, atol=1e-4) + + # decoder outputs + decoder_outputs = model.prophetnet.decoder(decoder_prev_ids, encoder_hidden_states=encoder_outputs) + predicting_streams = decoder_outputs[1].view(1, model.config.ngram, 12, -1) + predicting_streams_logits = model.lm_head(predicting_streams) + next_first_stream_logits = predicting_streams_logits[:, 0] + # self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3], expected_slice, atol=1e-4)) + assert torch.allclose(next_first_stream_logits[:, :3, :3], expected_slice, atol=1e-4) + + @slow + def test_cnndm_inference(self): + model = ProphetNetForConditionalGeneration.from_pretrained("microsoft/prophetnet-large-uncased-cnndm") + model.config.max_length = 512 + model.to(torch_device) + + tokenizer = ProphetNetTokenizer.from_pretrained("microsoft/prophetnet-large-uncased-cnndm") + + ARTICLE_TO_SUMMARIZE = ( + "USTC was founded in Beijing by the Chinese Academy of Sciences (CAS) in September 1958. The Director of" + " CAS, Mr. Guo Moruo was appointed the first president of USTC. USTC's founding mission was to develop a" + " high-level science and technology workforce, as deemed critical for development of China's economy," + ' defense, and science and technology education. The establishment was hailed as "A Major Event in the' + ' History of Chinese Education and Science." CAS has supported USTC by combining most of its institutes' + " with the departments of the university. USTC is listed in the top 16 national key universities, becoming" + " the youngest national key university.".lower() + ) + input_ids = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=511, return_tensors="pt").input_ids + + input_ids = input_ids.to(torch_device) + + summary_ids = model.generate( + input_ids, num_beams=4, length_penalty=1.0, no_repeat_ngram_size=3, early_stopping=True + ) + EXPECTED_SUMMARIZE_512 = ( + "us ##tc was founded by the chinese academy of sciences ( cas ) in 1958 . [X_SEP] us ##tc is listed in the" + " top 16 national key universities ." + ) + generated_titles = [ + " ".join(tokenizer.convert_ids_to_tokens(g, skip_special_tokens=True)) for g in summary_ids + ] + self.assertListEqual( + [EXPECTED_SUMMARIZE_512], + generated_titles, + ) + input_ids = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=99, return_tensors="pt").input_ids + input_ids = input_ids.to(torch_device) + # actually 98 tokens are used. max_length=100 contains bos and eos. + summary_ids = model.generate( + input_ids, num_beams=4, length_penalty=1.0, no_repeat_ngram_size=3, early_stopping=True + ) + EXPECTED_SUMMARIZE_100 = ( + r"us ##tc was founded in beijing by the chinese academy of sciences ( cas ) in 1958 . [X_SEP] us ##tc " + "'" + " s founding mission was to develop a high - level science and technology workforce . [X_SEP]" + ' establishment hailed as " a major event in the history of chinese education and science "' + ) + generated_titles = [ + " ".join(tokenizer.convert_ids_to_tokens(g, skip_special_tokens=True)) for g in summary_ids + ] + self.assertListEqual( + [EXPECTED_SUMMARIZE_100], + generated_titles, + ) + + @slow + def test_question_gen_inference(self): + model = ProphetNetForConditionalGeneration.from_pretrained("microsoft/prophetnet-large-uncased-squad-qg") + model.to(torch_device) + + tokenizer = ProphetNetTokenizer.from_pretrained("microsoft/prophetnet-large-uncased-squad-qg") + + INPUTS = [ + "Bill Gates [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.", + "1975 [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.", + "April 4, 1975 [SEP] Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975.", + ] + + input_ids = tokenizer(INPUTS, truncation=True, padding=True, return_tensors="pt").input_ids + input_ids = input_ids.to(torch_device) + + gen_output = model.generate(input_ids, num_beams=5, early_stopping=True) + generated_questions = tokenizer.batch_decode(gen_output, skip_special_tokens=True) + + EXPECTED_QUESTIONS = [ + "along with paul allen, who founded microsoft?", + "what year was microsoft founded?", + "when was microsoft founded?", + ] + + self.assertListEqual( + EXPECTED_QUESTIONS, + generated_questions, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_tokenization_prophetnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_tokenization_prophetnet.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4317b3a669b69700be06bc4ad07a56a2662c0a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/prophetnet/test_tokenization_prophetnet.py @@ -0,0 +1,205 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team, The Microsoft Research team. +# +# 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 os +import unittest + +from transformers import BatchEncoding +from transformers.models.bert.tokenization_bert import ( + BasicTokenizer, + WordpieceTokenizer, + _is_control, + _is_punctuation, + _is_whitespace, +) +from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer +from transformers.testing_utils import require_torch, slow + +from ...test_tokenization_common import TokenizerTesterMixin + + +class ProphetNetTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = ProphetNetTokenizer + test_rust_tokenizer = False + + def setUp(self): + super().setUp() + + vocab_tokens = [ + "[UNK]", + "[CLS]", + "[SEP]", + "[PAD]", + "[MASK]", + "want", + "##want", + "##ed", + "wa", + "un", + "runn", + "##ing", + ",", + "low", + "lowest", + ] + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def get_input_output_texts(self, tokenizer): + input_text = "UNwant\u00E9d,running" + output_text = "unwanted, running" + return input_text, output_text + + def test_full_tokenizer(self): + tokenizer = self.tokenizer_class(self.vocab_file) + + tokens = tokenizer.tokenize("UNwant\u00E9d,running") + self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"]) + self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [9, 6, 7, 12, 10, 11]) + + def test_chinese(self): + tokenizer = BasicTokenizer() + + self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"), ["ah", "\u535A", "\u63A8", "zz"]) + + def test_basic_tokenizer_lower(self): + tokenizer = BasicTokenizer(do_lower_case=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["hello", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_lower_strip_accents_false(self): + tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hällo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["h\u00E9llo"]) + + def test_basic_tokenizer_lower_strip_accents_true(self): + tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_lower_strip_accents_default(self): + tokenizer = BasicTokenizer(do_lower_case=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_no_lower(self): + tokenizer = BasicTokenizer(do_lower_case=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["HeLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_no_lower_strip_accents_false(self): + tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HäLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_no_lower_strip_accents_true(self): + tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HaLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_respects_never_split_tokens(self): + tokenizer = BasicTokenizer(do_lower_case=False, never_split=["[UNK]"]) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]"), ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] + ) + + def test_wordpiece_tokenizer(self): + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] + + vocab = {} + for i, token in enumerate(vocab_tokens): + vocab[token] = i + tokenizer = WordpieceTokenizer(vocab=vocab, unk_token="[UNK]") + + self.assertListEqual(tokenizer.tokenize(""), []) + + self.assertListEqual(tokenizer.tokenize("unwanted running"), ["un", "##want", "##ed", "runn", "##ing"]) + + self.assertListEqual(tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"]) + + @require_torch + def test_prepare_batch(self): + tokenizer = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased") + + src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] + expected_src_tokens = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] + batch = tokenizer(src_text, padding=True, return_tensors="pt") + self.assertIsInstance(batch, BatchEncoding) + result = list(batch.input_ids.numpy()[0]) + self.assertListEqual(expected_src_tokens, result) + + self.assertEqual((2, 9), batch.input_ids.shape) + self.assertEqual((2, 9), batch.attention_mask.shape) + + def test_is_whitespace(self): + self.assertTrue(_is_whitespace(" ")) + self.assertTrue(_is_whitespace("\t")) + self.assertTrue(_is_whitespace("\r")) + self.assertTrue(_is_whitespace("\n")) + self.assertTrue(_is_whitespace("\u00A0")) + + self.assertFalse(_is_whitespace("A")) + self.assertFalse(_is_whitespace("-")) + + def test_is_control(self): + self.assertTrue(_is_control("\u0005")) + + self.assertFalse(_is_control("A")) + self.assertFalse(_is_control(" ")) + self.assertFalse(_is_control("\t")) + self.assertFalse(_is_control("\r")) + + def test_is_punctuation(self): + self.assertTrue(_is_punctuation("-")) + self.assertTrue(_is_punctuation("$")) + self.assertTrue(_is_punctuation("`")) + self.assertTrue(_is_punctuation(".")) + + self.assertFalse(_is_punctuation("A")) + self.assertFalse(_is_punctuation(" ")) + + @slow + def test_sequence_builders(self): + tokenizer = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased") + + text = tokenizer.encode("sequence builders", add_special_tokens=False) + text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False) + + encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_sentence == text + [102] + assert encoded_pair == text + [102] + text_2 + [102] diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_image_processing_pvt.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_image_processing_pvt.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b11313d81147d364561b56f1cbea2a5fa10994 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_image_processing_pvt.py @@ -0,0 +1,106 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs + + +if is_vision_available(): + from transformers import PvtImageProcessor + + +class PvtImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + image_size=18, + min_resolution=30, + max_resolution=400, + do_resize=True, + size=None, + do_normalize=True, + image_mean=[0.485, 0.456, 0.406], + image_std=[0.229, 0.224, 0.225], + ): + size = size if size is not None else {"height": 18, "width": 18} + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.image_size = image_size + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + + def prepare_image_processor_dict(self): + return { + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_normalize": self.do_normalize, + "do_resize": self.do_resize, + "size": self.size, + } + + def expected_output_image_shape(self, images): + return self.num_channels, self.size["height"], self.size["width"] + + def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_image_inputs( + batch_size=self.batch_size, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class PvtImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = PvtImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = PvtImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "size")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"height": 18, "width": 18}) + + image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42) + self.assertEqual(image_processor.size, {"height": 42, "width": 42}) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_modeling_pvt.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_modeling_pvt.py new file mode 100644 index 0000000000000000000000000000000000000000..e174b67a07887c32179ab044ee86b33c3f6dbc84 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/pvt/test_modeling_pvt.py @@ -0,0 +1,325 @@ +# coding=utf-8 +# Copyright 2023 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 Pvt model. """ + + +import unittest + +from transformers import is_torch_available, is_vision_available +from transformers.models.auto import get_values +from transformers.testing_utils import ( + require_accelerate, + require_torch, + require_torch_accelerator, + require_torch_fp16, + slow, + torch_device, +) + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import MODEL_MAPPING, PvtConfig, PvtForImageClassification, PvtImageProcessor, PvtModel + from transformers.models.pvt.modeling_pvt import PVT_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + +class PvtConfigTester(ConfigTester): + def run_common_tests(self): + config = self.config_class(**self.inputs_dict) + self.parent.assertTrue(hasattr(config, "hidden_sizes")) + self.parent.assertTrue(hasattr(config, "num_encoder_blocks")) + + +class PvtModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=64, + num_channels=3, + num_encoder_blocks=4, + depths=[2, 2, 2, 2], + sr_ratios=[8, 4, 2, 1], + hidden_sizes=[16, 32, 64, 128], + downsampling_rates=[1, 4, 8, 16], + num_attention_heads=[1, 2, 4, 8], + is_training=True, + use_labels=True, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + initializer_range=0.02, + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.num_encoder_blocks = num_encoder_blocks + self.sr_ratios = sr_ratios + self.depths = depths + self.hidden_sizes = hidden_sizes + self.downsampling_rates = downsampling_rates + self.num_attention_heads = num_attention_heads + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.num_labels = num_labels + self.scope = scope + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels) + + config = self.get_config() + return config, pixel_values, labels + + def get_config(self): + return PvtConfig( + image_size=self.image_size, + num_channels=self.num_channels, + num_encoder_blocks=self.num_encoder_blocks, + depths=self.depths, + hidden_sizes=self.hidden_sizes, + num_attention_heads=self.num_attention_heads, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = PvtModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertIsNotNone(result.last_hidden_state) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.type_sequence_label_size + model = PvtForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + # test greyscale images + config.num_channels = 1 + model = PvtForImageClassification(config) + model.to(torch_device) + model.eval() + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +class PvtModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (PvtModel, PvtForImageClassification) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": PvtModel, "image-classification": PvtForImageClassification} + if is_torch_available() + else {} + ) + + test_head_masking = False + test_pruning = False + test_resize_embeddings = False + test_torchscript = False + has_attentions = False + + def setUp(self): + self.model_tester = PvtModelTester(self) + self.config_tester = PvtConfigTester(self, config_class=PvtConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @unittest.skip("Pvt does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip("Pvt does not have get_input_embeddings method and get_output_embeddings methods") + def test_model_common_attributes(self): + pass + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config=config) + for name, param in model.named_parameters(): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_layers = sum(self.model_tester.depths) + 1 + self.assertEqual(len(hidden_states), expected_num_layers) + + # verify the first hidden states (first block) + self.assertListEqual( + list(hidden_states[0].shape[-3:]), + [ + self.model_tester.batch_size, + (self.model_tester.image_size // 4) ** 2, + self.model_tester.image_size // 4, + ], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_training(self): + if not self.model_tester.is_training: + return + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + if model_class in get_values(MODEL_MAPPING): + continue + model = model_class(config) + model.to(torch_device) + model.train() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + loss = model(**inputs).loss + loss.backward() + + @slow + def test_model_from_pretrained(self): + for model_name in PVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = PvtModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_torch +class PvtModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_image_classification(self): + # only resize + normalize + image_processor = PvtImageProcessor.from_pretrained("Zetatech/pvt-tiny-224") + model = PvtForImageClassification.from_pretrained("Zetatech/pvt-tiny-224").to(torch_device).eval() + + image = prepare_img() + encoded_inputs = image_processor(images=image, return_tensors="pt") + pixel_values = encoded_inputs.pixel_values.to(torch_device) + + with torch.no_grad(): + outputs = model(pixel_values) + + expected_shape = torch.Size((1, model.config.num_labels)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-1.4192, -1.9158, -0.9702]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_model(self): + model = PvtModel.from_pretrained("Zetatech/pvt-tiny-224").to(torch_device).eval() + + image_processor = PvtImageProcessor.from_pretrained("Zetatech/pvt-tiny-224") + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt") + pixel_values = inputs.pixel_values.to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(pixel_values) + + # verify the logits + expected_shape = torch.Size((1, 50, 512)) + self.assertEqual(outputs.last_hidden_state.shape, expected_shape) + + expected_slice = torch.tensor( + [[-0.3086, 1.0402, 1.1816], [-0.2880, 0.5781, 0.6124], [0.1480, 0.6129, -0.0590]] + ).to(torch_device) + + self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4)) + + @slow + @require_accelerate + @require_torch_accelerator + @require_torch_fp16 + def test_inference_fp16(self): + r""" + A small test to make sure that inference work in half precision without any problem. + """ + model = PvtForImageClassification.from_pretrained("Zetatech/pvt-tiny-224", torch_dtype=torch.float16) + model.to(torch_device) + image_processor = PvtImageProcessor(size=224) + + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt") + pixel_values = inputs.pixel_values.to(torch_device, dtype=torch.float16) + + # forward pass to make sure inference works in fp16 + with torch.no_grad(): + _ = model(pixel_values) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/test_modeling_qdqbert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/test_modeling_qdqbert.py new file mode 100644 index 0000000000000000000000000000000000000000..d10abb733e07a9ff3f2aa87579afa7f868fdf00f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/qdqbert/test_modeling_qdqbert.py @@ -0,0 +1,575 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# Copyright 2021 NVIDIA Corporation. 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 QDQBERT model. """ + + +import unittest + +from transformers import QDQBertConfig, is_torch_available +from transformers.testing_utils import require_pytorch_quantization, require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + QDQBertForMaskedLM, + QDQBertForMultipleChoice, + QDQBertForNextSentencePrediction, + QDQBertForQuestionAnswering, + QDQBertForSequenceClassification, + QDQBertForTokenClassification, + QDQBertLMHeadModel, + QDQBertModel, + ) + from transformers.models.qdqbert.modeling_qdqbert import QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST + + +class QDQBertModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + # Set default quantizers before creating the model. + import pytorch_quantization.nn as quant_nn + from pytorch_quantization.tensor_quant import QuantDescriptor + + # The default tensor quantizer is set to use Max calibration method + input_desc = QuantDescriptor(num_bits=8, calib_method="max") + # The default tensor quantizer is set to be per-channel quantization for weights + weight_desc = QuantDescriptor(num_bits=8, axis=((0,))) + quant_nn.QuantLinear.set_default_quant_desc_input(input_desc) + quant_nn.QuantLinear.set_default_quant_desc_weight(weight_desc) + # For the test cases, since QDQBert model is tested in one run without calibration, the quantized tensors are set as fake quantized tensors which give float type tensors in the end. + quant_nn.TensorQuantizer.use_fb_fake_quant = True + + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def get_config(self): + return QDQBertConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = QDQBertModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = QDQBertModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = QDQBertLMHeadModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = QDQBertForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_model_for_causal_lm_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = QDQBertLMHeadModel(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=token_labels, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=token_labels, + encoder_hidden_states=encoder_hidden_states, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = QDQBertLMHeadModel(config=config) + model.to(torch_device) + model.eval() + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # 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)) + + def create_and_check_for_next_sequence_prediction( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = QDQBertForNextSentencePrediction(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=sequence_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, 2)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = QDQBertForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_for_sequence_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = QDQBertForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = QDQBertForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = QDQBertForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +@require_pytorch_quantization +class QDQBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + QDQBertModel, + QDQBertForMaskedLM, + QDQBertForMultipleChoice, + QDQBertForNextSentencePrediction, + QDQBertForQuestionAnswering, + QDQBertForSequenceClassification, + QDQBertForTokenClassification, + QDQBertLMHeadModel, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (QDQBertLMHeadModel,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": QDQBertModel, + "fill-mask": QDQBertForMaskedLM, + "question-answering": QDQBertForQuestionAnswering, + "text-classification": QDQBertForSequenceClassification, + "text-generation": QDQBertLMHeadModel, + "token-classification": QDQBertForTokenClassification, + "zero-shot": QDQBertForSequenceClassification, + } + if is_torch_available() + else {} + ) + + def setUp(self): + self.model_tester = QDQBertModelTester(self) + self.config_tester = ConfigTester(self, config_class=QDQBertConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_as_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_model_as_decoder_with_default_input_mask(self): + # This regression test was failing with PyTorch < 1.3 + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = self.model_tester.prepare_config_and_inputs_for_decoder() + + input_mask = None + + self.model_tester.create_and_check_model_as_decoder( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def test_for_causal_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_for_causal_lm(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_causal_lm_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_for_causal_lm_as_decoder(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_for_next_sequence_prediction(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_next_sequence_prediction(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = QDQBertModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + # Override + def test_feed_forward_chunking(self): + # feed forward chunking is not supported in QDQBert + pass + + +@require_torch +@require_pytorch_quantization +class QDQBertModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_no_head_absolute_embedding(self): + # Set default quantizers before creating the model. + import pytorch_quantization.nn as quant_nn + from pytorch_quantization.tensor_quant import QuantDescriptor + + # The default tensor quantizer is set to use Max calibration method + input_desc = QuantDescriptor(num_bits=8, calib_method="max") + # The default tensor quantizer is set to be per-channel quantization for weights + weight_desc = QuantDescriptor(num_bits=8, axis=((0,))) + quant_nn.QuantLinear.set_default_quant_desc_input(input_desc) + quant_nn.QuantLinear.set_default_quant_desc_weight(weight_desc) + + model = QDQBertModel.from_pretrained("bert-base-uncased") + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]) + attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) + output = model(input_ids, attention_mask=attention_mask)[0] + expected_shape = torch.Size((1, 11, 768)) + self.assertEqual(output.shape, expected_shape) + expected_slice = torch.tensor( + [[[0.4571, -0.0735, 0.8594], [0.2774, -0.0278, 0.8794], [0.3548, -0.0473, 0.7593]]] + ) + self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_rag.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..48c7099620f308f0ba46f056401e335d4bbeaa5a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_rag.py @@ -0,0 +1,1189 @@ +# coding=utf-8 +# Copyright 2020, The RAG Authors and The HuggingFace Inc. team. +# +# 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 gc +import json +import os +import shutil +import tempfile +import unittest +from unittest.mock import patch + +import numpy as np + +from transformers import BartTokenizer, T5Tokenizer +from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES +from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer +from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES +from transformers.testing_utils import ( + get_tests_dir, + require_sentencepiece, + require_tokenizers, + require_torch, + require_torch_non_multi_gpu, + slow, + torch_device, +) +from transformers.utils import cached_property, is_datasets_available, is_faiss_available, is_torch_available + +from ..bart.test_modeling_bart import BartModelTester +from ..dpr.test_modeling_dpr import DPRModelTester +from ..t5.test_modeling_t5 import T5ModelTester + + +TOLERANCE = 1e-3 + +T5_SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") +if is_torch_available() and is_datasets_available() and is_faiss_available(): + import faiss + import torch + from datasets import Dataset + + from transformers import ( + AutoConfig, + AutoModel, + AutoModelForSeq2SeqLM, + DPRContextEncoder, + RagConfig, + RagModel, + RagRetriever, + RagSequenceForGeneration, + RagTokenForGeneration, + RagTokenizer, + ) + from transformers.modeling_outputs import BaseModelOutput + + +def _assert_tensors_equal(a, b, atol=1e-12, prefix=""): + """If tensors not close, or a and b arent 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: + msg = f"{a} != {b}" + if prefix: + msg = prefix + ": " + msg + raise AssertionError(msg) + + +def require_retrieval(test_case): + """ + Decorator marking a test that requires a set of dependencies necessary for pefrorm retrieval with + [`RagRetriever`]. + + These tests are skipped when respective libraries are not installed. + + """ + if not (is_torch_available() and is_datasets_available() and is_faiss_available()): + test_case = unittest.skip("test requires PyTorch, datasets and faiss")(test_case) + return test_case + + +@require_torch +@require_retrieval +@require_sentencepiece +class RagTestMixin: + all_model_classes = ( + (RagModel, RagTokenForGeneration, RagSequenceForGeneration) + if is_torch_available() and is_datasets_available() and is_faiss_available() + else () + ) + + retrieval_vector_size = 32 + n_docs = 3 + max_combined_length = 16 + + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + # DPR tok + vocab_tokens = [ + "[UNK]", + "[CLS]", + "[SEP]", + "[PAD]", + "[MASK]", + "want", + "##want", + "##ed", + "wa", + "un", + "runn", + "##ing", + ",", + "low", + "lowest", + ] + dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer") + os.makedirs(dpr_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + # BART tok + 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": ""} + + bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer") + os.makedirs(bart_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"]) + self.merges_file = os.path.join(bart_tokenizer_path, BART_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)) + + t5_tokenizer = T5Tokenizer(T5_SAMPLE_VOCAB) + t5_tokenizer_path = os.path.join(self.tmpdirname, "t5_tokenizer") + t5_tokenizer.save_pretrained(t5_tokenizer_path) + + @cached_property + def dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer: + return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer")) + + @cached_property + def dpr_ctx_encoder_tokenizer(self) -> DPRContextEncoderTokenizer: + return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer")) + + @cached_property + def bart_tokenizer(self) -> BartTokenizer: + return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer")) + + @cached_property + def t5_tokenizer(self) -> BartTokenizer: + return T5Tokenizer.from_pretrained(os.path.join(self.tmpdirname, "t5_tokenizer")) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + torch.cuda.empty_cache() + + def get_retriever(self, config): + dataset = Dataset.from_dict( + { + "id": ["0", "1", "3"], + "text": ["foo", "bar", "qux"], + "title": ["Foo", "Bar", "Qux"], + "embeddings": [ + np.ones(self.retrieval_vector_size), + 2 * np.ones(self.retrieval_vector_size), + 3 * np.ones(self.retrieval_vector_size), + ], + } + ) + dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT) + tokenizer = self.bart_tokenizer if config.generator.model_type == "bart" else self.t5_tokenizer + with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset: + mock_load_dataset.return_value = dataset + retriever = RagRetriever( + config, + question_encoder_tokenizer=self.dpr_tokenizer, + generator_tokenizer=tokenizer, + ) + return retriever + + def check_model_with_retriever( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + for model_class in self.all_model_classes: + model = model_class(config, retriever=self.get_retriever(config)).to(torch_device) + model.eval() + + self.assertTrue(model.config.is_encoder_decoder) + + outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs)) + + def check_model_with_end2end_retriever( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + context_encoder_tokenizer = self.dpr_ctx_encoder_tokenizer + dpr_context_encoder = DPRContextEncoder(config.question_encoder) # dpr is a twin tower + + retriever = self.get_retriever(config) + retriever.set_ctx_encoder_tokenizer(context_encoder_tokenizer) # setting the ctx_encoder_tokenizer. + + for model_class in [RagTokenForGeneration, RagSequenceForGeneration]: + model = model_class(config, retriever=retriever) + model.set_context_encoder_for_training(dpr_context_encoder) # set the context_encoder for training + model.to(torch_device) + model.eval() + + self.assertTrue(model.config.is_encoder_decoder) + + outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs)) + + def check_model_generate_from_context_input_ids( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + retriever = self.get_retriever(config) + + for model_class in self.all_model_classes: + model = model_class(config).to(torch_device) + model.eval() + self.assertTrue(model.config.is_encoder_decoder) + + question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0] + + out = retriever( + input_ids, + question_hidden_states.cpu().detach().to(torch.float32).numpy(), + prefix=config.generator.prefix, + return_tensors="pt", + ) + + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + + # cast + retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states) + context_input_ids = context_input_ids.to(input_ids) + context_attention_mask = context_attention_mask.to(input_ids) + + # compute doc_scores + doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze( + 1 + ) + + outputs = model.generate( + context_input_ids=context_input_ids, + context_attention_mask=context_attention_mask, + doc_scores=doc_scores, + do_deduplication=True, + ) + + self.assertIsNotNone(outputs) + + def check_model_generate( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + for model_class in self.all_model_classes[1:]: + model = model_class(config, retriever=self.get_retriever(config)).to(torch_device) + model.eval() + + self.assertTrue(model.config.is_encoder_decoder) + + outputs = model.generate( + input_ids=input_ids, + num_beams=2, + num_return_sequences=2, + decoder_start_token_id=config.generator.eos_token_id, + ) + + self.assertIsNotNone(outputs) + + def check_model_without_retriever( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + retriever = self.get_retriever(config) + + for model_class in self.all_model_classes: + model = model_class(config).to(torch_device) + model.eval() + self.assertTrue(model.config.is_encoder_decoder) + + question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0] + + out = retriever( + input_ids, + question_hidden_states.cpu().detach().to(torch.float32).numpy(), + prefix=config.generator.prefix, + return_tensors="pt", + ) + + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + + # cast + retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states) + context_input_ids = context_input_ids.to(input_ids) + context_attention_mask = context_attention_mask.to(input_ids) + + # compute doc_scores + doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze( + 1 + ) + + outputs = model( + context_input_ids=context_input_ids, + context_attention_mask=context_attention_mask, + doc_scores=doc_scores, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs)) + + def check_model_custom_n_docs( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, n_docs, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + retriever = self.get_retriever(config) + + for model_class in self.all_model_classes: + model = model_class(config).to(torch_device) + model.eval() + self.assertTrue(model.config.is_encoder_decoder) + + question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0] + + out = retriever( + input_ids, + question_hidden_states.cpu().detach().to(torch.float32).numpy(), + prefix=config.generator.prefix, + return_tensors="pt", + n_docs=n_docs, + ) + + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + + # cast + retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states) + context_input_ids = context_input_ids.to(input_ids) + context_attention_mask = context_attention_mask.to(input_ids) + + # compute doc_scores + doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze( + 1 + ) + + outputs = model( + context_input_ids=context_input_ids, + context_attention_mask=context_attention_mask, + doc_scores=doc_scores, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + n_docs=n_docs, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], n_docs)) + + def check_model_with_mismatch_n_docs_value( + self, + config, + input_ids, + attention_mask, + decoder_input_ids, + decoder_attention_mask, + retriever_n_docs, + generator_n_docs, + **kwargs, + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + retriever = self.get_retriever(config) + + for model_class in self.all_model_classes: + model = model_class(config).to(torch_device) + model.eval() + self.assertTrue(model.config.is_encoder_decoder) + + question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0] + + out = retriever( + input_ids, + question_hidden_states.cpu().detach().to(torch.float32).numpy(), + prefix=config.generator.prefix, + return_tensors="pt", + n_docs=retriever_n_docs, + ) + + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + + # cast + retrieved_doc_embeds = retrieved_doc_embeds.to(question_hidden_states) + context_input_ids = context_input_ids.to(input_ids) + context_attention_mask = context_attention_mask.to(input_ids) + + # compute doc_scores + doc_scores = torch.bmm(question_hidden_states.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)).squeeze( + 1 + ) + + self.assertRaises( + AssertionError, + model.__call__, + context_input_ids=context_input_ids, + context_attention_mask=context_attention_mask, + doc_scores=doc_scores, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + n_docs=generator_n_docs, + ) + + def check_model_with_encoder_outputs( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + for model_class in self.all_model_classes: + model = model_class(config, retriever=self.get_retriever(config)).to(torch_device) + model.eval() + + self.assertTrue(model.config.is_encoder_decoder) + + outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + encoder_outputs = BaseModelOutput(outputs.generator_enc_last_hidden_state) + + # run only generator + outputs = model( + encoder_outputs=encoder_outputs, + doc_scores=outputs.doc_scores, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs)) + + def test_model_with_retriever(self): + inputs_dict = self.config_and_inputs + self.check_model_with_retriever(**inputs_dict) + + def test_model_with_end2end_retriever(self): + inputs_dict = self.config_and_inputs + self.check_model_with_end2end_retriever(**inputs_dict) + + def test_model_without_retriever(self): + inputs_dict = self.config_and_inputs + self.check_model_without_retriever(**inputs_dict) + + def test_model_with_encoder_outputs(self): + inputs_dict = self.config_and_inputs + self.check_model_with_encoder_outputs(**inputs_dict) + + def test_model_generate(self): + inputs_dict = self.config_and_inputs + self.check_model_generate(**inputs_dict) + + def test_model_with_custom_n_docs(self): + inputs_dict = self.config_and_inputs + inputs_dict["n_docs"] = 1 + self.check_model_custom_n_docs(**inputs_dict) + + def test_model_with_mismatch_n_docs_value(self): + inputs_dict = self.config_and_inputs + inputs_dict["retriever_n_docs"] = 3 + inputs_dict["generator_n_docs"] = 2 + self.check_model_with_mismatch_n_docs_value(**inputs_dict) + + +@require_torch +@require_retrieval +class RagDPRBartTest(RagTestMixin, unittest.TestCase): + @cached_property + def config_and_inputs(self): + question_encoder_tester = DPRModelTester(self) + dpr_config_and_inputs = question_encoder_tester.prepare_config_and_inputs() + generator_tester = BartModelTester(self) + bart_config_and_inputs = generator_tester.prepare_config_and_inputs_for_common() + + (question_encoder_config, input_ids, _, input_mask, _, _, _) = dpr_config_and_inputs + (generator_config, bart_inputs_dict) = bart_config_and_inputs + decoder_input_ids, decoder_attention_mask = bart_inputs_dict["input_ids"], bart_inputs_dict["attention_mask"] + + config = RagConfig.from_question_encoder_generator_configs( + question_encoder_config, + generator_config, + n_docs=self.n_docs, + retrieval_vector_size=self.retrieval_vector_size, + max_combined_length=self.max_combined_length, + ) + + return { + "config": config, + "input_ids": input_ids, + "attention_mask": input_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + +@require_torch +@require_retrieval +class RagDPRT5Test(RagTestMixin, unittest.TestCase): + @cached_property + def config_and_inputs(self): + question_encoder_tester = DPRModelTester(self) + dpr_config_and_inputs = question_encoder_tester.prepare_config_and_inputs() + generator_tester = T5ModelTester(self, vocab_size=1100) + t5_config_and_inputs = generator_tester.prepare_config_and_inputs() + + (question_encoder_config, input_ids, _, input_mask, _, _, _) = dpr_config_and_inputs + (generator_config, _, decoder_input_ids, _, decoder_attention_mask, _) = t5_config_and_inputs + config = RagConfig.from_question_encoder_generator_configs( + question_encoder_config, + generator_config, + n_docs=self.n_docs, + retrieval_vector_size=self.retrieval_vector_size, + max_combined_length=self.max_combined_length, + ) + + return { + "config": config, + "input_ids": input_ids, + "attention_mask": input_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + +@require_torch +@require_retrieval +@require_sentencepiece +@require_tokenizers +@require_torch_non_multi_gpu +class RagModelIntegrationTests(unittest.TestCase): + def tearDown(self): + super().tearDown() + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + torch.cuda.empty_cache() + + @cached_property + def sequence_model(self): + return ( + RagSequenceForGeneration.from_pretrained_question_encoder_generator( + "facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large-cnn" + ) + .to(torch_device) + .eval() + ) + + @cached_property + def token_model(self): + return ( + RagTokenForGeneration.from_pretrained_question_encoder_generator( + "facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large-cnn" + ) + .to(torch_device) + .eval() + ) + + def get_rag_config(self): + question_encoder_config = AutoConfig.from_pretrained("facebook/dpr-question_encoder-single-nq-base") + generator_config = AutoConfig.from_pretrained("facebook/bart-large-cnn") + return RagConfig.from_question_encoder_generator_configs( + question_encoder_config, + generator_config, + bos_token_id=0, + decoder_start_token_id=2, + eos_token_id=2, + is_encoder_decoder=True, + pad_token_id=1, + vocab_size=50264, + title_sep=" / ", + doc_sep=" // ", + n_docs=5, + max_combined_length=300, + dataset="wiki_dpr", + dataset_split="train", + index_name="exact", + index_path=None, + use_dummy_dataset=True, + retrieval_vector_size=768, + retrieval_batch_size=8, + ) + + @slow + def test_rag_sequence_inference(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_sequence = self.sequence_model + rag_sequence.set_retriever(rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="pt" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="pt").input_ids + + input_ids = input_ids.to(torch_device) + decoder_input_ids = decoder_input_ids.to(torch_device) + + with torch.no_grad(): + output = rag_sequence( + input_ids, + labels=decoder_input_ids, + ) + + expected_shape = torch.Size([5, 5, 50264]) + self.assertEqual(output.logits.shape, expected_shape) + + expected_doc_scores = torch.tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]]).to(torch_device) + _assert_tensors_equal(expected_doc_scores, output.doc_scores, atol=TOLERANCE) + + expected_loss = torch.tensor([36.7368]).to(torch_device) + _assert_tensors_equal(expected_loss, output.loss, atol=TOLERANCE) + + @slow + def test_rag_token_inference(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_token = self.token_model + rag_token.set_retriever(rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="pt" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="pt").input_ids + + input_ids = input_ids.to(torch_device) + decoder_input_ids = decoder_input_ids.to(torch_device) + + with torch.no_grad(): + output = rag_token( + input_ids, + labels=decoder_input_ids, + ) + + expected_shape = torch.Size([5, 5, 50264]) + self.assertEqual(output.logits.shape, expected_shape) + + expected_doc_scores = torch.tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]]).to(torch_device) + _assert_tensors_equal(expected_doc_scores, output.doc_scores, atol=TOLERANCE) + + expected_loss = torch.tensor([36.3557]).to(torch_device) + _assert_tensors_equal(expected_loss, output.loss, atol=TOLERANCE) + + @slow + def test_rag_token_generate_beam(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_token = self.token_model + rag_token.set_retriever(rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="pt" + ).input_ids + + input_ids = input_ids.to(torch_device) + + output_ids = rag_token.generate( + input_ids, + decoder_start_token_id=rag_token.generator.config.decoder_start_token_id, + num_beams=2, + num_return_sequences=2, + ) + # sequence generate test + output_text_1 = rag_decoder_tokenizer.decode(output_ids[0], skip_special_tokens=True) + output_text_2 = rag_decoder_tokenizer.decode(output_ids[1], skip_special_tokens=True) + + # Expected outputs as given by model at integration time. + EXPECTED_OUTPUT_TEXT_1 = "\"She's My Kind of Girl" + EXPECTED_OUTPUT_TEXT_2 = "\"She's My Kind of Love" + + self.assertEqual(output_text_1, EXPECTED_OUTPUT_TEXT_1) + self.assertEqual(output_text_2, EXPECTED_OUTPUT_TEXT_2) + + @slow + def test_rag_sequence_generate_beam(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_sequence = self.sequence_model + rag_sequence.set_retriever(rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="pt" + ).input_ids + + input_ids = input_ids.to(torch_device) + + output_ids = rag_sequence.generate( + input_ids, + decoder_start_token_id=rag_sequence.generator.config.decoder_start_token_id, + num_beams=2, + num_return_sequences=2, + ) + # sequence generate test + output_text_1 = rag_decoder_tokenizer.decode(output_ids[0], skip_special_tokens=True) + output_text_2 = rag_decoder_tokenizer.decode(output_ids[1], skip_special_tokens=True) + + # Expected outputs as given by model at integration time. + EXPECTED_OUTPUT_TEXT_1 = """\"She's My Kind of Girl\" was released through Epic Records in Japan in March 1972, giving the duo a Top 10 hit. Two more singles were released in Japan, \"En Carousel\" and \"Love Has Its Ways\" Ulvaeus and Andersson persevered with their songwriting and experimented with new sounds and vocal arrangements.""" + EXPECTED_OUTPUT_TEXT_2 = """In September 2018, Björn Ulvaeus revealed that the two new songs, \"I Still Have Faith In You\" and \"Don't Shut Me Down\", would be released no earlier than March 2019. The two new tracks will feature in a TV special set to air later in the year.""" + + self.assertEqual(output_text_1, EXPECTED_OUTPUT_TEXT_1) + self.assertEqual(output_text_2, EXPECTED_OUTPUT_TEXT_2) + + @property + def test_data_questions(self): + return [ + "who got the first nobel prize in physics", + "when is the next deadpool movie being released", + "which mode is used for short wave broadcast service", + "who is the owner of reading football club", + "when is the next scandal episode coming out", + "when is the last time the philadelphia won the superbowl", + "what is the most current adobe flash player version", + "how many episodes are there in dragon ball z", + ] + + @slow + def test_rag_sequence_generate_batch(self): + tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") + retriever = RagRetriever.from_pretrained( + "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True + ) + rag_sequence = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever).to( + torch_device + ) + + input_dict = tokenizer( + self.test_data_questions, + return_tensors="pt", + padding=True, + truncation=True, + ) + + input_ids = input_dict.input_ids.to(torch_device) + attention_mask = input_dict.attention_mask.to(torch_device) + + output_ids = rag_sequence.generate( + input_ids, + attention_mask=attention_mask, + ) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + EXPECTED_OUTPUTS = [ + " albert einstein", + " june 22, 2018", + " amplitude modulation", + " tim besley ( chairman )", + " june 20, 2018", + " 1980", + " 7.0", + " 8", + ] + self.assertListEqual(outputs, EXPECTED_OUTPUTS) + + @slow + def test_rag_sequence_generate_batch_from_context_input_ids(self): + tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") + retriever = RagRetriever.from_pretrained( + "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True + ) + rag_sequence = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever).to( + torch_device + ) + + input_dict = tokenizer( + self.test_data_questions, + return_tensors="pt", + padding=True, + truncation=True, + ) + + input_ids = input_dict.input_ids.to(torch_device) + attention_mask = input_dict.attention_mask.to(torch_device) + + question_hidden_states = rag_sequence.question_encoder(input_ids, attention_mask=attention_mask)[0] + docs_dict = retriever( + input_ids.cpu().detach().numpy(), question_hidden_states.cpu().detach().numpy(), return_tensors="pt" + ) + doc_scores = torch.bmm( + question_hidden_states.unsqueeze(1), + docs_dict["retrieved_doc_embeds"].to(torch_device).float().transpose(1, 2), + ).squeeze(1) + + output_ids = rag_sequence.generate( + context_input_ids=docs_dict["context_input_ids"].to(torch_device), + context_attention_mask=docs_dict["context_attention_mask"].to(torch_device), + doc_scores=doc_scores.to(torch_device), + do_deduplication=True, + ) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + EXPECTED_OUTPUTS = [ + " albert einstein", + " june 22, 2018", + " amplitude modulation", + " tim besley ( chairman )", + " june 20, 2018", + " 1980", + " 7.0", + " 8", + ] + self.assertListEqual(outputs, EXPECTED_OUTPUTS) + + @slow + def test_rag_token_generate_batch(self): + tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") + retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True) + rag_token = RagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever).to( + torch_device + ) + + if torch_device == "cuda": + rag_token.half() + + input_dict = tokenizer( + self.test_data_questions, + return_tensors="pt", + padding=True, + truncation=True, + ) + + input_ids = input_dict.input_ids.to(torch_device) + attention_mask = input_dict.attention_mask.to(torch_device) + + output_ids = rag_token.generate( + input_ids, + attention_mask=attention_mask, + ) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + EXPECTED_OUTPUTS = [ + " albert einstein", + " september 22, 2017", + " amplitude modulation", + " stefan persson", + " april 20, 2018", + " the 1970s", + " 7.1. 2", + " 13", + ] + self.assertListEqual(outputs, EXPECTED_OUTPUTS) + + +@require_torch +@require_retrieval +class RagModelSaveLoadTests(unittest.TestCase): + def tearDown(self): + super().tearDown() + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + torch.cuda.empty_cache() + + def get_rag_config(self): + question_encoder_config = AutoConfig.from_pretrained("facebook/dpr-question_encoder-single-nq-base") + generator_config = AutoConfig.from_pretrained("facebook/bart-large-cnn") + return RagConfig.from_question_encoder_generator_configs( + question_encoder_config, + generator_config, + bos_token_id=0, + decoder_start_token_id=2, + eos_token_id=2, + is_encoder_decoder=True, + pad_token_id=1, + vocab_size=50264, + title_sep=" / ", + doc_sep=" // ", + n_docs=5, + max_combined_length=300, + dataset="wiki_dpr", + dataset_split="train", + index_name="exact", + index_path=None, + use_dummy_dataset=True, + retrieval_vector_size=768, + retrieval_batch_size=8, + ) + + @slow + def test_rag_sequence_from_pretrained(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="pt" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="pt").input_ids + + input_ids = input_ids.to(torch_device) + decoder_input_ids = decoder_input_ids.to(torch_device) + + with tempfile.TemporaryDirectory() as tmp_dirname: + rag_sequence = RagSequenceForGeneration.from_pretrained_question_encoder_generator( + "facebook/dpr-question_encoder-single-nq-base", + "facebook/bart-large-cnn", + retriever=rag_retriever, + config=rag_config, + ).to(torch_device) + # check that the from pretrained methods work + rag_sequence.save_pretrained(tmp_dirname) + rag_sequence.from_pretrained(tmp_dirname, retriever=rag_retriever) + rag_sequence.to(torch_device) + + with torch.no_grad(): + output = rag_sequence( + input_ids, + labels=decoder_input_ids, + ) + + loss_pretrained = output.loss + del rag_sequence + + question_encoder = AutoModel.from_pretrained("facebook/dpr-question_encoder-single-nq-base") + generator = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn") + rag_sequence = RagSequenceForGeneration( + config=rag_config, question_encoder=question_encoder, generator=generator, retriever=rag_retriever + ) + rag_sequence.to(torch_device) + + with torch.no_grad(): + output = rag_sequence( + input_ids, + labels=decoder_input_ids, + ) + + loss_init = output.loss + + self.assertAlmostEqual(loss_pretrained.item(), loss_init.item(), places=4) + + @slow + def test_rag_token_from_pretrained(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="pt" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="pt").input_ids + + input_ids = input_ids.to(torch_device) + decoder_input_ids = decoder_input_ids.to(torch_device) + + with tempfile.TemporaryDirectory() as tmp_dirname: + rag_token = RagTokenForGeneration.from_pretrained_question_encoder_generator( + "facebook/dpr-question_encoder-single-nq-base", + "facebook/bart-large-cnn", + retriever=rag_retriever, + config=rag_config, + question_encoder_max_length=200, + generator_max_length=200, + ).to(torch_device) + # check that the from pretrained methods work + rag_token.save_pretrained(tmp_dirname) + rag_token.from_pretrained(tmp_dirname, retriever=rag_retriever) + rag_token.to(torch_device) + + self.assertTrue(rag_token.question_encoder.config.max_length == 200) + self.assertTrue(rag_token.generator.config.max_length == 200) + + with torch.no_grad(): + output = rag_token( + input_ids, + labels=decoder_input_ids, + ) + + loss_pretrained = output.loss + del rag_token + + question_encoder = AutoModel.from_pretrained("facebook/dpr-question_encoder-single-nq-base") + generator = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn") + rag_token = RagTokenForGeneration( + config=rag_config, question_encoder=question_encoder, generator=generator, retriever=rag_retriever + ) + rag_token.to(torch_device) + + with torch.no_grad(): + output = rag_token( + input_ids, + labels=decoder_input_ids, + ) + + loss_init = output.loss + + self.assertAlmostEqual(loss_pretrained.item(), loss_init.item(), places=4) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_tf_rag.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_tf_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..0041b0e6c49ac485e09a13bc8a3856e1a56fe1b0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_modeling_tf_rag.py @@ -0,0 +1,1080 @@ +from __future__ import annotations + +import json +import os +import shutil +import tempfile +import unittest +from unittest.mock import patch + +import numpy as np + +from transformers import BartTokenizer +from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES +from transformers.models.dpr.tokenization_dpr import DPRQuestionEncoderTokenizer +from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES +from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow +from transformers.utils import cached_property, is_datasets_available, is_faiss_available, is_tf_available + + +if is_tf_available() and is_datasets_available() and is_faiss_available(): + import faiss + import tensorflow as tf + from datasets import Dataset + + from transformers import ( + AutoConfig, + RagConfig, + RagRetriever, + RagTokenizer, + TFAutoModel, + TFAutoModelForSeq2SeqLM, + TFRagModel, + TFRagSequenceForGeneration, + TFRagTokenForGeneration, + ) + from transformers.modeling_tf_outputs import TFBaseModelOutput + +from ..bart.test_modeling_tf_bart import TFBartModelTester +from ..dpr.test_modeling_tf_dpr import TFDPRModelTester + + +TOLERANCE = 1e-3 + + +def require_retrieval(test_case): + """ + Decorator marking a test that requires a set of dependencies necessary for pefrorm retrieval with + [`RagRetriever`]. + + These tests are skipped when respective libraries are not installed. + + """ + if not (is_tf_available() and is_datasets_available() and is_faiss_available()): + test_case = unittest.skip("test requires tensorflow, datasets and faiss")(test_case) + return test_case + + +@require_tf +@require_retrieval +@require_sentencepiece +class TFRagTestMixin: + all_model_classes = ( + (TFRagModel, TFRagTokenForGeneration, TFRagSequenceForGeneration) + if is_tf_available() and is_datasets_available() and is_faiss_available() + else () + ) + all_generative_model_classes = ( + (TFRagTokenForGeneration, TFRagSequenceForGeneration) + if is_tf_available() and is_datasets_available() and is_faiss_available() + else () + ) + + retrieval_vector_size = 32 + n_docs = 3 + max_combined_length = 16 + + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + # DPR tok + vocab_tokens = [ + "[UNK]", + "[CLS]", + "[SEP]", + "[PAD]", + "[MASK]", + "want", + "##want", + "##ed", + "wa", + "un", + "runn", + "##ing", + ",", + "low", + "lowest", + ] + dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer") + os.makedirs(dpr_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + # BART tok + 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": ""} + + bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer") + os.makedirs(bart_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"]) + self.merges_file = os.path.join(bart_tokenizer_path, BART_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)) + + @cached_property + def dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer: + return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer")) + + @cached_property + def bart_tokenizer(self) -> BartTokenizer: + return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer")) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def get_retriever(self, config): + dataset = Dataset.from_dict( + { + "id": ["0", "1", "3"], + "text": ["foo", "bar", "qux"], + "title": ["Foo", "Bar", "Qux"], + "embeddings": [ + np.ones(self.retrieval_vector_size), + 2 * np.ones(self.retrieval_vector_size), + 3 * np.ones(self.retrieval_vector_size), + ], + } + ) + dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT) + tokenizer = self.bart_tokenizer + with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset: + mock_load_dataset.return_value = dataset + retriever = RagRetriever( + config, + question_encoder_tokenizer=self.dpr_tokenizer, + generator_tokenizer=tokenizer, + ) + return retriever + + def check_model_with_retriever( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + for model_class in self.all_model_classes: + model = model_class(config, retriever=self.get_retriever(config)) + + self.assertTrue(model.config.is_encoder_decoder) + + outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs)) + + def check_model_generate_from_context_input_ids( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + retriever = self.get_retriever(config) + + for i, model_class in enumerate(self.all_generative_model_classes): + model = model_class(config) + self.assertTrue(model.config.is_encoder_decoder) + + question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0] + + out = retriever( + input_ids, + question_hidden_states.numpy(), + prefix=config.generator.prefix, + return_tensors="tf", + ) + + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32) + + # compute doc_scores + doc_scores = tf.squeeze( + tf.matmul(tf.expand_dims(question_hidden_states, axis=[1]), retrieved_doc_embeds, transpose_b=True), + axis=[1], + ) + + outputs = model.generate( + context_input_ids=context_input_ids, + context_attention_mask=context_attention_mask, + doc_scores=doc_scores, + ) + + self.assertIsNotNone(outputs) + + def check_model_generate( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + for model_class in self.all_generative_model_classes: + model = model_class(config, retriever=self.get_retriever(config)) + + self.assertTrue(model.config.is_encoder_decoder) + + input_ids = tf.cast(input_ids, tf.int32) + outputs = model.generate( + input_ids=input_ids, + num_beams=2, + num_return_sequences=2, + decoder_start_token_id=config.generator.eos_token_id, + max_new_tokens=5, + ) + + self.assertIsNotNone(outputs) + + def check_model_without_retriever( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + retriever = self.get_retriever(config) + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertTrue(model.config.is_encoder_decoder) + + question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0] + + out = retriever( + input_ids, + question_hidden_states.numpy(), + prefix=config.generator.prefix, + return_tensors="tf", + ) + + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + + retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32) + + # compute doc_scores + doc_scores = tf.squeeze( + tf.matmul(tf.expand_dims(question_hidden_states, axis=[1]), retrieved_doc_embeds, transpose_b=True), + axis=[1], + ) + + outputs = model( + input_ids=None, + context_input_ids=context_input_ids, + context_attention_mask=context_attention_mask, + doc_scores=doc_scores, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs)) + + def check_model_custom_n_docs( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, n_docs, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + retriever = self.get_retriever(config) + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertTrue(model.config.is_encoder_decoder) + + question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0] + + out = retriever( + input_ids, + question_hidden_states.numpy(), + prefix=config.generator.prefix, + return_tensors="tf", + n_docs=n_docs, + ) + + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + + retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32) + + # compute doc_scores + doc_scores = tf.squeeze( + tf.matmul(tf.expand_dims(question_hidden_states, axis=[1]), retrieved_doc_embeds, transpose_b=True), + axis=[1], + ) + + outputs = model( + input_ids=None, + context_input_ids=context_input_ids, + context_attention_mask=context_attention_mask, + doc_scores=doc_scores, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + n_docs=n_docs, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], n_docs)) + + def check_model_with_mismatch_n_docs_value( + self, + config, + input_ids, + attention_mask, + decoder_input_ids, + decoder_attention_mask, + retriever_n_docs, + generator_n_docs, + **kwargs, + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + retriever = self.get_retriever(config) + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertTrue(model.config.is_encoder_decoder) + + question_hidden_states = model.question_encoder(input_ids, attention_mask=attention_mask)[0] + + out = retriever( + input_ids, + question_hidden_states.numpy(), + prefix=config.generator.prefix, + return_tensors="tf", + n_docs=retriever_n_docs, + ) + + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + + retrieved_doc_embeds = tf.cast(retrieved_doc_embeds, tf.float32) + + # compute doc_scores + doc_scores = tf.squeeze( + tf.matmul(tf.expand_dims(question_hidden_states, axis=[1]), retrieved_doc_embeds, transpose_b=True), + axis=[1], + ) + + self.assertRaises( + AssertionError, + model.__call__, + input_ids=None, + context_input_ids=context_input_ids, + context_attention_mask=context_attention_mask, + doc_scores=doc_scores, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + n_docs=generator_n_docs, + ) + + def check_model_with_encoder_outputs( + self, config, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, **kwargs + ): + self.assertIsNotNone(config.question_encoder) + self.assertIsNotNone(config.generator) + + for model_class in self.all_model_classes: + model = model_class(config, retriever=self.get_retriever(config)) + + self.assertTrue(model.config.is_encoder_decoder) + + outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + encoder_outputs = TFBaseModelOutput(outputs.generator_enc_last_hidden_state) + + # run only generator + outputs = model( + input_ids=None, + encoder_outputs=encoder_outputs, + doc_scores=outputs.doc_scores, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + # logits + self.assertEqual( + outputs.logits.shape, + (self.n_docs * decoder_input_ids.shape[0], decoder_input_ids.shape[1], config.generator.vocab_size), + ) + # generator encoder last hidden states + self.assertEqual( + outputs.generator_enc_last_hidden_state.shape, + (self.n_docs * decoder_input_ids.shape[0], self.max_combined_length, config.generator.hidden_size), + ) + # doc scores + self.assertEqual(outputs.doc_scores.shape, (input_ids.shape[0], self.n_docs)) + + def test_model_with_retriever(self): + inputs_dict = self.config_and_inputs + self.check_model_with_retriever(**inputs_dict) + + def test_model_without_retriever(self): + inputs_dict = self.config_and_inputs + self.check_model_without_retriever(**inputs_dict) + + @slow + def test_model_generate_from_context_input_ids(self): + inputs_dict = self.config_and_inputs + self.check_model_generate_from_context_input_ids(**inputs_dict) + + def test_model_with_encoder_outputs(self): + inputs_dict = self.config_and_inputs + self.check_model_with_encoder_outputs(**inputs_dict) + + @slow + def test_model_generate(self): + inputs_dict = self.config_and_inputs + self.check_model_generate(**inputs_dict) + + def test_model_with_custom_n_docs(self): + inputs_dict = self.config_and_inputs + inputs_dict["n_docs"] = 1 + self.check_model_custom_n_docs(**inputs_dict) + + def test_model_with_mismatch_n_docs_value(self): + inputs_dict = self.config_and_inputs + inputs_dict["retriever_n_docs"] = 3 + inputs_dict["generator_n_docs"] = 2 + self.check_model_with_mismatch_n_docs_value(**inputs_dict) + + +@require_tf +@require_retrieval +class TFRagDPRBartTest(TFRagTestMixin, unittest.TestCase): + @cached_property + def config_and_inputs(self): + question_encoder_tester = TFDPRModelTester(self) + dpr_config_and_inputs = question_encoder_tester.prepare_config_and_inputs() + generator_tester = TFBartModelTester(self) + bart_config_and_inputs = generator_tester.prepare_config_and_inputs_for_common() + + (question_encoder_config, input_ids, _, input_mask, _, _, _) = dpr_config_and_inputs + (generator_config, bart_inputs_dict) = bart_config_and_inputs + decoder_input_ids, decoder_attention_mask = bart_inputs_dict["input_ids"], bart_inputs_dict["attention_mask"] + + config = RagConfig.from_question_encoder_generator_configs( + question_encoder_config, + generator_config, + n_docs=self.n_docs, + retrieval_vector_size=self.retrieval_vector_size, + max_combined_length=self.max_combined_length, + ) + + return { + "config": config, + "input_ids": input_ids, + "attention_mask": input_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + +@require_tf +@require_retrieval +@require_sentencepiece +@require_tokenizers +class TFRagModelIntegrationTests(unittest.TestCase): + @cached_property + def token_model(self): + return TFRagTokenForGeneration.from_pretrained_question_encoder_generator( + "facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large-cnn" + ) + + @cached_property + def sequence_model(self): + return TFRagSequenceForGeneration.from_pretrained_question_encoder_generator( + "facebook/dpr-question_encoder-single-nq-base", "facebook/bart-large-cnn" + ) + + def token_model_nq_checkpoint(self, retriever): + return TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever) + + def get_rag_config(self): + question_encoder_config = AutoConfig.from_pretrained("facebook/dpr-question_encoder-single-nq-base") + generator_config = AutoConfig.from_pretrained("facebook/bart-large-cnn") + return RagConfig.from_question_encoder_generator_configs( + question_encoder_config, + generator_config, + bos_token_id=0, + decoder_start_token_id=2, + eos_token_id=2, + is_encoder_decoder=True, + pad_token_id=1, + vocab_size=50264, + title_sep=" / ", + doc_sep=" // ", + n_docs=5, + max_combined_length=300, + dataset="wiki_dpr", + dataset_split="train", + index_name="exact", + index_path=None, + use_dummy_dataset=True, + retrieval_vector_size=768, + retrieval_batch_size=8, + ) + + @slow + def test_rag_sequence_inference(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_sequence = self.sequence_model + rag_sequence.set_retriever(rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="tf" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids + + output = rag_sequence( + input_ids, + labels=decoder_input_ids, + ) + + expected_shape = tf.TensorShape([5, 5, 50264]) + self.assertEqual(output.logits.shape, expected_shape) + + expected_doc_scores = tf.convert_to_tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]]) + expected_loss = tf.convert_to_tensor([36.7368]) + + tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3) + tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3) + + @slow + def test_rag_token_inference(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_token = self.token_model + rag_token.set_retriever(rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="tf" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids + + output = rag_token( + input_ids, + labels=decoder_input_ids, + ) + + expected_shape = tf.TensorShape([5, 5, 50264]) + self.assertEqual(output.logits.shape, expected_shape) + + expected_doc_scores = tf.convert_to_tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]]) + expected_loss = tf.convert_to_tensor([36.3557]) + + tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3) + tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3) + + @slow + def test_rag_token_inference_nq_checkpoint(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_token = self.token_model_nq_checkpoint(retriever=rag_retriever) + + # check that outputs after saving and loading are equal + with tempfile.TemporaryDirectory() as tmpdirname: + rag_token.save_pretrained(tmpdirname) + rag_token = TFRagTokenForGeneration.from_pretrained(tmpdirname, retriever=rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="tf" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids + + output = rag_token( + input_ids, + labels=decoder_input_ids, + ) + + expected_shape = tf.TensorShape([5, 5, 50265]) + self.assertEqual(output.logits.shape, expected_shape) + + expected_doc_scores = tf.convert_to_tensor([[62.9402, 62.7107, 62.2382, 62.1194, 61.8578]]) + expected_loss = tf.convert_to_tensor([32.521812]) + + tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3) + tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3) + + @slow + def test_rag_token_inference_save_pretrained(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_token = self.token_model + rag_token.set_retriever(rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="tf" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids + + # model must run once to be functional before loading/saving works + rag_token( + input_ids, + labels=decoder_input_ids, + ) + + # check that outputs after saving and loading are equal + with tempfile.TemporaryDirectory() as tmpdirname: + rag_token.save_pretrained(tmpdirname) + rag_token = TFRagTokenForGeneration.from_pretrained(tmpdirname, retriever=rag_retriever) + + output = rag_token( + input_ids, + labels=decoder_input_ids, + ) + + expected_shape = tf.TensorShape([5, 5, 50264]) + self.assertEqual(output.logits.shape, expected_shape) + + expected_doc_scores = tf.convert_to_tensor([[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]]) + expected_loss = tf.convert_to_tensor([36.3557]) + + tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3) + tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3) + + @slow + def test_init_and_from_pretrained(self): + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + rag_config = RagConfig.from_pretrained("facebook/rag-sequence-base") + rag = TFRagTokenForGeneration(rag_config, retriever=rag_retriever) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="tf" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids + + rag( + input_ids, + decoder_input_ids=decoder_input_ids, + ) + + # this should not give any warnings + with tempfile.TemporaryDirectory() as tmpdirname: + rag.save_pretrained(tmpdirname) + rag = TFRagTokenForGeneration.from_pretrained(tmpdirname, retriever=rag_retriever) + + @property + def test_data_questions(self): + return [ + "who got the first nobel prize in physics", + "when is the next deadpool movie being released", + "which mode is used for short wave broadcast service", + "who is the owner of reading football club", + "when is the next scandal episode coming out", + "when is the last time the philadelphia won the superbowl", + "what is the most current adobe flash player version", + "how many episodes are there in dragon ball z", + ] + + @slow + def test_rag_token_greedy_search(self): + tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") + retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True) + rag_token = TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever) + + # check first two questions + input_dict = tokenizer( + self.test_data_questions[:2], + return_tensors="tf", + padding=True, + truncation=True, + ) + + input_ids = input_dict.input_ids + attention_mask = input_dict.attention_mask + + # make sure only 1 beam is used + rag_token.config.num_beams = 1 + + output_ids = rag_token.generate( + input_ids, + attention_mask=attention_mask, + ) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + EXPECTED_OUTPUTS = [ + " albert einstein", + " september 22, 2017", + ] + self.assertListEqual(outputs, EXPECTED_OUTPUTS) + + @slow + def test_rag_token_generate_batch(self): + # NOTE: gold labels comes from num_beam=4, so this is effectively beam-search test + tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") + retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True) + rag_token = TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever) + + input_dict = tokenizer( + self.test_data_questions, + return_tensors="tf", + padding=True, + truncation=True, + ) + + input_ids = input_dict.input_ids + attention_mask = input_dict.attention_mask + + EXPECTED_OUTPUTS = [ + " albert einstein", + " september 22, 2017", + " amplitude modulation", + " stefan persson", + " april 20, 2018", + " the 1970s", + " 7.1. 2", + " 13", + ] + + # Split into 2 batches of 4 examples to avoid GPU OOM. + output_ids = rag_token.generate( + input_ids[:4], + attention_mask=attention_mask[:4], + ) + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + self.assertListEqual(outputs, EXPECTED_OUTPUTS[:4]) + + output_ids = rag_token.generate( + input_ids[4:], + attention_mask=attention_mask[4:], + ) + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + self.assertListEqual(outputs, EXPECTED_OUTPUTS[4:]) + + @slow + def test_rag_sequence_generate_batch(self): + tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") + retriever = RagRetriever.from_pretrained( + "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True + ) + rag_sequence = TFRagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever) + + input_dict = tokenizer( + self.test_data_questions, + return_tensors="tf", + padding=True, + truncation=True, + ) + + input_ids = input_dict.input_ids + attention_mask = input_dict.attention_mask + + output_ids = rag_sequence.generate( + input_ids, + attention_mask=attention_mask, + ) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + EXPECTED_OUTPUTS = [ + " albert einstein", + " june 22, 2018", + " amplitude modulation", + " tim besley ( chairman )", + " june 20, 2018", + " 1980", + " 7.0", + " 8", + ] + self.assertListEqual(outputs, EXPECTED_OUTPUTS) + + @slow + def test_rag_sequence_generate_batch_from_context_input_ids(self): + tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") + retriever = RagRetriever.from_pretrained( + "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True + ) + rag_sequence = TFRagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever) + input_dict = tokenizer( + self.test_data_questions, + return_tensors="tf", + padding=True, + truncation=True, + ) + + input_ids = input_dict.input_ids + + question_hidden_states = rag_sequence.question_encoder(input_ids)[0] + docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors="tf") + doc_scores = tf.squeeze( + tf.matmul( + tf.expand_dims(question_hidden_states, axis=[1]), docs_dict["retrieved_doc_embeds"], transpose_b=True + ), + axis=[1], + ) + output_ids = rag_sequence.generate( + context_input_ids=docs_dict["context_input_ids"], + context_attention_mask=docs_dict["context_attention_mask"], + doc_scores=doc_scores, + do_deduplication=True, + ) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + EXPECTED_OUTPUTS = [ + " albert einstein", + " june 22, 2018", + " amplitude modulation", + " tim besley ( chairman )", + " june 20, 2018", + " 1980", + " 7.0", + " 8", + ] + self.assertListEqual(outputs, EXPECTED_OUTPUTS) + + +@require_tf +@require_retrieval +class TFRagModelSaveLoadTests(unittest.TestCase): + def get_rag_config(self): + question_encoder_config = AutoConfig.from_pretrained("facebook/dpr-question_encoder-single-nq-base") + generator_config = AutoConfig.from_pretrained("facebook/bart-large-cnn") + return RagConfig.from_question_encoder_generator_configs( + question_encoder_config, + generator_config, + bos_token_id=0, + decoder_start_token_id=2, + eos_token_id=2, + is_encoder_decoder=True, + pad_token_id=1, + vocab_size=50264, + title_sep=" / ", + doc_sep=" // ", + n_docs=5, + max_combined_length=300, + dataset="wiki_dpr", + dataset_split="train", + index_name="exact", + index_path=None, + use_dummy_dataset=True, + retrieval_vector_size=768, + retrieval_batch_size=8, + ) + + @slow + def test_rag_sequence_from_pretrained(self): + load_weight_prefix = "tf_rag_model_1" + + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="tf" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids + + with tempfile.TemporaryDirectory() as tmp_dirname: + rag_sequence = TFRagSequenceForGeneration.from_pretrained_question_encoder_generator( + "facebook/dpr-question_encoder-single-nq-base", + "facebook/bart-large-cnn", + retriever=rag_retriever, + config=rag_config, + ) + # check that the from pretrained methods work + rag_sequence.save_pretrained(tmp_dirname) + rag_sequence.from_pretrained(tmp_dirname, retriever=rag_retriever) + + output = rag_sequence(input_ids, labels=decoder_input_ids) + + loss_pretrained = output.loss + del rag_sequence + + question_encoder = TFAutoModel.from_pretrained("facebook/dpr-question_encoder-single-nq-base") + generator = TFAutoModelForSeq2SeqLM.from_pretrained( + "facebook/bart-large-cnn", load_weight_prefix=load_weight_prefix, name="generator" + ) + + rag_sequence = TFRagSequenceForGeneration( + config=rag_config, question_encoder=question_encoder, generator=generator, retriever=rag_retriever + ) + + output = rag_sequence(input_ids, labels=decoder_input_ids) + + loss_init = output.loss + + self.assertAlmostEqual(loss_pretrained, loss_init, places=4) + + @slow + def test_rag_token_from_pretrained(self): + load_weight_prefix = "tf_rag_model_1" + + rag_config = self.get_rag_config() + rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn") + rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained( + "facebook/dpr-question_encoder-single-nq-base" + ) + rag_retriever = RagRetriever( + rag_config, + question_encoder_tokenizer=rag_question_encoder_tokenizer, + generator_tokenizer=rag_decoder_tokenizer, + ) + + input_ids = rag_question_encoder_tokenizer( + "who sings does he love me with reba", return_tensors="tf" + ).input_ids + decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids + + with tempfile.TemporaryDirectory() as tmp_dirname: + rag_token = TFRagTokenForGeneration.from_pretrained_question_encoder_generator( + "facebook/dpr-question_encoder-single-nq-base", + "facebook/bart-large-cnn", + retriever=rag_retriever, + config=rag_config, + ) + # check that the from pretrained methods work + rag_token.save_pretrained(tmp_dirname) + rag_token.from_pretrained(tmp_dirname, retriever=rag_retriever) + + output = rag_token(input_ids, labels=decoder_input_ids) + + loss_pretrained = output.loss + del rag_token + + question_encoder = TFAutoModel.from_pretrained("facebook/dpr-question_encoder-single-nq-base") + generator = TFAutoModelForSeq2SeqLM.from_pretrained( + "facebook/bart-large-cnn", load_weight_prefix=load_weight_prefix, name="generator" + ) + rag_token = TFRagTokenForGeneration( + config=rag_config, question_encoder=question_encoder, generator=generator, retriever=rag_retriever + ) + + output = rag_token(input_ids, labels=decoder_input_ids) + + loss_init = output.loss + + self.assertAlmostEqual(loss_pretrained, loss_init, places=4) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_retrieval_rag.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_retrieval_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..1cf155b39a9e2decb0a4278c336489ec0d207a0c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_retrieval_rag.py @@ -0,0 +1,320 @@ +# 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 shutil +import tempfile +from unittest import TestCase +from unittest.mock import patch + +import numpy as np +from datasets import Dataset + +from transformers import is_faiss_available +from transformers.models.bart.configuration_bart import BartConfig +from transformers.models.bart.tokenization_bart import BartTokenizer +from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES +from transformers.models.dpr.configuration_dpr import DPRConfig +from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer +from transformers.models.rag.configuration_rag import RagConfig +from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever +from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES +from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch + + +if is_faiss_available(): + import faiss + + +@require_faiss +class RagRetrieverTest(TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + self.retrieval_vector_size = 8 + + # DPR tok + vocab_tokens = [ + "[UNK]", + "[CLS]", + "[SEP]", + "[PAD]", + "[MASK]", + "want", + "##want", + "##ed", + "wa", + "un", + "runn", + "##ing", + ",", + "low", + "lowest", + ] + dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer") + os.makedirs(dpr_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + # BART tok + 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": ""} + + bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer") + os.makedirs(bart_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"]) + self.merges_file = os.path.join(bart_tokenizer_path, BART_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_dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer: + return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer")) + + def get_dpr_ctx_encoder_tokenizer(self) -> DPRContextEncoderTokenizer: + return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer")) + + def get_bart_tokenizer(self) -> BartTokenizer: + return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer")) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def get_dummy_dataset(self): + dataset = Dataset.from_dict( + { + "id": ["0", "1"], + "text": ["foo", "bar"], + "title": ["Foo", "Bar"], + "embeddings": [np.ones(self.retrieval_vector_size), 2 * np.ones(self.retrieval_vector_size)], + } + ) + dataset.add_faiss_index("embeddings", string_factory="Flat", metric_type=faiss.METRIC_INNER_PRODUCT) + return dataset + + def get_dummy_canonical_hf_index_retriever(self): + dataset = self.get_dummy_dataset() + config = RagConfig( + retrieval_vector_size=self.retrieval_vector_size, + question_encoder=DPRConfig().to_dict(), + generator=BartConfig().to_dict(), + ) + with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset: + mock_load_dataset.return_value = dataset + retriever = RagRetriever( + config, + question_encoder_tokenizer=self.get_dpr_tokenizer(), + generator_tokenizer=self.get_bart_tokenizer(), + ) + return retriever + + def get_dummy_custom_hf_index_retriever(self, from_disk: bool): + dataset = self.get_dummy_dataset() + config = RagConfig( + retrieval_vector_size=self.retrieval_vector_size, + question_encoder=DPRConfig().to_dict(), + generator=BartConfig().to_dict(), + index_name="custom", + ) + if from_disk: + config.passages_path = os.path.join(self.tmpdirname, "dataset") + config.index_path = os.path.join(self.tmpdirname, "index.faiss") + dataset.get_index("embeddings").save(os.path.join(self.tmpdirname, "index.faiss")) + dataset.drop_index("embeddings") + dataset.save_to_disk(os.path.join(self.tmpdirname, "dataset")) + del dataset + retriever = RagRetriever( + config, + question_encoder_tokenizer=self.get_dpr_tokenizer(), + generator_tokenizer=self.get_bart_tokenizer(), + ) + else: + retriever = RagRetriever( + config, + question_encoder_tokenizer=self.get_dpr_tokenizer(), + generator_tokenizer=self.get_bart_tokenizer(), + index=CustomHFIndex(config.retrieval_vector_size, dataset), + ) + return retriever + + def test_canonical_hf_index_retriever_retrieve(self): + n_docs = 1 + retriever = self.get_dummy_canonical_hf_index_retriever() + hidden_states = np.array( + [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32 + ) + retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs) + self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size)) + self.assertEqual(len(doc_dicts), 2) + self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"]) + self.assertEqual(len(doc_dicts[0]["id"]), n_docs) + self.assertEqual(doc_dicts[0]["id"][0], "1") # max inner product is reached with second doc + self.assertEqual(doc_dicts[1]["id"][0], "0") # max inner product is reached with first doc + self.assertListEqual(doc_ids.tolist(), [[1], [0]]) + + def test_canonical_hf_index_retriever_save_and_from_pretrained(self): + retriever = self.get_dummy_canonical_hf_index_retriever() + with tempfile.TemporaryDirectory() as tmp_dirname: + with patch("transformers.models.rag.retrieval_rag.load_dataset") as mock_load_dataset: + mock_load_dataset.return_value = self.get_dummy_dataset() + retriever.save_pretrained(tmp_dirname) + retriever = RagRetriever.from_pretrained(tmp_dirname) + self.assertIsInstance(retriever, RagRetriever) + hidden_states = np.array( + [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32 + ) + out = retriever.retrieve(hidden_states, n_docs=1) + self.assertTrue(out is not None) + + def test_custom_hf_index_retriever_retrieve(self): + n_docs = 1 + retriever = self.get_dummy_custom_hf_index_retriever(from_disk=False) + hidden_states = np.array( + [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32 + ) + retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs) + self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size)) + self.assertEqual(len(doc_dicts), 2) + self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"]) + self.assertEqual(len(doc_dicts[0]["id"]), n_docs) + self.assertEqual(doc_dicts[0]["id"][0], "1") # max inner product is reached with second doc + self.assertEqual(doc_dicts[1]["id"][0], "0") # max inner product is reached with first doc + self.assertListEqual(doc_ids.tolist(), [[1], [0]]) + + def test_custom_hf_index_retriever_save_and_from_pretrained(self): + retriever = self.get_dummy_custom_hf_index_retriever(from_disk=False) + with tempfile.TemporaryDirectory() as tmp_dirname: + retriever.save_pretrained(tmp_dirname) + retriever = RagRetriever.from_pretrained(tmp_dirname) + self.assertIsInstance(retriever, RagRetriever) + hidden_states = np.array( + [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32 + ) + out = retriever.retrieve(hidden_states, n_docs=1) + self.assertTrue(out is not None) + + def test_custom_hf_index_retriever_retrieve_from_disk(self): + n_docs = 1 + retriever = self.get_dummy_custom_hf_index_retriever(from_disk=True) + hidden_states = np.array( + [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32 + ) + retrieved_doc_embeds, doc_ids, doc_dicts = retriever.retrieve(hidden_states, n_docs=n_docs) + self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size)) + self.assertEqual(len(doc_dicts), 2) + self.assertEqual(sorted(doc_dicts[0]), ["embeddings", "id", "text", "title"]) + self.assertEqual(len(doc_dicts[0]["id"]), n_docs) + self.assertEqual(doc_dicts[0]["id"][0], "1") # max inner product is reached with second doc + self.assertEqual(doc_dicts[1]["id"][0], "0") # max inner product is reached with first doc + self.assertListEqual(doc_ids.tolist(), [[1], [0]]) + + def test_custom_hf_index_retriever_save_and_from_pretrained_from_disk(self): + retriever = self.get_dummy_custom_hf_index_retriever(from_disk=True) + with tempfile.TemporaryDirectory() as tmp_dirname: + retriever.save_pretrained(tmp_dirname) + retriever = RagRetriever.from_pretrained(tmp_dirname) + self.assertIsInstance(retriever, RagRetriever) + hidden_states = np.array( + [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32 + ) + out = retriever.retrieve(hidden_states, n_docs=1) + self.assertTrue(out is not None) + + @require_torch + @require_tokenizers + @require_sentencepiece + def test_hf_index_retriever_call(self): + import torch + + n_docs = 1 + retriever = self.get_dummy_canonical_hf_index_retriever() + question_input_ids = [[5, 7], [10, 11]] + hidden_states = np.array( + [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32 + ) + out = retriever(question_input_ids, hidden_states, prefix=retriever.config.generator.prefix, n_docs=n_docs) + context_input_ids, context_attention_mask, retrieved_doc_embeds = ( + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + ) + self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size)) + self.assertIsInstance(context_input_ids, list) + self.assertIsInstance(context_attention_mask, list) + self.assertIsInstance(retrieved_doc_embeds, np.ndarray) + + out = retriever( + question_input_ids, + hidden_states, + prefix=retriever.config.generator.prefix, + n_docs=n_docs, + return_tensors="pt", + ) + context_input_ids, context_attention_mask, retrieved_doc_embeds, doc_ids = ( # noqa: F841 + out["context_input_ids"], + out["context_attention_mask"], + out["retrieved_doc_embeds"], + out["doc_ids"], + ) + self.assertEqual(retrieved_doc_embeds.shape, (2, n_docs, self.retrieval_vector_size)) + self.assertIsInstance(context_input_ids, torch.Tensor) + self.assertIsInstance(context_attention_mask, torch.Tensor) + self.assertIsInstance(retrieved_doc_embeds, torch.Tensor) + + @require_torch + @require_tokenizers + @require_sentencepiece + def test_custom_hf_index_end2end_retriever_call(self): + context_encoder_tokenizer = self.get_dpr_ctx_encoder_tokenizer() + n_docs = 1 + retriever = self.get_dummy_custom_hf_index_retriever(from_disk=False) + retriever.set_ctx_encoder_tokenizer(context_encoder_tokenizer) + + question_input_ids = [[5, 7], [10, 11]] + hidden_states = np.array( + [np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)], dtype=np.float32 + ) + out = retriever(question_input_ids, hidden_states, prefix=retriever.config.generator.prefix, n_docs=n_docs) + + self.assertEqual( + len(out), 6 + ) # check whether the retriever output consist of 6 attributes including tokenized docs + self.assertEqual( + all(k in out for k in ("tokenized_doc_ids", "tokenized_doc_attention_mask")), True + ) # check for doc token related keys in dictionary. diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_tokenization_rag.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_tokenization_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..3ac5b0efe02ea6ae8a09c70af729e4af732f048c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rag/test_tokenization_rag.py @@ -0,0 +1,168 @@ +# 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 shutil +import tempfile +from unittest import TestCase + +from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast +from transformers.models.bart.configuration_bart import BartConfig +from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES +from transformers.models.dpr.configuration_dpr import DPRConfig +from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES +from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow +from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available + + +if is_torch_available() and is_datasets_available() and is_faiss_available(): + from transformers.models.rag.configuration_rag import RagConfig + from transformers.models.rag.tokenization_rag import RagTokenizer + + +@require_faiss +@require_torch +class RagTokenizerTest(TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + self.retrieval_vector_size = 8 + + # DPR tok + vocab_tokens = [ + "[UNK]", + "[CLS]", + "[SEP]", + "[PAD]", + "[MASK]", + "want", + "##want", + "##ed", + "wa", + "un", + "runn", + "##ing", + ",", + "low", + "lowest", + ] + dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer") + os.makedirs(dpr_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + # BART tok + 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": ""} + + bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer") + os.makedirs(bart_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"]) + self.merges_file = os.path.join(bart_tokenizer_path, BART_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_dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer: + return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer")) + + def get_bart_tokenizer(self) -> BartTokenizer: + return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer")) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + @require_tokenizers + def test_save_load_pretrained_with_saved_config(self): + save_dir = os.path.join(self.tmpdirname, "rag_tokenizer") + rag_config = RagConfig(question_encoder=DPRConfig().to_dict(), generator=BartConfig().to_dict()) + rag_tokenizer = RagTokenizer(question_encoder=self.get_dpr_tokenizer(), generator=self.get_bart_tokenizer()) + rag_config.save_pretrained(save_dir) + rag_tokenizer.save_pretrained(save_dir) + new_rag_tokenizer = RagTokenizer.from_pretrained(save_dir, config=rag_config) + self.assertIsInstance(new_rag_tokenizer.question_encoder, DPRQuestionEncoderTokenizerFast) + self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab(), rag_tokenizer.question_encoder.get_vocab()) + self.assertIsInstance(new_rag_tokenizer.generator, BartTokenizerFast) + self.assertEqual(new_rag_tokenizer.generator.get_vocab(), rag_tokenizer.generator.get_vocab()) + + @slow + def test_pretrained_token_nq_tokenizer(self): + tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") + input_strings = [ + "who got the first nobel prize in physics", + "when is the next deadpool movie being released", + "which mode is used for short wave broadcast service", + "who is the owner of reading football club", + "when is the next scandal episode coming out", + "when is the last time the philadelphia won the superbowl", + "what is the most current adobe flash player version", + "how many episodes are there in dragon ball z", + "what is the first step in the evolution of the eye", + "where is gall bladder situated in human body", + "what is the main mineral in lithium batteries", + "who is the president of usa right now", + "where do the greasers live in the outsiders", + "panda is a national animal of which country", + "what is the name of manchester united stadium", + ] + input_dict = tokenizer(input_strings) + self.assertIsNotNone(input_dict) + + @slow + def test_pretrained_sequence_nq_tokenizer(self): + tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") + input_strings = [ + "who got the first nobel prize in physics", + "when is the next deadpool movie being released", + "which mode is used for short wave broadcast service", + "who is the owner of reading football club", + "when is the next scandal episode coming out", + "when is the last time the philadelphia won the superbowl", + "what is the most current adobe flash player version", + "how many episodes are there in dragon ball z", + "what is the first step in the evolution of the eye", + "where is gall bladder situated in human body", + "what is the main mineral in lithium batteries", + "who is the president of usa right now", + "where do the greasers live in the outsiders", + "panda is a national animal of which country", + "what is the name of manchester united stadium", + ] + input_dict = tokenizer(input_strings) + self.assertIsNotNone(input_dict) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_modeling_realm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_modeling_realm.py new file mode 100644 index 0000000000000000000000000000000000000000..4d6d9fd0ff114a6ecc773ff86a8e56ba3fc59a7d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_modeling_realm.py @@ -0,0 +1,554 @@ +# coding=utf-8 +# Copyright 2022 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 REALM model. """ + +import copy +import unittest + +import numpy as np + +from transformers import RealmConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + RealmEmbedder, + RealmForOpenQA, + RealmKnowledgeAugEncoder, + RealmReader, + RealmRetriever, + RealmScorer, + RealmTokenizer, + ) + + +class RealmModelTester: + def __init__( + self, + parent, + batch_size=13, + retriever_proj_size=128, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + layer_norm_eps=1e-12, + span_hidden_size=50, + max_span_width=10, + reader_layer_norm_eps=1e-3, + reader_beam_size=4, + reader_seq_len=288 + 32, + num_block_records=13353718, + searcher_beam_size=8, + searcher_seq_len=64, + num_labels=3, + num_choices=4, + num_candidates=10, + scope=None, + ): + # General config + self.parent = parent + self.batch_size = batch_size + self.retriever_proj_size = retriever_proj_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.layer_norm_eps = layer_norm_eps + + # Reader config + self.span_hidden_size = span_hidden_size + self.max_span_width = max_span_width + self.reader_layer_norm_eps = reader_layer_norm_eps + self.reader_beam_size = reader_beam_size + self.reader_seq_len = reader_seq_len + + # Searcher config + self.num_block_records = num_block_records + self.searcher_beam_size = searcher_beam_size + self.searcher_seq_len = searcher_seq_len + + self.num_labels = num_labels + self.num_choices = num_choices + self.num_candidates = num_candidates + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + candiate_input_ids = ids_tensor([self.batch_size, self.num_candidates, self.seq_length], self.vocab_size) + reader_input_ids = ids_tensor([self.reader_beam_size, self.reader_seq_len], self.vocab_size) + + input_mask = None + candiate_input_mask = None + reader_input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + candiate_input_mask = random_attention_mask([self.batch_size, self.num_candidates, self.seq_length]) + reader_input_mask = random_attention_mask([self.reader_beam_size, self.reader_seq_len]) + + token_type_ids = None + candidate_token_type_ids = None + reader_token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + candidate_token_type_ids = ids_tensor( + [self.batch_size, self.num_candidates, self.seq_length], self.type_vocab_size + ) + reader_token_type_ids = ids_tensor([self.reader_beam_size, self.reader_seq_len], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + # inputs with additional num_candidates axis. + scorer_encoder_inputs = (candiate_input_ids, candiate_input_mask, candidate_token_type_ids) + # reader inputs + reader_inputs = (reader_input_ids, reader_input_mask, reader_token_type_ids) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + scorer_encoder_inputs, + reader_inputs, + sequence_labels, + token_labels, + choice_labels, + ) + + def get_config(self): + return RealmConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + retriever_proj_size=self.retriever_proj_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + num_candidates=self.num_candidates, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + ) + + def create_and_check_embedder( + self, + config, + input_ids, + token_type_ids, + input_mask, + scorer_encoder_inputs, + reader_inputs, + sequence_labels, + token_labels, + choice_labels, + ): + model = RealmEmbedder(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.projected_score.shape, (self.batch_size, self.retriever_proj_size)) + + def create_and_check_encoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + scorer_encoder_inputs, + reader_inputs, + sequence_labels, + token_labels, + choice_labels, + ): + model = RealmKnowledgeAugEncoder(config=config) + model.to(torch_device) + model.eval() + relevance_score = floats_tensor([self.batch_size, self.num_candidates]) + result = model( + scorer_encoder_inputs[0], + attention_mask=scorer_encoder_inputs[1], + token_type_ids=scorer_encoder_inputs[2], + relevance_score=relevance_score, + labels=token_labels, + ) + self.parent.assertEqual( + result.logits.shape, (self.batch_size * self.num_candidates, self.seq_length, self.vocab_size) + ) + + def create_and_check_reader( + self, + config, + input_ids, + token_type_ids, + input_mask, + scorer_encoder_inputs, + reader_inputs, + sequence_labels, + token_labels, + choice_labels, + ): + model = RealmReader(config=config) + model.to(torch_device) + model.eval() + relevance_score = floats_tensor([self.reader_beam_size]) + result = model( + reader_inputs[0], + attention_mask=reader_inputs[1], + token_type_ids=reader_inputs[2], + relevance_score=relevance_score, + ) + self.parent.assertEqual(result.block_idx.shape, ()) + self.parent.assertEqual(result.candidate.shape, ()) + self.parent.assertEqual(result.start_pos.shape, ()) + self.parent.assertEqual(result.end_pos.shape, ()) + + def create_and_check_scorer( + self, + config, + input_ids, + token_type_ids, + input_mask, + scorer_encoder_inputs, + reader_inputs, + sequence_labels, + token_labels, + choice_labels, + ): + model = RealmScorer(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + candidate_input_ids=scorer_encoder_inputs[0], + candidate_attention_mask=scorer_encoder_inputs[1], + candidate_token_type_ids=scorer_encoder_inputs[2], + ) + self.parent.assertEqual(result.relevance_score.shape, (self.batch_size, self.num_candidates)) + self.parent.assertEqual(result.query_score.shape, (self.batch_size, self.retriever_proj_size)) + self.parent.assertEqual( + result.candidate_score.shape, (self.batch_size, self.num_candidates, self.retriever_proj_size) + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + scorer_encoder_inputs, + reader_inputs, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class RealmModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + RealmEmbedder, + RealmKnowledgeAugEncoder, + # RealmScorer is excluded from common tests as it is a container model + # consisting of two RealmEmbedders & a simple inner product calculation. + # RealmScorer + ) + if is_torch_available() + else () + ) + all_generative_model_classes = () + pipeline_model_mapping = {} if is_torch_available() else {} + + # disable these tests because there is no base_model in Realm + test_save_load_fast_init_from_base = False + test_save_load_fast_init_to_base = False + + def setUp(self): + self.test_pruning = False + self.model_tester = RealmModelTester(self) + self.config_tester = ConfigTester(self, config_class=RealmConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_embedder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_embedder(*config_and_inputs) + + def test_encoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_encoder(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_embedder(*config_and_inputs) + self.model_tester.create_and_check_encoder(*config_and_inputs) + + def test_scorer(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_scorer(*config_and_inputs) + + def test_training(self): + if not self.model_tester.is_training: + return + + config, *inputs = self.model_tester.prepare_config_and_inputs() + input_ids, token_type_ids, input_mask, scorer_encoder_inputs = inputs[0:4] + config.return_dict = True + + tokenizer = RealmTokenizer.from_pretrained("google/realm-orqa-nq-openqa") + + # RealmKnowledgeAugEncoder training + model = RealmKnowledgeAugEncoder(config) + model.to(torch_device) + model.train() + + inputs_dict = { + "input_ids": scorer_encoder_inputs[0].to(torch_device), + "attention_mask": scorer_encoder_inputs[1].to(torch_device), + "token_type_ids": scorer_encoder_inputs[2].to(torch_device), + "relevance_score": floats_tensor([self.model_tester.batch_size, self.model_tester.num_candidates]), + } + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + inputs = inputs_dict + loss = model(**inputs).loss + loss.backward() + + # RealmForOpenQA training + openqa_config = copy.deepcopy(config) + openqa_config.vocab_size = 30522 # the retrieved texts will inevitably have more than 99 vocabs. + openqa_config.num_block_records = 5 + openqa_config.searcher_beam_size = 2 + + block_records = np.array( + [ + b"This is the first record.", + b"This is the second record.", + b"This is the third record.", + b"This is the fourth record.", + b"This is the fifth record.", + ], + dtype=object, + ) + retriever = RealmRetriever(block_records, tokenizer) + model = RealmForOpenQA(openqa_config, retriever) + model.to(torch_device) + model.train() + + inputs_dict = { + "input_ids": input_ids[:1].to(torch_device), + "attention_mask": input_mask[:1].to(torch_device), + "token_type_ids": token_type_ids[:1].to(torch_device), + "answer_ids": input_ids[:1].tolist(), + } + inputs = self._prepare_for_class(inputs_dict, RealmForOpenQA) + loss = model(**inputs).reader_output.loss + loss.backward() + + # Test model.block_embedding_to + device = torch.device("cpu") + model.block_embedding_to(device) + loss = model(**inputs).reader_output.loss + loss.backward() + self.assertEqual(model.block_emb.device.type, device.type) + + @slow + def test_embedder_from_pretrained(self): + model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder") + self.assertIsNotNone(model) + + @slow + def test_encoder_from_pretrained(self): + model = RealmKnowledgeAugEncoder.from_pretrained("google/realm-cc-news-pretrained-encoder") + self.assertIsNotNone(model) + + @slow + def test_open_qa_from_pretrained(self): + model = RealmForOpenQA.from_pretrained("google/realm-orqa-nq-openqa") + self.assertIsNotNone(model) + + @slow + def test_reader_from_pretrained(self): + model = RealmReader.from_pretrained("google/realm-orqa-nq-reader") + self.assertIsNotNone(model) + + @slow + def test_scorer_from_pretrained(self): + model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer") + self.assertIsNotNone(model) + + +@require_torch +class RealmModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_embedder(self): + retriever_projected_size = 128 + + model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder") + input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) + output = model(input_ids)[0] + + expected_shape = torch.Size((1, retriever_projected_size)) + self.assertEqual(output.shape, expected_shape) + + expected_slice = torch.tensor([[-0.0714, -0.0837, -0.1314]]) + self.assertTrue(torch.allclose(output[:, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_encoder(self): + num_candidates = 2 + vocab_size = 30522 + + model = RealmKnowledgeAugEncoder.from_pretrained( + "google/realm-cc-news-pretrained-encoder", num_candidates=num_candidates + ) + input_ids = torch.tensor([[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) + relevance_score = torch.tensor([[0.3, 0.7]], dtype=torch.float32) + output = model(input_ids, relevance_score=relevance_score)[0] + + expected_shape = torch.Size((2, 6, vocab_size)) + self.assertEqual(output.shape, expected_shape) + + expected_slice = torch.tensor([[[-11.0888, -11.2544], [-10.2170, -10.3874]]]) + + self.assertTrue(torch.allclose(output[1, :2, :2], expected_slice, atol=1e-4)) + + @slow + def test_inference_open_qa(self): + from transformers.models.realm.retrieval_realm import RealmRetriever + + tokenizer = RealmTokenizer.from_pretrained("google/realm-orqa-nq-openqa") + retriever = RealmRetriever.from_pretrained("google/realm-orqa-nq-openqa") + + model = RealmForOpenQA.from_pretrained( + "google/realm-orqa-nq-openqa", + retriever=retriever, + ) + + question = "Who is the pioneer in modern computer science?" + + question = tokenizer( + [question], + padding=True, + truncation=True, + max_length=model.config.searcher_seq_len, + return_tensors="pt", + ).to(model.device) + + predicted_answer_ids = model(**question).predicted_answer_ids + + predicted_answer = tokenizer.decode(predicted_answer_ids) + self.assertEqual(predicted_answer, "alan mathison turing") + + @slow + def test_inference_reader(self): + config = RealmConfig(reader_beam_size=2, max_span_width=3) + model = RealmReader.from_pretrained("google/realm-orqa-nq-reader", config=config) + + concat_input_ids = torch.arange(10).view((2, 5)) + concat_token_type_ids = torch.tensor([[0, 0, 1, 1, 1], [0, 0, 1, 1, 1]], dtype=torch.int64) + concat_block_mask = torch.tensor([[0, 0, 1, 1, 0], [0, 0, 1, 1, 0]], dtype=torch.int64) + relevance_score = torch.tensor([0.3, 0.7], dtype=torch.float32) + + output = model( + concat_input_ids, + token_type_ids=concat_token_type_ids, + relevance_score=relevance_score, + block_mask=concat_block_mask, + return_dict=True, + ) + + block_idx_expected_shape = torch.Size(()) + start_pos_expected_shape = torch.Size((1,)) + end_pos_expected_shape = torch.Size((1,)) + self.assertEqual(output.block_idx.shape, block_idx_expected_shape) + self.assertEqual(output.start_pos.shape, start_pos_expected_shape) + self.assertEqual(output.end_pos.shape, end_pos_expected_shape) + + expected_block_idx = torch.tensor(1) + expected_start_pos = torch.tensor(3) + expected_end_pos = torch.tensor(3) + + self.assertTrue(torch.allclose(output.block_idx, expected_block_idx, atol=1e-4)) + self.assertTrue(torch.allclose(output.start_pos, expected_start_pos, atol=1e-4)) + self.assertTrue(torch.allclose(output.end_pos, expected_end_pos, atol=1e-4)) + + @slow + def test_inference_scorer(self): + num_candidates = 2 + + model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer", num_candidates=num_candidates) + + input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) + candidate_input_ids = torch.tensor([[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) + output = model(input_ids, candidate_input_ids=candidate_input_ids)[0] + + expected_shape = torch.Size((1, 2)) + self.assertEqual(output.shape, expected_shape) + + expected_slice = torch.tensor([[0.7410, 0.7170]]) + self.assertTrue(torch.allclose(output, expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_retrieval_realm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_retrieval_realm.py new file mode 100644 index 0000000000000000000000000000000000000000..ba65a6afdd6771fbc33472f615e079ba81b71975 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_retrieval_realm.py @@ -0,0 +1,187 @@ +# coding=utf-8 +# Copyright 2022 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 os +import shutil +import tempfile +from unittest import TestCase +from unittest.mock import patch + +import numpy as np +from datasets import Dataset + +from transformers.models.realm.configuration_realm import RealmConfig +from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever +from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer + + +class RealmRetrieverTest(TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + self.num_block_records = 5 + + # Realm tok + vocab_tokens = [ + "[UNK]", + "[CLS]", + "[SEP]", + "[PAD]", + "[MASK]", + "test", + "question", + "this", + "is", + "the", + "first", + "second", + "third", + "fourth", + "fifth", + "record", + "want", + "##want", + "##ed", + "wa", + "un", + "runn", + "##ing", + ",", + "low", + "lowest", + ] + realm_tokenizer_path = os.path.join(self.tmpdirname, "realm_tokenizer") + os.makedirs(realm_tokenizer_path, exist_ok=True) + self.vocab_file = os.path.join(realm_tokenizer_path, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + realm_block_records_path = os.path.join(self.tmpdirname, "realm_block_records") + os.makedirs(realm_block_records_path, exist_ok=True) + + def get_tokenizer(self) -> RealmTokenizer: + return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname, "realm_tokenizer")) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def get_config(self): + config = RealmConfig(num_block_records=self.num_block_records) + return config + + def get_dummy_dataset(self): + dataset = Dataset.from_dict( + { + "id": ["0", "1"], + "question": ["foo", "bar"], + "answers": [["Foo", "Bar"], ["Bar"]], + } + ) + return dataset + + def get_dummy_block_records(self): + block_records = np.array( + [ + b"This is the first record", + b"This is the second record", + b"This is the third record", + b"This is the fourth record", + b"This is the fifth record", + b"This is a longer longer longer record", + ], + dtype=object, + ) + return block_records + + def get_dummy_retriever(self): + retriever = RealmRetriever( + block_records=self.get_dummy_block_records(), + tokenizer=self.get_tokenizer(), + ) + return retriever + + def test_retrieve(self): + config = self.get_config() + retriever = self.get_dummy_retriever() + tokenizer = retriever.tokenizer + + retrieved_block_ids = np.array([0, 3], dtype="long") + question_input_ids = tokenizer(["Test question"]).input_ids + answer_ids = tokenizer( + ["the fourth"], + add_special_tokens=False, + return_token_type_ids=False, + return_attention_mask=False, + ).input_ids + max_length = config.reader_seq_len + + has_answers, start_pos, end_pos, concat_inputs = retriever( + retrieved_block_ids, question_input_ids, answer_ids=answer_ids, max_length=max_length, return_tensors="np" + ) + + self.assertEqual(len(has_answers), 2) + self.assertEqual(len(start_pos), 2) + self.assertEqual(len(end_pos), 2) + self.assertEqual(concat_inputs.input_ids.shape, (2, 10)) + self.assertEqual(concat_inputs.attention_mask.shape, (2, 10)) + self.assertEqual(concat_inputs.token_type_ids.shape, (2, 10)) + self.assertEqual(concat_inputs.special_tokens_mask.shape, (2, 10)) + self.assertEqual( + tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0]), + ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"], + ) + self.assertEqual( + tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1]), + ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"], + ) + + def test_block_has_answer(self): + config = self.get_config() + retriever = self.get_dummy_retriever() + tokenizer = retriever.tokenizer + + retrieved_block_ids = np.array([0, 3, 5], dtype="long") + question_input_ids = tokenizer(["Test question"]).input_ids + answer_ids = tokenizer( + ["the fourth", "longer longer"], + add_special_tokens=False, + return_token_type_ids=False, + return_attention_mask=False, + ).input_ids + max_length = config.reader_seq_len + + has_answers, start_pos, end_pos, _ = retriever( + retrieved_block_ids, question_input_ids, answer_ids=answer_ids, max_length=max_length, return_tensors="np" + ) + + self.assertEqual([False, True, True], has_answers) + self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]], start_pos) + self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]], end_pos) + + def test_save_load_pretrained(self): + retriever = self.get_dummy_retriever() + retriever.save_pretrained(os.path.join(self.tmpdirname, "realm_block_records")) + + # Test local path + retriever = retriever.from_pretrained(os.path.join(self.tmpdirname, "realm_block_records")) + self.assertEqual(retriever.block_records[0], b"This is the first record") + + # Test mocked remote path + with patch("transformers.models.realm.retrieval_realm.hf_hub_download") as mock_hf_hub_download: + mock_hf_hub_download.return_value = os.path.join( + os.path.join(self.tmpdirname, "realm_block_records"), _REALM_BLOCK_RECORDS_FILENAME + ) + retriever = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa") + + self.assertEqual(retriever.block_records[0], b"This is the first record") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_tokenization_realm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_tokenization_realm.py new file mode 100644 index 0000000000000000000000000000000000000000..6a5a3878fd4354d112950958167567d83e210171 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/realm/test_tokenization_realm.py @@ -0,0 +1,321 @@ +# coding=utf-8 +# Copyright 2022 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 os +import unittest + +from transformers import RealmTokenizerFast +from transformers.models.bert.tokenization_bert import ( + VOCAB_FILES_NAMES, + BasicTokenizer, + WordpieceTokenizer, + _is_control, + _is_punctuation, + _is_whitespace, +) +from transformers.models.realm.tokenization_realm import RealmTokenizer +from transformers.testing_utils import require_tokenizers, slow + +from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english + + +@require_tokenizers +class RealmTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = RealmTokenizer + rust_tokenizer_class = RealmTokenizerFast + test_rust_tokenizer = True + space_between_special_tokens = True + from_pretrained_filter = filter_non_english + + def setUp(self): + super().setUp() + + vocab_tokens = [ + "[UNK]", + "[CLS]", + "[SEP]", + "[PAD]", + "[MASK]", + "want", + "##want", + "##ed", + "wa", + "un", + "runn", + "##ing", + ",", + "low", + "lowest", + ] + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def get_input_output_texts(self, tokenizer): + input_text = "UNwant\u00E9d,running" + output_text = "unwanted, running" + return input_text, output_text + + def test_full_tokenizer(self): + tokenizer = self.tokenizer_class(self.vocab_file) + + tokens = tokenizer.tokenize("UNwant\u00E9d,running") + self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"]) + self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [9, 6, 7, 12, 10, 11]) + + def test_rust_and_python_full_tokenizers(self): + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + sequence = "UNwant\u00E9d,running" + + tokens = tokenizer.tokenize(sequence) + rust_tokens = rust_tokenizer.tokenize(sequence) + self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + rust_tokenizer = self.get_rust_tokenizer() + ids = tokenizer.encode(sequence) + rust_ids = rust_tokenizer.encode(sequence) + self.assertListEqual(ids, rust_ids) + + # With lower casing + tokenizer = self.get_tokenizer(do_lower_case=True) + rust_tokenizer = self.get_rust_tokenizer(do_lower_case=True) + + sequence = "UNwant\u00E9d,running" + + tokens = tokenizer.tokenize(sequence) + rust_tokens = rust_tokenizer.tokenize(sequence) + self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + rust_tokenizer = self.get_rust_tokenizer() + ids = tokenizer.encode(sequence) + rust_ids = rust_tokenizer.encode(sequence) + self.assertListEqual(ids, rust_ids) + + def test_chinese(self): + tokenizer = BasicTokenizer() + + self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"), ["ah", "\u535A", "\u63A8", "zz"]) + + def test_basic_tokenizer_lower(self): + tokenizer = BasicTokenizer(do_lower_case=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["hello", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_lower_strip_accents_false(self): + tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hällo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["h\u00E9llo"]) + + def test_basic_tokenizer_lower_strip_accents_true(self): + tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_lower_strip_accents_default(self): + tokenizer = BasicTokenizer(do_lower_case=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_no_lower(self): + tokenizer = BasicTokenizer(do_lower_case=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["HeLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_no_lower_strip_accents_false(self): + tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HäLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_no_lower_strip_accents_true(self): + tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HaLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_respects_never_split_tokens(self): + tokenizer = BasicTokenizer(do_lower_case=False, never_split=["[UNK]"]) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]"), ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] + ) + + def test_wordpiece_tokenizer(self): + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] + + vocab = {} + for i, token in enumerate(vocab_tokens): + vocab[token] = i + tokenizer = WordpieceTokenizer(vocab=vocab, unk_token="[UNK]") + + self.assertListEqual(tokenizer.tokenize(""), []) + + self.assertListEqual(tokenizer.tokenize("unwanted running"), ["un", "##want", "##ed", "runn", "##ing"]) + + self.assertListEqual(tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"]) + + def test_is_whitespace(self): + self.assertTrue(_is_whitespace(" ")) + self.assertTrue(_is_whitespace("\t")) + self.assertTrue(_is_whitespace("\r")) + self.assertTrue(_is_whitespace("\n")) + self.assertTrue(_is_whitespace("\u00A0")) + + self.assertFalse(_is_whitespace("A")) + self.assertFalse(_is_whitespace("-")) + + def test_is_control(self): + self.assertTrue(_is_control("\u0005")) + + self.assertFalse(_is_control("A")) + self.assertFalse(_is_control(" ")) + self.assertFalse(_is_control("\t")) + self.assertFalse(_is_control("\r")) + + def test_is_punctuation(self): + self.assertTrue(_is_punctuation("-")) + self.assertTrue(_is_punctuation("$")) + self.assertTrue(_is_punctuation("`")) + self.assertTrue(_is_punctuation(".")) + + self.assertFalse(_is_punctuation("A")) + self.assertFalse(_is_punctuation(" ")) + + def test_clean_text(self): + tokenizer = self.get_tokenizer() + + # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 + self.assertListEqual([tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], [], ["[UNK]"]]) + + if self.test_rust_tokenizer: + rust_tokenizer = self.get_rust_tokenizer() + self.assertListEqual( + [rust_tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], [], ["[UNK]"]] + ) + + @slow + def test_sequence_builders(self): + tokenizer = self.tokenizer_class.from_pretrained("bert-base-uncased") + + text = tokenizer.encode("sequence builders", add_special_tokens=False) + text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False) + + encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_sentence == [101] + text + [102] + assert encoded_pair == [101] + text + [102] + text_2 + [102] + + def test_offsets_with_special_characters(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) + + sentence = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." + tokens = tokenizer_r.encode_plus( + sentence, + return_attention_mask=False, + return_token_type_ids=False, + return_offsets_mapping=True, + add_special_tokens=True, + ) + + do_lower_case = tokenizer_r.do_lower_case if hasattr(tokenizer_r, "do_lower_case") else False + expected_results = ( + [ + ((0, 0), tokenizer_r.cls_token), + ((0, 1), "A"), + ((1, 2), ","), + ((3, 5), "na"), + ((5, 6), "##ï"), + ((6, 8), "##ve"), + ((9, 15), tokenizer_r.mask_token), + ((16, 21), "Allen"), + ((21, 23), "##NL"), + ((23, 24), "##P"), + ((25, 33), "sentence"), + ((33, 34), "."), + ((0, 0), tokenizer_r.sep_token), + ] + if not do_lower_case + else [ + ((0, 0), tokenizer_r.cls_token), + ((0, 1), "a"), + ((1, 2), ","), + ((3, 8), "naive"), + ((9, 15), tokenizer_r.mask_token), + ((16, 21), "allen"), + ((21, 23), "##nl"), + ((23, 24), "##p"), + ((25, 33), "sentence"), + ((33, 34), "."), + ((0, 0), tokenizer_r.sep_token), + ] + ) + + self.assertEqual( + [e[1] for e in expected_results], tokenizer_r.convert_ids_to_tokens(tokens["input_ids"]) + ) + self.assertEqual([e[0] for e in expected_results], tokens["offset_mapping"]) + + @slow + def test_batch_encode_candidates(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) + text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]] + + encoded_sentence_r = tokenizer_r.batch_encode_candidates(text, max_length=10, return_tensors="np") + encoded_sentence_p = tokenizer_p.batch_encode_candidates(text, max_length=10, return_tensors="np") + + expected_shape = (2, 2, 10) + + self.assertEqual(encoded_sentence_r["input_ids"].shape, expected_shape) + self.assertEqual(encoded_sentence_r["attention_mask"].shape, expected_shape) + self.assertEqual(encoded_sentence_r["token_type_ids"].shape, expected_shape) + + self.assertEqual(encoded_sentence_p["input_ids"].shape, expected_shape) + self.assertEqual(encoded_sentence_p["attention_mask"].shape, expected_shape) + self.assertEqual(encoded_sentence_p["token_type_ids"].shape, expected_shape) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_modeling_reformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_modeling_reformer.py new file mode 100644 index 0000000000000000000000000000000000000000..11cd7e1a33b45af07d98740313cfd1cf62fe3fd6 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_modeling_reformer.py @@ -0,0 +1,1305 @@ +# coding=utf-8 # Copyright 2020 Huggingface +# +# 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 unittest + +from transformers import ReformerConfig, is_torch_available +from transformers.testing_utils import ( + require_sentencepiece, + require_tokenizers, + require_torch, + require_torch_fp16, + require_torch_multi_gpu, + slow, + torch_device, +) + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ( + REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, + ReformerForMaskedLM, + ReformerForQuestionAnswering, + ReformerForSequenceClassification, + ReformerLayer, + ReformerModel, + ReformerModelWithLMHead, + ReformerTokenizer, + ) + + +class ReformerModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=32, + is_training=True, + is_decoder=True, + use_input_mask=True, + use_labels=True, + vocab_size=32, + attention_head_size=16, + hidden_size=32, + num_attention_heads=2, + local_attn_chunk_length=4, + local_num_chunks_before=1, + local_num_chunks_after=0, + num_buckets=None, + num_hashes=1, + lsh_attn_chunk_length=None, + lsh_num_chunks_before=None, + lsh_num_chunks_after=None, + chunk_size_lm_head=0, + chunk_size_feed_forward=0, + feed_forward_size=32, + hidden_act="gelu", + hidden_dropout_prob=0.1, + local_attention_probs_dropout_prob=0.1, + lsh_attention_probs_dropout_prob=None, + max_position_embeddings=512, + initializer_range=0.02, + axial_norm_std=1.0, + layer_norm_eps=1e-12, + axial_pos_embds=True, + axial_pos_shape=[4, 8], + axial_pos_embds_dim=[16, 16], + attn_layers=["local", "local", "local", "local"], + pad_token_id=0, + eos_token_id=2, + scope=None, + hash_seed=0, + num_labels=2, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.is_decoder = is_decoder + self.use_input_mask = use_input_mask + self.use_labels = use_labels + self.vocab_size = vocab_size + self.attention_head_size = attention_head_size + self.hidden_size = hidden_size + self.num_attention_heads = num_attention_heads + self.num_hidden_layers = len(attn_layers) if attn_layers is not None else 0 + self.local_attn_chunk_length = local_attn_chunk_length + self.local_num_chunks_after = local_num_chunks_after + self.local_num_chunks_before = local_num_chunks_before + self.num_hashes = num_hashes + self.num_buckets = tuple(num_buckets) if isinstance(num_buckets, list) else num_buckets + self.lsh_attn_chunk_length = lsh_attn_chunk_length + self.lsh_num_chunks_after = lsh_num_chunks_after + self.lsh_num_chunks_before = lsh_num_chunks_before + self.hidden_act = hidden_act + self.feed_forward_size = feed_forward_size + self.hidden_dropout_prob = hidden_dropout_prob + self.local_attention_probs_dropout_prob = local_attention_probs_dropout_prob + self.lsh_attention_probs_dropout_prob = lsh_attention_probs_dropout_prob + self.max_position_embeddings = max_position_embeddings + self.initializer_range = initializer_range + self.layer_norm_eps = layer_norm_eps + self.axial_pos_embds = axial_pos_embds + self.axial_pos_shape = tuple(axial_pos_shape) + self.axial_pos_embds_dim = tuple(axial_pos_embds_dim) + self.axial_norm_std = axial_norm_std + self.chunk_size_lm_head = chunk_size_lm_head + self.chunk_size_feed_forward = chunk_size_feed_forward + self.scope = scope + self.attn_layers = attn_layers + self.pad_token_id = pad_token_id + self.hash_seed = hash_seed + + attn_chunk_length = local_attn_chunk_length if local_attn_chunk_length is not None else lsh_attn_chunk_length + num_chunks_after = local_num_chunks_after if local_num_chunks_after is not None else lsh_num_chunks_after + num_chunks_before = local_num_chunks_before if local_num_chunks_before is not None else lsh_num_chunks_before + + self.encoder_seq_length = seq_length // attn_chunk_length + (self.seq_length % attn_chunk_length != 0) + self.key_length = (num_chunks_before + num_chunks_after + 1) * attn_chunk_length + self.chunk_length = attn_chunk_length + self.num_labels = num_labels + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + choice_labels = None + if self.use_labels: + choice_labels = ids_tensor([self.batch_size], 2) + + config = self.get_config() + + return ( + config, + input_ids, + input_mask, + choice_labels, + ) + + def get_config(self): + return ReformerConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + feed_forward_size=self.feed_forward_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + local_attention_probs_dropout_prob=self.local_attention_probs_dropout_prob, + lsh_attention_probs_dropout_prob=self.lsh_attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + is_decoder=self.is_decoder, + axial_pos_embds=self.axial_pos_embds, + axial_pos_shape=self.axial_pos_shape, + axial_pos_embds_dim=self.axial_pos_embds_dim, + local_attn_chunk_length=self.local_attn_chunk_length, + local_num_chunks_after=self.local_num_chunks_after, + local_num_chunks_before=self.local_num_chunks_before, + num_hashes=self.num_hashes, + num_buckets=self.num_buckets, + lsh_attn_chunk_length=self.lsh_attn_chunk_length, + lsh_num_chunks_after=self.lsh_num_chunks_after, + lsh_num_chunks_before=self.lsh_num_chunks_before, + attn_layers=self.attn_layers, + pad_token_id=self.pad_token_id, + hash_seed=self.hash_seed, + ) + + def get_pipeline_config(self): + config = self.get_config() + config.vocab_size = 100 + config.max_position_embeddings = 100 + config.axial_pos_shape = (4, 25) + config.is_decoder = False + return config + + def create_and_check_reformer_model(self, config, input_ids, input_mask, choice_labels): + model = ReformerModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask) + result = model(input_ids) + + # 2 * hidden_size because we use reversible resnet layers + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.seq_length, 2 * self.hidden_size) + ) + + def create_and_check_reformer_model_with_lm_backward(self, config, input_ids, input_mask, choice_labels): + if not self.is_training: + return + + config.is_decoder = False + config.lsh_num_chunks_after = 1 + model = ReformerForMaskedLM(config=config) + model.to(torch_device) + model.train() + loss = model(input_ids, attention_mask=input_mask, labels=input_ids)["loss"] + loss.backward() + + def create_and_check_reformer_with_lm(self, config, input_ids, input_mask, choice_labels): + config.lsh_num_chunks_after = 0 + config.is_decoder = True + model = ReformerModelWithLMHead(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, labels=input_ids) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_reformer_with_mlm(self, config, input_ids, input_mask, choice_labels): + config.is_decoder = False + model = ReformerForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, labels=input_ids) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_reformer_model_with_attn_mask( + self, config, input_ids, input_mask, choice_labels, is_decoder=False + ): + # no special position embeddings + config.axial_pos_embds = False + config.is_decoder = is_decoder + + if self.lsh_attn_chunk_length is not None: + # need to set chunk length equal sequence length to be certain that chunking works + config.lsh_attn_chunk_length = self.seq_length + + model = ReformerModel(config=config) + model.to(torch_device) + model.eval() + # set all position encodings to zero so that postions don't matter + with torch.no_grad(): + embedding = model.embeddings.position_embeddings.embedding + embedding.weight = nn.Parameter(torch.zeros(embedding.weight.shape).to(torch_device)) + embedding.weight.requires_grad = False + + half_seq_len = self.seq_length // 2 + roll = self.chunk_length + + half_input_ids = input_ids[:, :half_seq_len] + + # normal padded + attn_mask = torch.cat( + [torch.ones_like(half_input_ids), torch.zeros_like(half_input_ids)], + dim=-1, + ) + input_ids_padded = torch.cat( + [half_input_ids, ids_tensor((self.batch_size, half_seq_len), self.vocab_size)], + dim=-1, + ) + + # shifted padded + input_ids_roll = torch.cat( + [half_input_ids, ids_tensor((self.batch_size, half_seq_len), self.vocab_size)], + dim=-1, + ) + input_ids_roll = torch.roll(input_ids_roll, roll, dims=-1) + attn_mask_roll = torch.roll(attn_mask, roll, dims=-1) + + output_padded = model(input_ids_padded, attention_mask=attn_mask)[0][:, :half_seq_len] + output_padded_rolled = model(input_ids_roll, attention_mask=attn_mask_roll)[0][:, roll : half_seq_len + roll] + + self.parent.assertTrue(torch.allclose(output_padded, output_padded_rolled, atol=1e-3)) + + def create_and_check_reformer_layer_dropout_seed( + self, config, input_ids, input_mask, choice_labels, is_decoder=False + ): + config.is_decoder = is_decoder + layer = ReformerLayer(config).to(torch_device) + layer.train() + shape = ( + self.batch_size, + self.seq_length, + config.hidden_size, + ) # Batch x SeqLen x hiddenSize + + # get random tensors + hidden_states = floats_tensor(shape) + prev_attn_output = floats_tensor(shape) + + # now the random seeds for attention and feed forward is initialized + # forward tensors with dropout + layer_outputs = layer(prev_attn_output, hidden_states, attention_mask=input_mask) + + next_attn_output = layer_outputs.attn_output + next_hidden_states = layer_outputs.hidden_states + + torch.manual_seed(layer.attention_seed) + attn_outputs = layer.attention(hidden_states, attention_mask=input_mask) + self.parent.assertTrue( + torch.allclose( + prev_attn_output + attn_outputs.hidden_states, + next_attn_output, + atol=1e-3, + ) + ) + + torch.manual_seed(layer.feed_forward_seed) + feed_forward_hidden_states = layer.feed_forward(next_attn_output) + self.parent.assertTrue( + torch.allclose( + next_hidden_states, + hidden_states + feed_forward_hidden_states, + atol=1e-3, + ) + ) + + def create_and_check_reformer_feed_backward_chunking(self, config, input_ids, input_mask, choice_labels): + if not self.is_training: + return + + # disable dropout + config.hidden_dropout_prob = 0 + config.local_attention_probs_dropout_prob = 0 + config.lsh_attention_probs_dropout_prob = 0 + config.lsh_num_chunks_after = 1 + config.is_decoder = False + + torch.manual_seed(0) + model = ReformerForMaskedLM(config=config) + model.to(torch_device) + model.train() + model.zero_grad() + loss_no_chunk, output_no_chunk = model(input_ids, labels=input_ids, attention_mask=input_mask)[:2] + loss_no_chunk.backward() + grad_slice_word_no_chunk = model.reformer.embeddings.word_embeddings.weight.grad[0, :5] + grad_slice_position_factor_1_no_chunk = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:] + grad_slice_position_factor_2_no_chunk = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5] + + config.chunk_size_lm_head = 1 + config.chunk_size_feed_forward = 1 + + torch.manual_seed(0) + model = ReformerForMaskedLM(config=config) + model.to(torch_device) + model.train() + model.zero_grad() + loss_chunk, output_chunk = model(input_ids, labels=input_ids, attention_mask=input_mask)[:2] + loss_chunk.backward() + grad_slice_word_chunk = model.reformer.embeddings.word_embeddings.weight.grad[0, :5] + grad_slice_position_factor_1_chunk = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:] + grad_slice_position_factor_2_chunk = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5] + self.parent.assertTrue(torch.allclose(loss_chunk, loss_no_chunk, atol=1e-3)) + self.parent.assertTrue(torch.allclose(grad_slice_word_no_chunk, grad_slice_word_chunk, atol=1e-3)) + self.parent.assertTrue( + torch.allclose(grad_slice_position_factor_1_chunk, grad_slice_position_factor_1_no_chunk, atol=1e-3) + ) + self.parent.assertTrue( + torch.allclose(grad_slice_position_factor_2_chunk, grad_slice_position_factor_2_no_chunk, atol=1e-3) + ) + + def create_and_check_reformer_random_seed(self, config, input_ids, input_mask, choice_labels): + layer = ReformerLayer(config).to(torch_device) + layer.train() + + shape = ( + self.batch_size, + self.seq_length, + config.hidden_size, + ) # Batch x SeqLen x hiddenSize + + hidden_states = floats_tensor(shape) + attn_output = floats_tensor(shape) + + seeds = [] + for _ in range(100): + layer_outputs = layer(attn_output, hidden_states, attention_mask=input_mask) + attn_output = layer_outputs.attn_output + hidden_states = layer_outputs.hidden_states + torch.manual_seed(layer.attention_seed) + seeds.append(layer.attention_seed) + self.parent.assertGreater(len(set(seeds)), 70) + + seeds = [] + for _ in range(100): + layer_outputs = layer(attn_output, hidden_states, attention_mask=input_mask) + attn_output = layer_outputs.attn_output + hidden_states = layer_outputs.hidden_states + torch.manual_seed(layer.feed_forward_seed) + seeds.append(layer.feed_forward_seed) + self.parent.assertGreater(len(set(seeds)), 70) + + def create_and_check_reformer_model_fp16_forward(self, config, input_ids, input_mask, choice_labels): + model = ReformerModel(config=config) + model.to(torch_device) + model.half() + model.eval() + output = model(input_ids, attention_mask=input_mask)["last_hidden_state"] + self.parent.assertFalse(torch.isnan(output).any().item()) + + def create_and_check_reformer_model_generate(self, config, input_ids, input_mask, choice_labels): + config.is_decoder = True + config.lsh_num_chunks_after = 0 + config.bos_token_id = 0 + config.eos_token_id = None + config.max_length = 20 + + model = ReformerModelWithLMHead(config=config) + model.to(torch_device) + model.eval() + output = model.generate() + self.parent.assertIsNotNone(output) + + def create_and_check_reformer_model_fp16_generate(self, config, input_ids, input_mask, choice_labels): + config.is_decoder = True + config.lsh_num_chunks_after = 0 + model = ReformerModelWithLMHead(config=config) + model.to(torch_device) + model.half() + model.eval() + # only use last 10 inputs for generation + output = model.generate(input_ids[:, -10:], attention_mask=input_mask, do_sample=False) + self.parent.assertFalse(torch.isnan(output).any().item()) + + def create_and_check_reformer_no_chunking(self, config, input_ids, input_mask, choice_labels): + # force chunk length to be bigger than input_ids + config.lsh_attn_chunk_length = 2 * input_ids.shape[-1] + config.local_attn_chunk_length = 2 * input_ids.shape[-1] + config.lsh_num_chunks_after = 1 + config.is_decoder = False + model = ReformerForMaskedLM(config=config) + model.to(torch_device) + model.eval() + output_logits = model(input_ids, attention_mask=input_mask)["logits"] + self.parent.assertTrue(output_logits.shape[1] == input_ids.shape[-1]) + + def create_and_check_reformer_for_question_answering(self, config, input_ids, input_mask, choice_labels): + model = ReformerForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + start_positions=choice_labels, + end_positions=choice_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_past_buckets_states(self, config, input_ids, input_mask, choice_labels): + config.is_decoder = True + config.lsh_num_chunks_before = 1 + config.lsh_num_chunks_after = 0 + model = ReformerModelWithLMHead(config=config) + model.to(torch_device) + model.eval() + input_ids_first = input_ids[:, :-1] + input_ids_second = input_ids[:, -1:] + + # return saved cache + past_buckets_states = model(input_ids_first, use_cache=True)["past_buckets_states"] + + # calculate last output with and without cache + outputs_with_cache = model(input_ids_second, past_buckets_states=past_buckets_states, use_cache=True)["logits"] + outputs_without_cache = model(input_ids)["logits"][:, -1] + + # select random slice idx + random_slice_idx = torch.randint(outputs_without_cache.shape[-1], (1, 1), device=torch_device).item() + + # outputs should be similar within range + self.parent.assertTrue( + torch.allclose( + outputs_with_cache[:, 0, random_slice_idx], outputs_without_cache[:, random_slice_idx], atol=1e-2 + ) + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + (config, input_ids, input_mask, choice_labels) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} + return config, inputs_dict + + def create_and_check_reformer_for_sequence_classification( + self, config, input_ids, input_mask, choice_labels, is_decoder + ): + config.is_decoder = is_decoder + sequence_labels = ids_tensor([self.batch_size], config.num_labels) + model = ReformerForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, labels=sequence_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + +class ReformerTesterMixin: + """ + Reformer Local and Reformer LSH run essentially the same tests + """ + + def test_config(self): + self.config_tester.run_common_tests() + + def test_reformer_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_model(*config_and_inputs) + + def test_reformer_lm_model_backward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_model_with_lm_backward(*config_and_inputs) + + def test_reformer_model_attn_masking(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_model_with_attn_mask(*config_and_inputs, is_decoder=True) + self.model_tester.create_and_check_reformer_model_with_attn_mask(*config_and_inputs, is_decoder=False) + + def test_reformer_with_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_with_lm(*config_and_inputs) + + def test_reformer_with_mlm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_with_mlm(*config_and_inputs) + + def test_reformer_layer_training_dropout(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_layer_dropout_seed(*config_and_inputs, is_decoder=True) + self.model_tester.create_and_check_reformer_layer_dropout_seed(*config_and_inputs, is_decoder=False) + + def test_reformer_chunking_backward_equality(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_feed_backward_chunking(*config_and_inputs) + + def test_reformer_no_chunking(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_no_chunking(*config_and_inputs) + + def test_reformer_qa_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_for_question_answering(*config_and_inputs) + + def test_reformer_cached_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_past_buckets_states(*config_and_inputs) + + def test_reformer_cached_generate(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_model_generate(*config_and_inputs) + + @slow + def test_dropout_random_seed_is_changing(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_random_seed(*config_and_inputs) + + @require_torch_fp16 + def test_reformer_model_fp16_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_model_fp16_forward(*config_and_inputs) + + @require_torch_fp16 + def test_reformer_model_fp16_generate(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_model_fp16_generate(*config_and_inputs) + + @require_torch_multi_gpu + @unittest.skip( + reason=( + "Reformer does not work with data parallel (DP) because of a bug in PyTorch:" + " https://github.com/pytorch/pytorch/issues/36035" + ) + ) + def test_multi_gpu_data_parallel_forward(self): + pass + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_reformer_for_sequence_classification(*config_and_inputs, is_decoder=False) + + def test_retain_grad_hidden_states_attentions(self): + # reformer cannot keep gradients in attentions or hidden states + return + + def test_resize_embeddings_untied(self): + # reformer cannot resize embeddings that easily + return + + +@require_torch +class ReformerLocalAttnModelTest(ReformerTesterMixin, GenerationTesterMixin, ModelTesterMixin, unittest.TestCase): + all_model_classes = ( + (ReformerModel, ReformerModelWithLMHead, ReformerForSequenceClassification, ReformerForQuestionAnswering) + if is_torch_available() + else () + ) + all_generative_model_classes = (ReformerModelWithLMHead,) if is_torch_available() else () + test_pruning = False + test_headmasking = False + test_torchscript = False + test_sequence_classification_problem_types = True + + def setUp(self): + self.model_tester = ReformerModelTester(self) + self.config_tester = ConfigTester(self, config_class=ReformerConfig, hidden_size=37) + + @slow + def test_model_from_pretrained(self): + for model_name in REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = ReformerModelWithLMHead.from_pretrained(model_name) + self.assertIsNotNone(model) + + def _check_attentions_for_generate( + self, batch_size, attentions, min_length, max_length, config, use_cache=False, num_beam_groups=1 + ): + self.assertIsInstance(attentions, tuple) + self.assertListEqual( + [isinstance(iter_attentions, list) for iter_attentions in attentions], [True] * len(attentions) + ) + self.assertEqual(len(attentions), (max_length - min_length) * num_beam_groups) + + for idx, iter_attentions in enumerate(attentions): + tgt_len = min_length + idx if not use_cache else 1 + num_chunks = tgt_len // config.local_attn_chunk_length + (tgt_len % config.local_attn_chunk_length != 0) + tgt_chunk_len = config.local_attn_chunk_length + src_chunk_len = config.local_attn_chunk_length * ( + 1 + config.local_num_chunks_after + config.local_num_chunks_before + ) + + if use_cache: + expected_shape = ( + batch_size * num_beam_groups, + config.num_attention_heads, + tgt_len, + min_length // config.local_attn_chunk_length + 1 + idx, + ) + else: + expected_shape = ( + batch_size * num_beam_groups, + config.num_attention_heads, + num_chunks, + tgt_chunk_len, + src_chunk_len, + ) + # check attn size + self.assertListEqual( + [layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(iter_attentions) + ) + + def _check_hidden_states_for_generate( + self, batch_size, hidden_states, min_length, max_length, config, use_cache=False, num_beam_groups=1 + ): + self.assertIsInstance(hidden_states, tuple) + self.assertListEqual( + [isinstance(iter_hidden_states, list) for iter_hidden_states in hidden_states], + [True] * len(hidden_states), + ) + self.assertEqual(len(hidden_states), (max_length - min_length) * num_beam_groups) + + for idx, iter_hidden_states in enumerate(hidden_states): + seq_len = min_length + idx + seq_len = config.local_attn_chunk_length * ( + seq_len // config.local_attn_chunk_length + (seq_len % config.local_attn_chunk_length != 0) + ) + + if use_cache: + seq_len = 1 + + expected_shape = (batch_size * num_beam_groups, seq_len, config.hidden_size) + # check hidden size + self.assertListEqual( + [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states], + [expected_shape] * len(iter_hidden_states), + ) + + @unittest.skip("The model doesn't support left padding") # and it's not used enough to be worth fixing :) + def test_left_padding_compatibility(self): + pass + + +@require_torch +class ReformerLSHAttnModelTest( + ReformerTesterMixin, ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase +): + all_model_classes = ( + (ReformerModel, ReformerModelWithLMHead, ReformerForSequenceClassification, ReformerForQuestionAnswering) + if is_torch_available() + else () + ) + all_generative_model_classes = (ReformerModelWithLMHead,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": ReformerModel, + "fill-mask": ReformerForMaskedLM, + "question-answering": ReformerForQuestionAnswering, + "text-classification": ReformerForSequenceClassification, + "text-generation": ReformerModelWithLMHead, + "zero-shot": ReformerForSequenceClassification, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_headmasking = False + test_torchscript = False + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if ( + pipeline_test_casse_name == "QAPipelineTests" + and tokenizer_name is not None + and not tokenizer_name.endswith("Fast") + ): + # `QAPipelineTests` fails for a few models when the slower tokenizer are used. + # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) + # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer + return True + + return False + + def setUp(self): + self.model_tester = ReformerModelTester( + self, + batch_size=13, + seq_length=13, + use_input_mask=True, + use_labels=True, + is_training=False, + is_decoder=True, + vocab_size=32, + attention_head_size=16, + hidden_size=64, + num_attention_heads=2, + num_buckets=2, + num_hashes=4, + lsh_attn_chunk_length=4, + lsh_num_chunks_before=1, + lsh_num_chunks_after=0, + chunk_size_lm_head=5, + chunk_size_feed_forward=6, + feed_forward_size=32, + hidden_act="relu", + hidden_dropout_prob=0.1, + lsh_attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + initializer_range=0.02, + axial_norm_std=1.0, + layer_norm_eps=1e-12, + axial_pos_embds=True, + axial_pos_shape=[4, 8], + axial_pos_embds_dim=[16, 48], + # sanotheu + # attn_layers=[lsh,lsh,lsh,lsh], + attn_layers=["lsh"], + pad_token_id=0, + eos_token_id=2, + scope=None, + hash_seed=0, + num_labels=2, + ) + self.config_tester = ConfigTester(self, config_class=ReformerConfig, hidden_size=37) + + def _check_attentions_for_generate( + self, batch_size, attentions, min_length, max_length, config, use_cache=False, num_beam_groups=1 + ): + self.assertIsInstance(attentions, tuple) + self.assertListEqual( + [isinstance(iter_attentions, list) for iter_attentions in attentions], [True] * len(attentions) + ) + self.assertEqual(len(attentions), (max_length - min_length) * num_beam_groups) + + for idx, iter_attentions in enumerate(attentions): + tgt_len = min_length + idx if not use_cache else 1 + num_chunks = tgt_len // config.lsh_attn_chunk_length + (tgt_len % config.lsh_attn_chunk_length != 0) + tgt_chunk_len = config.lsh_attn_chunk_length + src_chunk_len = config.lsh_attn_chunk_length * ( + 1 + config.lsh_num_chunks_after + config.lsh_num_chunks_before + ) + + if use_cache: + expected_shape = ( + batch_size * num_beam_groups, + config.num_attention_heads, + config.num_hashes, + tgt_len, + config.num_hashes * (1 + config.lsh_num_chunks_after + config.lsh_num_chunks_before), + ) + else: + expected_shape = ( + batch_size * num_beam_groups, + config.num_attention_heads, + num_chunks * config.num_hashes, + tgt_chunk_len, + src_chunk_len, + ) + # check attn size + self.assertListEqual( + [layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(iter_attentions) + ) + + def _check_hidden_states_for_generate( + self, batch_size, hidden_states, min_length, max_length, config, use_cache=False, num_beam_groups=1 + ): + self.assertIsInstance(hidden_states, tuple) + self.assertListEqual( + [isinstance(iter_hidden_states, list) for iter_hidden_states in hidden_states], + [True] * len(hidden_states), + ) + self.assertEqual(len(hidden_states), (max_length - min_length) * num_beam_groups) + + for idx, iter_hidden_states in enumerate(hidden_states): + seq_len = min_length + idx if not use_cache else 1 + seq_len = config.lsh_attn_chunk_length * ( + seq_len // config.lsh_attn_chunk_length + (seq_len % config.lsh_attn_chunk_length != 0) + ) + + if use_cache: + seq_len = 1 + + expected_shape = (batch_size * num_beam_groups, seq_len, config.hidden_size) + # check hidden size + self.assertListEqual( + [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states], + [expected_shape] * len(iter_hidden_states), + ) + + @unittest.skip("Fails because the sequence length is not a multiple of 4") + def test_problem_types(self): + pass + + @unittest.skip("Fails because the sequence length is not a multiple of 4") + def test_past_key_values_format(self): + pass + + @unittest.skip("The model doesn't support left padding") # and it's not used enough to be worth fixing :) + def test_left_padding_compatibility(self): + pass + + +@require_torch +@require_sentencepiece +@require_tokenizers +class ReformerIntegrationTests(unittest.TestCase): + """ + These integration tests test the current layer activations and gradients againts the output of the Hugging Face Reformer model at time of integration: 29/06/2020. During integration, the model was tested against the output of the official Trax ReformerLM model for various cases ("lsh" only, "lsh" only, masked / non-masked, different chunk length, ....). In order to recover the original trax integration tests, one should use patrickvonplaten's fork of trax and the code that lives on the branch `reformer_trax_tests`. + """ + + def _get_basic_config_and_input(self): + config = { + "vocab_size": 320, + "attention_head_size": 8, + "hidden_size": 16, + "num_attention_heads": 2, + "num_buckets": 2, + "num_hashes": 4, + "lsh_attn_chunk_length": 4, + "local_attn_chunk_length": 4, + "lsh_num_chunks_before": 1, + "lsh_num_chunks_after": 0, + "local_num_chunks_before": 1, + "local_num_chunks_after": 0, + "chunk_size_lm_head": 0, + "chunk_size_feed_forward": 0, + "feed_forward_size": 32, + "hidden_act": "gelu", + "hidden_dropout_prob": 0.0, + "lsh_attention_probs_dropout_prob": 0.0, + "local_attention_probs_dropout_prob": 0.0, + "max_position_embeddings": 32, + "initializer_range": 0.02, + "axial_norm_std": 1.0, + "layer_norm_eps": 1e-12, + "sinusoidal_pos_embds": False, + "axial_pos_embds": True, + "axial_pos_shape": [4, 8], + "axial_pos_embds_dim": [8, 8], + "hash_seed": 0, + "is_decoder": True, + } + return config + + def _get_hidden_states(self): + return torch.tensor( + [ + [ + [ + 1.90826353e00, + -1.45999730e00, + -6.20405462e-01, + 1.52503433e00, + -3.64464232e-01, + -8.27359235e-01, + 8.39670803e-01, + 2.44492178e-01, + 4.98332758e-01, + 2.69175139e00, + -7.08081422e-03, + 1.04915401e00, + -1.83476661e00, + 7.67220476e-01, + 2.98580543e-01, + 2.84803992e-02, + ], + [ + -2.66374286e-02, + 4.33497576e-01, + 3.10386309e-01, + 5.46039944e-01, + -2.47292666e-04, + -7.52305019e-01, + 2.39162103e-01, + 7.25216186e-01, + -7.58357372e-01, + 4.20635998e-01, + -4.04739919e-02, + 1.59924145e-01, + 2.05135748e00, + -1.15997978e00, + 5.37166397e-01, + 2.62873606e-01, + ], + [ + 1.85247482e-01, + 7.07046037e-01, + -6.77089715e-01, + -2.24209655e00, + -3.75307980e-02, + -8.59380874e-01, + -2.81027884e00, + 1.01276376e00, + -1.69438001e00, + 4.17574660e-01, + -1.49196962e00, + -1.76483717e00, + -1.94566312e-01, + -1.71183858e00, + 7.72903565e-01, + -1.11557056e00, + ], + [ + 9.46069193e-01, + 1.53417623e-01, + -9.58686996e-01, + 1.18126669e-01, + 1.75967724e00, + 1.62194590e00, + -5.74108159e-01, + 6.79920443e-01, + 5.44028163e-01, + 2.05466114e-01, + -3.63045868e-01, + 2.41865062e-01, + 3.20348382e-01, + -9.05611176e-01, + -1.92690727e-01, + -1.19917547e00, + ], + ] + ], + dtype=torch.float32, + device=torch_device, + ) + + def _get_attn_mask(self): + return torch.tensor([[0, 1, 0, 0]], dtype=torch.long, device=torch_device) + + def _get_input_ids_and_mask(self): + mask = torch.tensor( + [ + [1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0], + ], + dtype=torch.long, + device=torch_device, + ) + + input_ids = torch.tensor( + [ + [ + 89, + 279, + 286, + 84, + 194, + 316, + 182, + 28, + 283, + 37, + 169, + 7, + 253, + 267, + 107, + 250, + 44, + 7, + 102, + 62, + 3, + 243, + 171, + 265, + 302, + 48, + 164, + 264, + 148, + 229, + 280, + 150, + ], + [ + 9, + 192, + 66, + 112, + 163, + 83, + 135, + 70, + 224, + 96, + 31, + 80, + 196, + 80, + 63, + 22, + 85, + 100, + 47, + 283, + 0, + 163, + 126, + 143, + 195, + 82, + 53, + 82, + 18, + 27, + 182, + 52, + ], + ], + dtype=torch.long, + device=torch_device, + ) + + return input_ids, mask + + def test_lsh_layer_forward(self): + config = self._get_basic_config_and_input() + config["lsh_num_chunks_before"] = 0 + config["attn_layers"] = ["lsh"] + config["is_decoder"] = False + hidden_states = self._get_hidden_states() + torch.manual_seed(0) + layer = ReformerLayer(ReformerConfig(**config)).to(torch_device) + layer.eval() + reformer_output = layer(prev_attn_output=hidden_states.clone(), hidden_states=hidden_states) + output_slice = reformer_output.hidden_states[0, 0, :5] + expected_output_slice = torch.tensor( + [1.6879, -1.3083, -0.4708, 1.3555, -0.6292], + dtype=torch.float, + device=torch_device, + ) + self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3)) + + def test_lsh_layer_forward_complex(self): + config = self._get_basic_config_and_input() + config["lsh_num_chunks_before"] = 0 + config["attn_layers"] = ["lsh"] + config["num_buckets"] = [2, 4] + attn_mask = self._get_attn_mask() + hidden_states = self._get_hidden_states() + torch.manual_seed(0) + layer = ReformerLayer(ReformerConfig(**config)).to(torch_device) + layer.eval() + reformer_output = layer( + prev_attn_output=hidden_states.clone(), + hidden_states=hidden_states, + attention_mask=attn_mask, + ) + output_slice = reformer_output.hidden_states[0, 0, :5] + expected_output_slice = torch.tensor( + [1.6439, -1.2306, -0.5108, 1.3006, -0.6537], + dtype=torch.float, + device=torch_device, + ) + self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3)) + + def test_local_layer_forward(self): + config = self._get_basic_config_and_input() + config["local_num_chunks_before"] = 0 + config["attn_layers"] = ["local"] + config["is_decoder"] = False + hidden_states = self._get_hidden_states() + torch.manual_seed(0) + layer = ReformerLayer(ReformerConfig(**config)).to(torch_device) + layer.eval() + reformer_output = layer(prev_attn_output=hidden_states, hidden_states=hidden_states) + output_slice = reformer_output.hidden_states[0, 0, :5] + expected_output_slice = torch.tensor( + [1.4212, -2.0576, -0.9688, 1.4599, -0.1344], + dtype=torch.float, + device=torch_device, + ) + self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3)) + + def test_local_layer_forward_complex(self): + config = self._get_basic_config_and_input() + config["local_num_chunks_before"] = 0 + config["attn_layers"] = ["local"] + attn_mask = self._get_attn_mask() + hidden_states = self._get_hidden_states() + torch.manual_seed(0) + layer = ReformerLayer(ReformerConfig(**config)).to(torch_device) + layer.eval() + reformer_output = layer( + prev_attn_output=hidden_states, + hidden_states=hidden_states, + attention_mask=attn_mask, + ) + output_slice = reformer_output.hidden_states[0, 0, :5] + expected_output_slice = torch.tensor( + [1.4750, -2.0235, -0.9743, 1.4463, -0.1269], + dtype=torch.float, + device=torch_device, + ) + self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3)) + + def test_lsh_model_forward(self): + config = self._get_basic_config_and_input() + config["attn_layers"] = ["lsh", "lsh", "lsh", "lsh"] + config["num_buckets"] = [2, 4] + torch.manual_seed(0) + model = ReformerModel(ReformerConfig(**config)).to(torch_device) + model.eval() + input_ids, attn_mask = self._get_input_ids_and_mask() + hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0] + output_slice = hidden_states[0, 0, :5] + expected_output_slice = torch.tensor( + [-0.9896, -0.9396, -1.0831, -0.0597, 0.2456], + dtype=torch.float, + device=torch_device, + ) + self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3)) + + def test_local_model_forward(self): + config = self._get_basic_config_and_input() + config["attn_layers"] = ["local", "local", "local", "local"] + torch.manual_seed(0) + model = ReformerModel(ReformerConfig(**config)).to(torch_device) + model.eval() + input_ids, attn_mask = self._get_input_ids_and_mask() + hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0] + output_slice = hidden_states[0, 0, :5] + expected_output_slice = torch.tensor( + [-1.6791, 0.7171, 0.1594, 0.4063, 1.2584], + dtype=torch.float, + device=torch_device, + ) + self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3)) + + def test_lm_model_forward(self): + config = self._get_basic_config_and_input() + config["attn_layers"] = ["local", "lsh", "local", "lsh", "local", "lsh"] + config["num_buckets"] = [2, 4] + config["is_decoder"] = False + torch.manual_seed(0) + model = ReformerForMaskedLM(ReformerConfig(**config)).to(torch_device) + model.eval() + input_ids, attn_mask = self._get_input_ids_and_mask() + hidden_states = model(input_ids=input_ids, attention_mask=attn_mask)[0] + output_slice = hidden_states[1, -1, :5] + expected_output_slice = torch.tensor( + [0.1018, -0.2026, 0.2116, 0.0270, -0.1233], + dtype=torch.float, + device=torch_device, + ) + + self.assertTrue(torch.allclose(output_slice, expected_output_slice, atol=1e-3)) + + def test_local_lm_model_grad(self): + config = self._get_basic_config_and_input() + config["attn_layers"] = ["local", "local", "local", "local"] + config["hidden_dropout_prob"] = 0.0 + config["local_attention_probs_dropout_prob"] = 0.0 + torch.manual_seed(0) + model = ReformerModelWithLMHead(ReformerConfig(**config)).to(torch_device) + model.train() + model.zero_grad() + input_ids, _ = self._get_input_ids_and_mask() + loss = model(input_ids=input_ids, labels=input_ids)[0] + + self.assertTrue(torch.allclose(loss, torch.tensor(5.8019, dtype=torch.float, device=torch_device), atol=1e-3)) + loss.backward() + + # check last grads to cover all proable errors + grad_slice_word = model.reformer.embeddings.word_embeddings.weight.grad[0, :5] + expected_grad_slice_word = torch.tensor( + [-0.0005, -0.0001, -0.0002, -0.0006, -0.0006], + dtype=torch.float, + device=torch_device, + ) + grad_slice_position_factor_1 = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:] + expected_grad_slice_pos_fac_1 = torch.tensor( + [-0.5235, 0.5704, 0.0922, -0.3140, 0.9928], + dtype=torch.float, + device=torch_device, + ) + grad_slice_position_factor_2 = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5] + expected_grad_slice_pos_fac_2 = torch.tensor( + [1.7960, 1.7668, 0.5593, 0.0907, 1.8342], + dtype=torch.float, + device=torch_device, + ) + self.assertTrue(torch.allclose(grad_slice_word, expected_grad_slice_word, atol=1e-3)) + self.assertTrue(torch.allclose(grad_slice_position_factor_1, expected_grad_slice_pos_fac_1, atol=1e-3)) + self.assertTrue(torch.allclose(grad_slice_position_factor_2, expected_grad_slice_pos_fac_2, atol=1e-3)) + + def test_lsh_lm_model_grad(self): + config = self._get_basic_config_and_input() + config["attn_layers"] = ["lsh", "lsh", "lsh", "lsh"] + config["hidden_dropout_prob"] = 0.0 + config["lsh_attention_probs_dropout_prob"] = 0.0 + config["num_buckets"] = [2, 4] + config["num_hashes"] = 6 + torch.manual_seed(0) + model = ReformerModelWithLMHead(ReformerConfig(**config)).to(torch_device) + model.train() + model.zero_grad() + input_ids, _ = self._get_input_ids_and_mask() + loss = model(input_ids=input_ids, labels=input_ids)[0] + + self.assertTrue(torch.allclose(loss, torch.tensor(5.7854, dtype=torch.float, device=torch_device), atol=1e-3)) + loss.backward() + # check last grads to cover all proable errors + grad_slice_word = model.reformer.embeddings.word_embeddings.weight.grad[0, :5] + expected_grad_slice_word = torch.tensor( + [0.0004, 0.0003, 0.0006, -0.0004, 0.0002], + dtype=torch.float, + device=torch_device, + ) + grad_slice_position_factor_1 = model.reformer.embeddings.position_embeddings.weights[0][1, 0, -5:] + expected_grad_slice_pos_fac_1 = torch.tensor( + [-0.3792, 0.5593, -1.6993, 0.2033, 0.4131], + dtype=torch.float, + device=torch_device, + ) + grad_slice_position_factor_2 = model.reformer.embeddings.position_embeddings.weights[1][0, 1, :5] + expected_grad_slice_pos_fac_2 = torch.tensor( + [-1.4212, -0.3201, -1.1944, 0.1258, 0.2856], + dtype=torch.float, + device=torch_device, + ) + self.assertTrue(torch.allclose(grad_slice_word, expected_grad_slice_word, atol=1e-3)) + self.assertTrue(torch.allclose(grad_slice_position_factor_1, expected_grad_slice_pos_fac_1, atol=1e-3)) + self.assertTrue(torch.allclose(grad_slice_position_factor_2, expected_grad_slice_pos_fac_2, atol=1e-3)) + + @slow + def test_pretrained_generate_crime_and_punish(self): + model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment").to(torch_device) + tokenizer = ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment") + model.eval() + + input_ids = tokenizer.encode("A few months later", return_tensors="pt").to(torch_device) + output_ids = model.generate( + input_ids, max_length=50, num_beams=4, early_stopping=True, do_sample=False, num_hashes=8 + ) + output = tokenizer.decode(output_ids[0]) + + self.assertEqual( + output, + "A few months later state expression in his ideas, at the first entrance. He was positively for an inst", + ) + + @slow + def test_pretrained_generate_use_cache_equality(self): + model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment").to(torch_device) + tokenizer = ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment") + model.eval() + input_ids = tokenizer.encode("A few months later", return_tensors="pt").to(torch_device) + output_ids_with_cache = model.generate(input_ids, max_length=130, num_hashes=8, use_cache=False) + output_ids_without_cache = model.generate(input_ids, max_length=130, num_hashes=8, use_cache=True) + + output_with_cache = tokenizer.decode(output_ids_with_cache[0]) + output_without_cache = tokenizer.decode(output_ids_without_cache[0]) + + self.assertEqual(output_with_cache, output_without_cache) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_tokenization_reformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_tokenization_reformer.py new file mode 100644 index 0000000000000000000000000000000000000000..0f72bf311a22986724b7bfd89d954ac73fc5096d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/reformer/test_tokenization_reformer.py @@ -0,0 +1,370 @@ +# 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 unittest + +from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow +from transformers.utils import cached_property + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + + +@require_sentencepiece +@require_tokenizers +class ReformerTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = ReformerTokenizer + rust_tokenizer_class = ReformerTokenizerFast + test_rust_tokenizer = True + test_seq2seq = False + test_sentencepiece = True + + def setUp(self): + super().setUp() + + tokenizer = ReformerTokenizer(SAMPLE_VOCAB, keep_accents=True) + tokenizer.save_pretrained(self.tmpdirname) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "" + token_id = 1 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + self.assertEqual(vocab_keys[-1], "j") + self.assertEqual(len(vocab_keys), 1_000) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 1_000) + + def test_rust_and_python_full_tokenizers(self): + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + sequence = "I was born in 92000, and this is falsé." + + tokens = tokenizer.tokenize(sequence) + rust_tokens = rust_tokenizer.tokenize(sequence) + self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + rust_tokenizer = self.get_rust_tokenizer() + ids = tokenizer.encode(sequence) + rust_ids = rust_tokenizer.encode(sequence) + self.assertListEqual(ids, rust_ids) + + def test_padding(self, max_length=15): + 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) + + # Simple input + s = "This is a simple input" + s2 = ["This is a simple input 1", "This is a simple input 2"] + p = ("This is a simple input", "This is a pair") + p2 = [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ] + + # Simple input tests + self.assertRaises(ValueError, tokenizer_r.encode, s, max_length=max_length, padding="max_length") + + # Simple input + self.assertRaises(ValueError, tokenizer_r.encode_plus, s, max_length=max_length, padding="max_length") + + # Simple input + self.assertRaises( + ValueError, + tokenizer_r.batch_encode_plus, + s2, + max_length=max_length, + padding="max_length", + ) + + # Pair input + self.assertRaises(ValueError, tokenizer_r.encode, p, max_length=max_length, padding="max_length") + + # Pair input + self.assertRaises(ValueError, tokenizer_r.encode_plus, p, max_length=max_length, padding="max_length") + + # Pair input + self.assertRaises( + ValueError, + tokenizer_r.batch_encode_plus, + p2, + max_length=max_length, + padding="max_length", + ) + + # tokenizer has no padding token + def test_padding_different_model_input_name(self): + pass + + def test_full_tokenizer(self): + tokenizer = ReformerTokenizer(SAMPLE_VOCAB, keep_accents=True) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [285, 46, 10, 170, 382], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "é", + ".", + ], + ) + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual( + ids, + [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4], + ) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual( + back_tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "", + ".", + ], + ) + + @cached_property + def big_tokenizer(self): + return ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment") + + @slow + def test_tokenization_base_easy_symbols(self): + symbols = "Hello World!" + original_tokenizer_encodings = [126, 32, 262, 152, 38, 72, 287] + + self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) + + @slow + def test_tokenization_base_hard_symbols(self): + symbols = ( + 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' + " add words that should not exsist and be tokenized to , such as saoneuhaoesuth" + ) + original_tokenizer_encodings = [ + 108, + 265, + 24, + 111, + 4, + 258, + 156, + 35, + 28, + 275, + 3, + 259, + 297, + 260, + 84, + 4, + 35, + 110, + 44, + 8, + 259, + 91, + 268, + 21, + 11, + 209, + 274, + 109, + 266, + 277, + 117, + 86, + 93, + 315, + 258, + 278, + 258, + 277, + 258, + 0, + 258, + 288, + 258, + 319, + 258, + 0, + 258, + 0, + 258, + 0, + 258, + 0, + 258, + 287, + 258, + 315, + 258, + 289, + 258, + 278, + 99, + 269, + 266, + 262, + 8, + 259, + 241, + 4, + 217, + 230, + 268, + 266, + 55, + 168, + 106, + 75, + 193, + 266, + 223, + 27, + 49, + 26, + 282, + 25, + 264, + 299, + 19, + 26, + 0, + 258, + 277, + 117, + 86, + 93, + 176, + 183, + 270, + 11, + 262, + 42, + 61, + 265, + ] + + self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) + + @require_torch + @slow + def test_torch_encode_plus_sent_to_model(self): + import torch + + from transformers import ReformerConfig, ReformerModel + + # Build sequence + first_ten_tokens = list(self.big_tokenizer.get_vocab().keys())[:10] + sequence = " ".join(first_ten_tokens) + encoded_sequence = self.big_tokenizer.encode_plus(sequence, return_tensors="pt") + batch_encoded_sequence = self.big_tokenizer.batch_encode_plus([sequence, sequence], return_tensors="pt") + + config = ReformerConfig() + # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) + config.axial_pos_shape = encoded_sequence["input_ids"].shape + model = ReformerModel(config) + + # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) + assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size + + with torch.no_grad(): + model(**encoded_sequence) + model(**batch_encoded_sequence) + + @slow + def test_tokenizer_integration(self): + expected_encoding = {'input_ids': [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # fmt: skip + + # This tokenizer does not know some characters like ")". + # That is the reason why we use very simple texts here. + # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 + sequences = [ + "This is a very simple sentence.", + "The quick brown fox jumps over the lazy dog.", + ] + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, + model_name="google/reformer-crime-and-punishment", + revision="0e6c3decb8211d49bf881013425dc8b0448b3f5a", + padding=False, + sequences=sequences, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_flax_regnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_flax_regnet.py new file mode 100644 index 0000000000000000000000000000000000000000..911d595c56e6a0b80021f27b0a36c89a9ad9416d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_flax_regnet.py @@ -0,0 +1,237 @@ +# coding=utf-8 +# Copyright 2023 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 + +from transformers import RegNetConfig, is_flax_available +from transformers.testing_utils import require_flax, slow +from transformers.utils import cached_property, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor + + +if is_flax_available(): + import jax + import jax.numpy as jnp + + from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class FlaxRegNetModelTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=3, + image_size=32, + num_channels=3, + embeddings_size=10, + hidden_sizes=[10, 20, 30, 40], + depths=[1, 1, 2, 1], + is_training=True, + use_labels=True, + hidden_act="relu", + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.embeddings_size = embeddings_size + self.hidden_sizes = hidden_sizes + self.depths = depths + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.num_labels = num_labels + self.scope = scope + self.num_stages = len(hidden_sizes) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + config = self.get_config() + + return config, pixel_values + + def get_config(self): + return RegNetConfig( + num_channels=self.num_channels, + embeddings_size=self.embeddings_size, + hidden_sizes=self.hidden_sizes, + depths=self.depths, + hidden_act=self.hidden_act, + num_labels=self.num_labels, + image_size=self.image_size, + ) + + def create_and_check_model(self, config, pixel_values): + model = FlaxRegNetModel(config=config) + result = model(pixel_values) + + # Output shape (b, c, h, w) + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), + ) + + def create_and_check_for_image_classification(self, config, pixel_values): + config.num_labels = self.num_labels + model = FlaxRegNetForImageClassification(config=config) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_flax +class FlaxResNetModelTest(FlaxModelTesterMixin, unittest.TestCase): + all_model_classes = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () + + is_encoder_decoder = False + test_head_masking = False + has_attentions = False + + def setUp(self) -> None: + self.model_tester = FlaxRegNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=RegNetConfig, has_text_modality=False) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @unittest.skip(reason="RegNet does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="RegNet does not support input and output embeddings") + def test_model_common_attributes(self): + pass + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.__call__) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_stages = self.model_tester.num_stages + self.assertEqual(len(hidden_states), expected_num_stages + 1) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_jit_compilation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def model_jitted(pixel_values, **kwargs): + return model(pixel_values=pixel_values, **kwargs) + + with self.subTest("JIT Enabled"): + jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_flax +class FlaxRegNetModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return AutoImageProcessor.from_pretrained("facebook/regnet-y-040") if is_vision_available() else None + + @slow + def test_inference_image_classification_head(self): + model = FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040") + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="np") + + outputs = model(**inputs) + + # verify the logits + expected_shape = (1, 1000) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = jnp.array([-0.4180, -1.5051, -3.4836]) + + self.assertTrue(jnp.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_regnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_regnet.py new file mode 100644 index 0000000000000000000000000000000000000000..9840575f317ecd6982bb19f50afa9d9fe7012636 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_regnet.py @@ -0,0 +1,263 @@ +# coding=utf-8 +# Copyright 2022 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 RegNet model. """ + + +import unittest + +from transformers import RegNetConfig +from transformers.file_utils import cached_property, is_torch_available, is_vision_available +from transformers.testing_utils import require_torch, require_vision, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import RegNetForImageClassification, RegNetModel + from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class RegNetModelTester: + def __init__( + self, + parent, + batch_size=3, + image_size=32, + num_channels=3, + embeddings_size=10, + hidden_sizes=[10, 20, 30, 40], + depths=[1, 1, 2, 1], + is_training=True, + use_labels=True, + hidden_act="relu", + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.embeddings_size = embeddings_size + self.hidden_sizes = hidden_sizes + self.depths = depths + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.num_labels = num_labels + self.scope = scope + self.num_stages = len(hidden_sizes) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.num_labels) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return RegNetConfig( + num_channels=self.num_channels, + embeddings_size=self.embeddings_size, + hidden_sizes=self.hidden_sizes, + depths=self.depths, + hidden_act=self.hidden_act, + num_labels=self.num_labels, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = RegNetModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + # expected last hidden states: B, C, H // 32, W // 32 + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), + ) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.num_labels + model = RegNetForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class RegNetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as RegNet does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification} + if is_torch_available() + else {} + ) + + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + has_attentions = False + + def setUp(self): + self.model_tester = RegNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=RegNetConfig, has_text_modality=False) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + @unittest.skip(reason="RegNet does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="RegNet does not support input and output embeddings") + def test_model_common_attributes(self): + pass + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config=config) + for name, module in model.named_modules(): + if isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)): + self.assertTrue( + torch.all(module.weight == 1), + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + self.assertTrue( + torch.all(module.bias == 0), + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_stages = self.model_tester.num_stages + self.assertEqual(len(hidden_states), expected_num_stages + 1) + + # RegNet's feature maps are of shape (batch_size, num_channels, height, width) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.image_size // 2, self.model_tester.image_size // 2], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + layers_type = ["basic", "bottleneck"] + for model_class in self.all_model_classes: + for layer_type in layers_type: + config.layer_type = layer_type + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = RegNetModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class RegNetModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ( + AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) + if is_vision_available() + else None + ) + + @slow + def test_inference_image_classification_head(self): + model = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-0.4180, -1.5051, -3.4836]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_tf_regnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_tf_regnet.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f2bf92ef46c485fd2b911f198b5ce3709efbc1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/regnet/test_modeling_tf_regnet.py @@ -0,0 +1,294 @@ +# coding=utf-8 +# Copyright 2022 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 TensorFlow RegNet model. """ + +from __future__ import annotations + +import inspect +import unittest +from typing import List, Tuple + +from transformers import RegNetConfig +from transformers.testing_utils import require_tf, require_vision, slow +from transformers.utils import cached_property, is_tf_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class TFRegNetModelTester: + def __init__( + self, + parent, + batch_size=3, + image_size=32, + num_channels=3, + embeddings_size=10, + hidden_sizes=[10, 20, 30, 40], + depths=[1, 1, 2, 1], + is_training=True, + use_labels=True, + hidden_act="relu", + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.embeddings_size = embeddings_size + self.hidden_sizes = hidden_sizes + self.depths = depths + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.num_labels = num_labels + self.scope = scope + self.num_stages = len(hidden_sizes) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.num_labels) + + config = self.get_config() + return config, pixel_values, labels + + def get_config(self): + return RegNetConfig( + num_channels=self.num_channels, + embeddings_size=self.embeddings_size, + hidden_sizes=self.hidden_sizes, + depths=self.depths, + hidden_act=self.hidden_act, + num_labels=self.num_labels, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = TFRegNetModel(config=config) + result = model(pixel_values, training=False) + # expected last hidden states: B, C, H // 32, W // 32 + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), + ) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.num_labels + model = TFRegNetForImageClassification(config) + result = model(pixel_values, labels=labels, training=False) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_tf +class TFRegNetModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as RegNet does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () + pipeline_model_mapping = ( + {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification} + if is_tf_available() + else {} + ) + + test_pruning = False + test_onnx = False + test_resize_embeddings = False + test_head_masking = False + has_attentions = False + + def setUp(self): + self.model_tester = TFRegNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=RegNetConfig, has_text_modality=False) + + def create_and_test_config_common_properties(self): + return + + @unittest.skip(reason="RegNet does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skipIf( + not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, + reason="TF does not support backprop for grouped convolutions on CPU.", + ) + @slow + def test_keras_fit(self): + super().test_keras_fit() + + @unittest.skip(reason="RegNet does not support input and output embeddings") + def test_model_common_attributes(self): + pass + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class), training=False) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_stages = self.model_tester.num_stages + self.assertEqual(len(hidden_states), expected_num_stages + 1) + + # RegNet's feature maps are of shape (batch_size, num_channels, height, width) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.image_size // 2, self.model_tester.image_size // 2], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + layers_type = ["basic", "bottleneck"] + for model_class in self.all_model_classes: + for layer_type in layers_type: + config.layer_type = layer_type + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + # Since RegNet does not have any attention we need to rewrite this test. + def test_model_outputs_equivalence(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): + tuple_output = model(tuple_inputs, return_dict=False, **additional_kwargs) + dict_output = model(dict_inputs, return_dict=True, **additional_kwargs).to_tuple() + + def recursive_check(tuple_object, dict_object): + if isinstance(tuple_object, (List, Tuple)): + for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif tuple_object is None: + return + else: + self.assertTrue( + all(tf.equal(tuple_object, dict_object)), + msg=( + "Tuple and dict output are not equal. Difference:" + f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}" + ), + ) + + recursive_check(tuple_output, dict_output) + + for model_class in self.all_model_classes: + model = model_class(config) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFRegNetModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_tf +@require_vision +class RegNetModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ( + AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) + if is_vision_available() + else None + ) + + @slow + def test_inference_image_classification_head(self): + model = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="tf") + + # forward pass + outputs = model(**inputs, training=False) + + # verify the logits + expected_shape = tf.TensorShape((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = tf.constant([-0.4180, -1.5051, -3.4836]) + + tf.debugging.assert_near(outputs.logits[0, :3], expected_slice, atol=1e-4) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_rembert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_rembert.py new file mode 100644 index 0000000000000000000000000000000000000000..557a42243df86129f03b1d6eb2dead0a04446bf0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_rembert.py @@ -0,0 +1,512 @@ +# coding=utf-8 +# 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 RemBERT model. """ + + +import unittest + +from transformers import is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + RemBertConfig, + RemBertForCausalLM, + RemBertForMaskedLM, + RemBertForMultipleChoice, + RemBertForQuestionAnswering, + RemBertForSequenceClassification, + RemBertForTokenClassification, + RemBertModel, + ) + from transformers.models.rembert.modeling_rembert import REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST + + +class RemBertModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + input_embedding_size=18, + output_embedding_size=43, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + self.use_labels = use_labels + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.input_embedding_size = input_embedding_size + self.output_embedding_size = output_embedding_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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = RemBertConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + input_embedding_size=self.input_embedding_size, + output_embedding_size=self.output_embedding_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RemBertModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = RemBertModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = RemBertForCausalLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RemBertForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = RemBertForCausalLM(config=config) + model.to(torch_device) + model.eval() + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # 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)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RemBertForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_for_sequence_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = RemBertForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = RemBertForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = RemBertForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class RemBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + RemBertModel, + RemBertForMaskedLM, + RemBertForCausalLM, + RemBertForMultipleChoice, + RemBertForQuestionAnswering, + RemBertForSequenceClassification, + RemBertForTokenClassification, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (RemBertForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": RemBertModel, + "fill-mask": RemBertForMaskedLM, + "question-answering": RemBertForQuestionAnswering, + "text-classification": RemBertForSequenceClassification, + "text-generation": RemBertForCausalLM, + "token-classification": RemBertForTokenClassification, + "zero-shot": RemBertForSequenceClassification, + } + if is_torch_available() + else {} + ) + + def setUp(self): + self.model_tester = RemBertModelTester(self) + self.config_tester = ConfigTester(self, config_class=RemBertConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_model_as_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_model_as_decoder_with_default_input_mask(self): + # This regression test was failing with PyTorch < 1.3 + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = self.model_tester.prepare_config_and_inputs_for_decoder() + + input_mask = None + + self.model_tester.create_and_check_model_as_decoder( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + @slow + def test_model_from_pretrained(self): + for model_name in REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = RemBertModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_torch +class RemBertModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_model(self): + # Test exact values at the last hidden layer + model = RemBertModel.from_pretrained("google/rembert") + input_ids = torch.tensor([[312, 56498, 313, 2125, 313]]) + segment_ids = torch.tensor([[0, 0, 0, 1, 1]]) + with torch.no_grad(): + output = model(input_ids, token_type_ids=segment_ids, output_hidden_states=True) + + hidden_size = 1152 + + expected_shape = torch.Size((1, 5, hidden_size)) + self.assertEqual(output["last_hidden_state"].shape, expected_shape) + + expected_implementation = torch.tensor( + [ + [ + [0.0754, -0.2022, 0.1904], + [-0.3354, -0.3692, -0.4791], + [-0.2314, -0.6729, -0.0749], + [-0.0396, -0.3105, -0.4234], + [-0.1571, -0.0525, 0.5353], + ] + ] + ) + + # Running on the original tf implementation gives slightly different results here. + # Not clear why this variations is present + # TODO: Find reason for discrepancy + # expected_original_implementation = [[ + # [0.07630594074726105, -0.20146065950393677, 0.19107051193714142], + # [-0.3405614495277405, -0.36971670389175415, -0.4808273911476135], + # [-0.22587086260318756, -0.6656315922737122, -0.07844287157058716], + # [-0.04145475849509239, -0.3077218234539032, -0.42316967248916626], + # [-0.15887849032878876, -0.054529931396245956, 0.5356100797653198] + # ]] + + self.assertTrue(torch.allclose(output["last_hidden_state"][:, :, :3], expected_implementation, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_tf_rembert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_tf_rembert.py new file mode 100644 index 0000000000000000000000000000000000000000..8698d3febc841fc7ac4e781484ec4c1ef13f21a2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_modeling_tf_rembert.py @@ -0,0 +1,728 @@ +# coding=utf-8 +# 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. + + +from __future__ import annotations + +import unittest + +from transformers import RemBertConfig, is_tf_available +from transformers.testing_utils import require_tf, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import ( + TFRemBertForCausalLM, + TFRemBertForMaskedLM, + TFRemBertForMultipleChoice, + TFRemBertForQuestionAnswering, + TFRemBertForSequenceClassification, + TFRemBertForTokenClassification, + TFRemBertModel, + ) + + +class TFRemBertModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + input_embedding_size=18, + output_embedding_size=43, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = 13 + self.seq_length = 7 + self.is_training = True + self.use_input_mask = True + self.use_token_type_ids = True + self.use_labels = True + self.vocab_size = 99 + self.hidden_size = 32 + self.input_embedding_size = input_embedding_size + self.output_embedding_size = output_embedding_size + self.num_hidden_layers = 2 + self.num_attention_heads = 4 + self.intermediate_size = 37 + self.hidden_act = "gelu" + self.hidden_dropout_prob = 0.1 + self.attention_probs_dropout_prob = 0.1 + self.max_position_embeddings = 512 + self.type_vocab_size = 16 + self.type_sequence_label_size = 2 + self.initializer_range = 0.02 + self.num_labels = 3 + self.num_choices = 4 + self.scope = None + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = RemBertConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + input_embedding_size=self.input_embedding_size, + output_embedding_size=self.output_embedding_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + return_dict=True, + ) + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRemBertModel(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + + inputs = [input_ids, input_mask] + result = model(inputs) + + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_causal_lm_base_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.is_decoder = True + + model = TFRemBertModel(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs) + + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRemBertModel(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "encoder_hidden_states": encoder_hidden_states, + "encoder_attention_mask": encoder_attention_mask, + } + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states) + + # Also check the case where encoder outputs are not passed + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_causal_lm_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.is_decoder = True + model = TFRemBertForCausalLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + prediction_scores = model(inputs)["logits"] + self.parent.assertListEqual( + list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size] + ) + + def create_and_check_causal_lm_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRemBertForCausalLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "encoder_hidden_states": encoder_hidden_states, + "encoder_attention_mask": encoder_attention_mask, + } + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states) + + prediction_scores = result["logits"] + self.parent.assertListEqual( + list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size] + ) + + def create_and_check_causal_lm_model_past( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRemBertForCausalLM(config=config) + + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + past_key_values = outputs.past_key_values + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and attn_mask + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + + output_from_no_past = model(next_input_ids, output_hidden_states=True).hidden_states[0] + output_from_past = model( + next_tokens, past_key_values=past_key_values, output_hidden_states=True + ).hidden_states[0] + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx] + output_from_past_slice = output_from_past[:, 0, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6) + + def create_and_check_causal_lm_model_past_with_attn_mask( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRemBertForCausalLM(config=config) + + # create attention mask + half_seq_length = self.seq_length // 2 + attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32) + attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32) + attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1) + + # first forward pass + outputs = model(input_ids, attention_mask=attn_mask, use_cache=True) + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + past_key_values = outputs.past_key_values + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size) + vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change) + condition = tf.transpose( + tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size)) + ) + input_ids = tf.where(condition, random_other_next_tokens, input_ids) + + # append to next input_ids and + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + attn_mask = tf.concat( + [attn_mask, tf.ones((attn_mask.shape[0], 1), dtype=tf.int32)], + axis=1, + ) + + output_from_no_past = model( + next_input_ids, + attention_mask=attn_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, past_key_values=past_key_values, attention_mask=attn_mask, output_hidden_states=True + ).hidden_states[0] + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx] + output_from_past_slice = output_from_past[:, 0, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6) + + def create_and_check_causal_lm_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRemBertForCausalLM(config=config) + + input_ids = input_ids[:1, :] + input_mask = input_mask[:1, :] + self.batch_size = 1 + + # first forward pass + outputs = model(input_ids, attention_mask=input_mask, use_cache=True) + past_key_values = outputs.past_key_values + + # create hypothetical 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 = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + ).hidden_states[0] + + self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1]) + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRemBertForCausalLM(config=config) + + input_ids = input_ids[:1, :] + input_mask = input_mask[:1, :] + encoder_hidden_states = encoder_hidden_states[:1, :, :] + encoder_attention_mask = encoder_attention_mask[:1, :] + self.batch_size = 1 + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical 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 = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + ).hidden_states[0] + + self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1]) + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRemBertForMaskedLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_sequence_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = TFRemBertForSequenceClassification(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = TFRemBertForMultipleChoice(config=config) + multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1)) + multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1)) + multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1)) + inputs = { + "input_ids": multiple_choice_inputs_ids, + "attention_mask": multiple_choice_input_mask, + "token_type_ids": multiple_choice_token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = TFRemBertForTokenClassification(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRemBertForQuestionAnswering(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + + result = model(inputs) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_tf +class TFRemBertModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TFRemBertModel, + TFRemBertForCausalLM, + TFRemBertForMaskedLM, + TFRemBertForQuestionAnswering, + TFRemBertForSequenceClassification, + TFRemBertForTokenClassification, + TFRemBertForMultipleChoice, + ) + if is_tf_available() + else () + ) + pipeline_model_mapping = ( + { + "feature-extraction": TFRemBertModel, + "fill-mask": TFRemBertForMaskedLM, + "question-answering": TFRemBertForQuestionAnswering, + "text-classification": TFRemBertForSequenceClassification, + "text-generation": TFRemBertForCausalLM, + "token-classification": TFRemBertForTokenClassification, + "zero-shot": TFRemBertForSequenceClassification, + } + if is_tf_available() + else {} + ) + + test_head_masking = False + test_onnx = False + + def setUp(self): + self.model_tester = TFRemBertModelTester(self) + self.config_tester = ConfigTester(self, config_class=RemBertConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + """Test the base model""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_causal_lm_base_model(self): + """Test the base model of the causal LM model + + is_deocder=True, no cross_attention, no encoder outputs + """ + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_base_model(*config_and_inputs) + + def test_model_as_decoder(self): + """Test the base model as a decoder (of an encoder-decoder architecture) + + is_deocder=True + cross_attention + pass encoder outputs + """ + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_causal_lm(self): + """Test the causal LM model""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model(*config_and_inputs) + + def test_causal_lm_model_as_decoder(self): + """Test the causal LM model as a decoder""" + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_causal_lm_model_as_decoder(*config_and_inputs) + + def test_causal_lm_model_past(self): + """Test causal LM model with `past_key_values`""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past(*config_and_inputs) + + def test_causal_lm_model_past_with_attn_mask(self): + """Test the causal LM model with `past_key_values` and `attention_mask`""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past_with_attn_mask(*config_and_inputs) + + def test_causal_lm_model_past_with_large_inputs(self): + """Test the causal LM model with `past_key_values` and a longer decoder sequence length""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past_large_inputs(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + """Similar to `test_causal_lm_model_past_with_large_inputs` but with cross-attention""" + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + model = TFRemBertModel.from_pretrained("google/rembert") + self.assertIsNotNone(model) + + +@require_tf +class TFRemBertModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_model(self): + model = TFRemBertModel.from_pretrained("google/rembert") + + input_ids = tf.constant([[312, 56498, 313, 2125, 313]]) + segment_ids = tf.constant([[0, 0, 0, 1, 1]]) + output = model(input_ids, token_type_ids=segment_ids, output_hidden_states=True) + + hidden_size = 1152 + + expected_shape = [1, 5, hidden_size] + self.assertEqual(output["last_hidden_state"].shape, expected_shape) + + expected_implementation = tf.constant( + [ + [ + [0.0754, -0.2022, 0.1904], + [-0.3354, -0.3692, -0.4791], + [-0.2314, -0.6729, -0.0749], + [-0.0396, -0.3105, -0.4234], + [-0.1571, -0.0525, 0.5353], + ] + ] + ) + tf.debugging.assert_near(output["last_hidden_state"][:, :, :3], expected_implementation, atol=1e-4) + + # Running on the original tf implementation gives slightly different results here. + # Not clear why this variations is present + # TODO: Find reason for discrepancy + # expected_original_implementation = [[ + # [0.07630594074726105, -0.20146065950393677, 0.19107051193714142], + # [-0.3405614495277405, -0.36971670389175415, -0.4808273911476135], + # [-0.22587086260318756, -0.6656315922737122, -0.07844287157058716], + # [-0.04145475849509239, -0.3077218234539032, -0.42316967248916626], + # [-0.15887849032878876, -0.054529931396245956, 0.5356100797653198] + # ]] diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_tokenization_rembert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_tokenization_rembert.py new file mode 100644 index 0000000000000000000000000000000000000000..12c43643be7a48c5a5d9214c002e6985983f04e3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rembert/test_tokenization_rembert.py @@ -0,0 +1,243 @@ +# coding=utf-8 +# Copyright 2022 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. +""" Testing suite for the RemBert tokenizer. """ + + +import tempfile +import unittest + +from tests.test_tokenization_common import AddedToken, TokenizerTesterMixin +from transformers import RemBertTokenizer, RemBertTokenizerFast +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers + + +SENTENCEPIECE_UNDERLINE = "▁" +SPIECE_UNDERLINE = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + + +@require_sentencepiece +@require_tokenizers +class RemBertTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = RemBertTokenizer + rust_tokenizer_class = RemBertTokenizerFast + space_between_special_tokens = True + test_rust_tokenizer = True + test_sentencepiece_ignore_case = True + pre_trained_model_path = "google/rembert" + + def setUp(self): + super().setUp() + + tokenizer = RemBertTokenizer(SAMPLE_VOCAB) + tokenizer.save_pretrained(self.tmpdirname) + + # Copied from ReformerTokenizationTest.get_input_output_texts + def get_input_output_texts(self, tokenizer): + input_text = "this is a test" + output_text = "this is a test" + return input_text, output_text + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + + self.assertEqual(vocab_keys[5], "▁the") + self.assertEqual(vocab_keys[2], "") + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 1_000) + + def test_full_tokenizer(self): + tokenizer = RemBertTokenizer(SAMPLE_VOCAB, keep_accents=True) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [285, 46, 10, 170, 382], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( tokens, [SPIECE_UNDERLINE + "I",SPIECE_UNDERLINE + "was",SPIECE_UNDERLINE + "b","or","n",SPIECE_UNDERLINE + "in",SPIECE_UNDERLINE + "","9","2","0","0","0",",",SPIECE_UNDERLINE + "and",SPIECE_UNDERLINE + "this",SPIECE_UNDERLINE + "is",SPIECE_UNDERLINE + "f","al","s","é",".",],) # fmt: skip + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual(ids, [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]) + + def test_encode_decode_round_trip(self): + tokenizer = RemBertTokenizer(SAMPLE_VOCAB, keep_accents=True) + + text = "清水寺は京都にある。" + tokens = tokenizer.tokenize(text) + self.assertListEqual(tokens, ["▁", "清水寺は京都にある。"]) + encoded_string = tokenizer.encode(text) + self.assertListEqual(encoded_string, [1000, 7, 0, 1001]) + decode_text = tokenizer.convert_tokens_to_string(tokens) + self.assertEquals(decode_text, text) + + text = "That's awesome! 🤩 #HuggingFace, 🌟 Have a great day! 🌈" + tokens = tokenizer.tokenize(text) + self.assertListEqual( tokens, ['▁That', "'", 's', '▁a', 'w', 'es', 'ome', '!', '▁', '🤩', '▁', '#', 'H', 'u', 'g', 'g', 'ing', 'F', 'a', 'ce', ',', '▁', '🌟', '▁H', 'a', 've', '▁a', '▁great', '▁day', '!', '▁', '🌈']) # fmt: skip + decode_text = tokenizer.convert_tokens_to_string(tokens) + self.assertEquals(decode_text, "That's awesome! 🤩 #HuggingFace, 🌟 Have a great day! 🌈") + + text = "In the sky up above" + tokens = tokenizer._tokenize(text) + self.assertListEqual(tokens, ["▁In", "▁the", "▁s", "k", "y", "▁up", "▁a", "b", "o", "ve"]) # fmt: skip + encoded_string = tokenizer.encode(text) + self.assertListEqual(encoded_string, [1000, 388, 5, 47, 45, 30, 118, 10, 65, 20, 123, 1001]) + decode_text = tokenizer.convert_tokens_to_string(tokens) + self.assertEqual(text, decode_text) + + text = "The cat. . Sat .In a room" + tokens = tokenizer.tokenize(text) + self.assertListEqual( + tokens, ["▁The", "▁c", "at", ".", "▁", ".", "▁S", "at", "▁", "<", "s", ">", ".", "I", "n", "▁a", "▁room"] + ) + encoded_string = tokenizer.encode(text) + self.assertListEqual( + encoded_string, [1000, 68, 69, 76, 4, 7, 4, 166, 76, 7, 0, 6, 0, 4, 100, 24, 10, 136, 1001] + ) + decode_text = tokenizer.convert_tokens_to_string(tokens) + self.assertEqual(text, decode_text) + + text = "Invoice #12345, dated 2023-12-01, is due on 2024-01-15." + tokens = tokenizer.tokenize(text) + self.assertListEqual(tokens, ['▁In', 'v', 'o', 'ic', 'e', '▁', '#', '1', '2', '34', '5', ',', '▁da', 'ted', '▁', '2', '0', '2', '3', '-', '1', '2', '-', '0', '1', ',', '▁is', '▁d', 'u', 'e', '▁on', '▁', '2', '0', '2', '4', '-', '0', '1', '-', '1', '5', '.']) # fmt: skip + encoded_string = tokenizer.encode(text) + self.assertListEqual(encoded_string, [1000, 388, 83, 20, 113, 15, 7, 0, 356, 602, 0, 555, 3, 417, 273, 7, 602, 347, 602, 0, 33, 356, 602, 33, 347, 356, 3, 46, 229, 51, 15, 59, 7, 602, 347, 602, 0, 33, 347, 356, 33, 356, 555, 4, 1001]) # fmt: skip + decode_text = tokenizer.convert_tokens_to_string(tokens) + self.assertEqual(text, decode_text) + + text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." + tokens = tokenizer.tokenize(text) + self.assertListEqual(tokens, ['▁', 'L', 'or', 'em', '▁', 'i', 'p', 's', 'um', '▁do', 'l', 'or', '▁sit', '▁am', 'e', 't', ',', '▁con', 'se', 'c', 'te', 't', 'ur', '▁a', 'd', 'i', 'p', 'is', 'c', 'ing', '▁', 'el', 'it', '.', '.', '.']) # fmt: skip + encoded_string = tokenizer.encode(text) + self.assertListEqual( encoded_string, [1000, 7, 279, 55, 300, 7, 23, 29, 6, 155, 92, 27, 55, 615, 219, 15, 14, 3, 247, 114, 28, 181, 14, 108, 10, 16, 23, 29, 125, 28, 17, 7, 168, 137, 4, 4, 4, 1001] ) # fmt: skip + decode_text = tokenizer.convert_tokens_to_string(tokens) + self.assertEqual(text, decode_text) + + # for multiple language in one sentence + text = "Bonjour! Hello! こんにちは!" + tokens = tokenizer.tokenize(text) + self.assertListEqual(tokens, ["▁B", "on", "j", "o", "ur", "!", "▁He", "ll", "o", "!", "▁", "こんにちは", "!"]) + encoded_string = tokenizer.encode(text) + self.assertListEqual(encoded_string, [1000, 295, 109, 999, 20, 108, 146, 156, 86, 20, 146, 7, 0, 146, 1001]) + decode_text = tokenizer.convert_tokens_to_string(tokens) + self.assertEqual(text, decode_text) + + text = "Extra spaces\tand\nline breaks\r\nshould be handled." + tokens = tokenizer.tokenize(text) + self.assertListEqual(tokens, ['▁E', 'x', 't', 'r', 'a', '▁sp', 'a', 'ce', 's', '▁and', '▁line', '▁b', 're', 'a', 'k', 's', '▁should', '▁be', '▁hand', 'led', '.']) # fmt: skip + encoded_string = tokenizer.encode(text) + self.assertListEqual( + encoded_string, + [1000, 454, 297, 14, 35, 18, 277, 18, 133, 6, 12, 485, 84, 56, 18, 45, 6, 173, 36, 363, 338, 4, 1001], + ) + decode_text = tokenizer.convert_tokens_to_string(tokens) + self.assertEqual("Extra spaces and line breaks should be handled.", decode_text) + + def test_sequence_builders(self): + tokenizer = RemBertTokenizer(SAMPLE_VOCAB) + + text = tokenizer.encode("sequence builders") + text_2 = tokenizer.encode("multi-sequence build") + + encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [ + tokenizer.sep_token_id + ] + + def test_added_tokens_serialization(self): + # Utility to test the added vocab + def _test_added_vocab_and_eos(expected, tokenizer_class, expected_eos, temp_dir): + tokenizer = tokenizer_class.from_pretrained(temp_dir) + self.assertTrue(str(expected_eos) not in tokenizer.additional_special_tokens) + self.assertIn(new_eos, tokenizer.added_tokens_decoder.values()) + self.assertEqual(tokenizer.added_tokens_decoder[tokenizer.eos_token_id], new_eos) + self.assertDictEqual(expected, tokenizer.added_tokens_decoder) + return tokenizer + + new_eos = AddedToken("[NEW_EOS]", rstrip=False, lstrip=True, normalized=False, special=True) + new_masked_token = AddedToken("[MASK]", lstrip=True, rstrip=False, normalized=False) + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + # Load a slow tokenizer from the hub, init with the new token for fast to also include it + tokenizer = self.tokenizer_class.from_pretrained( + pretrained_name, eos_token=new_eos, mask_token=new_masked_token + ) + EXPECTED_ADDED_TOKENS_DECODER = tokenizer.added_tokens_decoder + with self.subTest("Hub -> Slow: Test loading a slow tokenizer from the hub)"): + self.assertEqual(tokenizer._eos_token, new_eos) + self.assertIn(new_eos, list(tokenizer.added_tokens_decoder.values())) + + with tempfile.TemporaryDirectory() as tmp_dir_2: + tokenizer.save_pretrained(tmp_dir_2) + with self.subTest( + "Hub -> Slow -> Slow: Test saving this slow tokenizer and reloading it in the fast class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_2 + ) + + if self.rust_tokenizer_class is not None: + with self.subTest( + "Hub -> Slow -> Fast: Test saving this slow tokenizer and reloading it in the fast class" + ): + tokenizer_fast = _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_2 + ) + with tempfile.TemporaryDirectory() as tmp_dir_3: + tokenizer_fast.save_pretrained(tmp_dir_3) + with self.subTest( + "Hub -> Slow -> Fast -> Fast: Test saving this fast tokenizer and reloading it in the fast class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3 + ) + + with self.subTest( + "Hub -> Slow -> Fast -> Slow: Test saving this slow tokenizer and reloading it in the slow class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3 + ) + + with self.subTest("Hub -> Fast: Test loading a fast tokenizer from the hub)"): + if self.rust_tokenizer_class is not None: + tokenizer_fast = self.rust_tokenizer_class.from_pretrained(pretrained_name, eos_token=new_eos) + self.assertEqual(tokenizer_fast._eos_token, new_eos) + self.assertIn(new_eos, list(tokenizer_fast.added_tokens_decoder.values())) + # We can't test the following because for BC we kept the default rstrip lstrip in slow not fast. Will comment once normalization is alright + with self.subTest("Hub -> Fast == Hub -> Slow: make sure slow and fast tokenizer match"): + self.assertDictEqual(EXPECTED_ADDED_TOKENS_DECODER, tokenizer_fast.added_tokens_decoder) + + EXPECTED_ADDED_TOKENS_DECODER = tokenizer_fast.added_tokens_decoder + with tempfile.TemporaryDirectory() as tmp_dir_4: + tokenizer_fast.save_pretrained(tmp_dir_4) + with self.subTest("Hub -> Fast -> Fast: saving Fast1 locally and loading"): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_4 + ) + + with self.subTest("Hub -> Fast -> Slow: saving Fast1 locally and loading"): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_4 + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_flax_resnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_flax_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..e9566e2e2fd5fb7b275ef942c872c9b1c4eb85bc --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_flax_resnet.py @@ -0,0 +1,228 @@ +# Copyright 2023 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 inspect +import unittest + +from transformers import ResNetConfig, is_flax_available +from transformers.testing_utils import require_flax, slow +from transformers.utils import cached_property, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor + + +if is_flax_available(): + import jax + import jax.numpy as jnp + + from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class FlaxResNetModelTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=3, + image_size=32, + num_channels=3, + embeddings_size=10, + hidden_sizes=[10, 20, 30, 40], + depths=[1, 1, 2, 1], + is_training=True, + use_labels=True, + hidden_act="relu", + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.embeddings_size = embeddings_size + self.hidden_sizes = hidden_sizes + self.depths = depths + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.num_labels = num_labels + self.scope = scope + self.num_stages = len(hidden_sizes) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + config = self.get_config() + + return config, pixel_values + + def get_config(self): + return ResNetConfig( + num_channels=self.num_channels, + embeddings_size=self.embeddings_size, + hidden_sizes=self.hidden_sizes, + depths=self.depths, + hidden_act=self.hidden_act, + num_labels=self.num_labels, + image_size=self.image_size, + ) + + def create_and_check_model(self, config, pixel_values): + model = FlaxResNetModel(config=config) + result = model(pixel_values) + + # Output shape (b, c, h, w) + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), + ) + + def create_and_check_for_image_classification(self, config, pixel_values): + config.num_labels = self.num_labels + model = FlaxResNetForImageClassification(config=config) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_flax +class FlaxResNetModelTest(FlaxModelTesterMixin, unittest.TestCase): + all_model_classes = (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else () + + is_encoder_decoder = False + test_head_masking = False + has_attentions = False + + def setUp(self) -> None: + self.model_tester = FlaxResNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=ResNetConfig, has_text_modality=False) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @unittest.skip(reason="ResNet does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="ResNet does not support input and output embeddings") + def test_model_common_attributes(self): + pass + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.__call__) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_stages = self.model_tester.num_stages + self.assertEqual(len(hidden_states), expected_num_stages + 1) + + @unittest.skip(reason="ResNet does not use feedforward chunking") + def test_feed_forward_chunking(self): + pass + + def test_jit_compilation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def model_jitted(pixel_values, **kwargs): + return model(pixel_values=pixel_values, **kwargs) + + with self.subTest("JIT Enabled"): + jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_flax +class FlaxResNetModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return AutoImageProcessor.from_pretrained("microsoft/resnet-50") if is_vision_available() else None + + @slow + def test_inference_image_classification_head(self): + model = FlaxResNetForImageClassification.from_pretrained("microsoft/resnet-50") + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="np") + + outputs = model(**inputs) + + # verify the logits + expected_shape = (1, 1000) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = jnp.array([-11.1069, -9.7877, -8.3777]) + + self.assertTrue(jnp.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_resnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..bae9eb6d24c8cbec1d8dce0b7c8d5f8e9b545b9c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_resnet.py @@ -0,0 +1,326 @@ +# coding=utf-8 +# Copyright 2022 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 ResNet model. """ + + +import unittest + +from transformers import ResNetConfig +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_backbone_common import BackboneTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel + from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class ResNetModelTester: + def __init__( + self, + parent, + batch_size=3, + image_size=32, + num_channels=3, + embeddings_size=10, + hidden_sizes=[10, 20, 30, 40], + depths=[1, 1, 2, 1], + is_training=True, + use_labels=True, + hidden_act="relu", + num_labels=3, + scope=None, + out_features=["stage2", "stage3", "stage4"], + out_indices=[2, 3, 4], + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.embeddings_size = embeddings_size + self.hidden_sizes = hidden_sizes + self.depths = depths + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.num_labels = num_labels + self.scope = scope + self.num_stages = len(hidden_sizes) + self.out_features = out_features + self.out_indices = out_indices + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.num_labels) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return ResNetConfig( + num_channels=self.num_channels, + embeddings_size=self.embeddings_size, + hidden_sizes=self.hidden_sizes, + depths=self.depths, + hidden_act=self.hidden_act, + num_labels=self.num_labels, + out_features=self.out_features, + out_indices=self.out_indices, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = ResNetModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + # expected last hidden states: B, C, H // 32, W // 32 + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), + ) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.num_labels + model = ResNetForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_backbone(self, config, pixel_values, labels): + model = ResNetBackbone(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + # verify feature maps + self.parent.assertEqual(len(result.feature_maps), len(config.out_features)) + self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[1], 4, 4]) + + # verify channels + self.parent.assertEqual(len(model.channels), len(config.out_features)) + self.parent.assertListEqual(model.channels, config.hidden_sizes[1:]) + + # verify backbone works with out_features=None + config.out_features = None + model = ResNetBackbone(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + # verify feature maps + self.parent.assertEqual(len(result.feature_maps), 1) + self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[-1], 1, 1]) + + # verify channels + self.parent.assertEqual(len(model.channels), 1) + self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]]) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class ResNetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as ResNet does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = ( + ( + ResNetModel, + ResNetForImageClassification, + ResNetBackbone, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + {"feature-extraction": ResNetModel, "image-classification": ResNetForImageClassification} + if is_torch_available() + else {} + ) + + fx_compatible = True + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + has_attentions = False + + def setUp(self): + self.model_tester = ResNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=ResNetConfig, has_text_modality=False) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + @unittest.skip(reason="ResNet does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="ResNet does not support input and output embeddings") + def test_model_common_attributes(self): + pass + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_backbone(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_backbone(*config_and_inputs) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config=config) + for name, module in model.named_modules(): + if isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)): + self.assertTrue( + torch.all(module.weight == 1), + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + self.assertTrue( + torch.all(module.bias == 0), + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_stages = self.model_tester.num_stages + self.assertEqual(len(hidden_states), expected_num_stages + 1) + + # ResNet's feature maps are of shape (batch_size, num_channels, height, width) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.image_size // 4, self.model_tester.image_size // 4], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + layers_type = ["basic", "bottleneck"] + for model_class in self.all_model_classes: + for layer_type in layers_type: + config.layer_type = layer_type + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + @unittest.skip(reason="ResNet does not use feedforward chunking") + def test_feed_forward_chunking(self): + pass + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = ResNetModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class ResNetModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ( + AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) + if is_vision_available() + else None + ) + + @slow + def test_inference_image_classification_head(self): + model = ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-11.1069, -9.7877, -8.3777]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) + + +@require_torch +class ResNetBackboneTest(BackboneTesterMixin, unittest.TestCase): + all_model_classes = (ResNetBackbone,) if is_torch_available() else () + has_attentions = False + config_class = ResNetConfig + + def setUp(self): + self.model_tester = ResNetModelTester(self) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_tf_resnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_tf_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..827fc807dfe5ab02c278e64e6df21f688f5767b3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/resnet/test_modeling_tf_resnet.py @@ -0,0 +1,256 @@ +# coding=utf-8 +# Copyright 2022 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 Tensorflow ResNet model. """ + + +from __future__ import annotations + +import inspect +import unittest + +import numpy as np + +from transformers import ResNetConfig +from transformers.testing_utils import require_tf, require_vision, slow +from transformers.utils import cached_property, is_tf_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import TFResNetForImageClassification, TFResNetModel + from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class TFResNetModelTester: + def __init__( + self, + parent, + batch_size=3, + image_size=32, + num_channels=3, + embeddings_size=10, + hidden_sizes=[10, 20, 30, 40], + depths=[1, 1, 2, 1], + is_training=True, + use_labels=True, + hidden_act="relu", + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.embeddings_size = embeddings_size + self.hidden_sizes = hidden_sizes + self.depths = depths + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.num_labels = num_labels + self.scope = scope + self.num_stages = len(hidden_sizes) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.num_labels) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return ResNetConfig( + num_channels=self.num_channels, + embeddings_size=self.embeddings_size, + hidden_sizes=self.hidden_sizes, + depths=self.depths, + hidden_act=self.hidden_act, + num_labels=self.num_labels, + image_size=self.image_size, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = TFResNetModel(config=config) + result = model(pixel_values) + # expected last hidden states: B, C, H // 32, W // 32 + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), + ) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.num_labels + model = TFResNetForImageClassification(config) + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_tf +class TFResNetModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as ResNet does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () + pipeline_model_mapping = ( + {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification} + if is_tf_available() + else {} + ) + + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + test_onnx = False + has_attentions = False + + def setUp(self): + self.model_tester = TFResNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=ResNetConfig, has_text_modality=False) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + @unittest.skip(reason="ResNet does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="ResNet does not support input and output embeddings") + def test_model_common_attributes(self): + pass + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_stages = self.model_tester.num_stages + self.assertEqual(len(hidden_states), expected_num_stages + 1) + + # ResNet's feature maps are of shape (batch_size, num_channels, height, width) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.image_size // 4, self.model_tester.image_size // 4], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + layers_type = ["basic", "bottleneck"] + for model_class in self.all_model_classes: + for layer_type in layers_type: + config.layer_type = layer_type + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFResNetModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_tf +@require_vision +class TFResNetModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ( + AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) + if is_vision_available() + else None + ) + + @slow + def test_inference_image_classification_head(self): + model = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="tf") + + # forward pass + outputs = model(**inputs) + + # verify the logits + expected_shape = tf.TensorShape((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = tf.constant([-11.1069, -9.7877, -8.3777]) + + self.assertTrue(np.allclose(outputs.logits[0, :3].numpy(), expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_flax_roberta.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_flax_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..f82479aa706fd0cef6ad3d1d48318fe6d694689c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_flax_roberta.py @@ -0,0 +1,159 @@ +# 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 unittest + +import numpy as np + +from transformers import RobertaConfig, is_flax_available +from transformers.testing_utils import require_flax, slow + +from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask + + +if is_flax_available(): + from transformers.models.roberta.modeling_flax_roberta import ( + FlaxRobertaForCausalLM, + FlaxRobertaForMaskedLM, + FlaxRobertaForMultipleChoice, + FlaxRobertaForQuestionAnswering, + FlaxRobertaForSequenceClassification, + FlaxRobertaForTokenClassification, + FlaxRobertaModel, + ) + + +class FlaxRobertaModelTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_attention_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_choices=4, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_choices = num_choices + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + config = RobertaConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + return config, input_ids, token_type_ids, attention_mask + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, token_type_ids, attention_mask = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} + return config, inputs_dict + + def prepare_config_and_inputs_for_decoder(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, token_type_ids, attention_mask = config_and_inputs + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + encoder_hidden_states, + encoder_attention_mask, + ) + + +@require_flax +class FlaxRobertaModelTest(FlaxModelTesterMixin, unittest.TestCase): + test_head_masking = True + + all_model_classes = ( + ( + FlaxRobertaModel, + FlaxRobertaForCausalLM, + FlaxRobertaForMaskedLM, + FlaxRobertaForSequenceClassification, + FlaxRobertaForTokenClassification, + FlaxRobertaForMultipleChoice, + FlaxRobertaForQuestionAnswering, + ) + if is_flax_available() + else () + ) + + def setUp(self): + self.model_tester = FlaxRobertaModelTester(self) + + @slow + def test_model_from_pretrained(self): + for model_class_name in self.all_model_classes: + model = model_class_name.from_pretrained("roberta-base", from_pt=True) + outputs = model(np.ones((1, 1))) + self.assertIsNotNone(outputs) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_roberta.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..6cacf605a26a035a4686a951b053c2393aa811aa --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_roberta.py @@ -0,0 +1,581 @@ +# coding=utf-8 +# 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 unittest + +from transformers import RobertaConfig, is_torch_available +from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + RobertaForCausalLM, + RobertaForMaskedLM, + RobertaForMultipleChoice, + RobertaForQuestionAnswering, + RobertaForSequenceClassification, + RobertaForTokenClassification, + RobertaModel, + ) + from transformers.models.roberta.modeling_roberta import ( + ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, + RobertaEmbeddings, + create_position_ids_from_input_ids, + ) + +ROBERTA_TINY = "sshleifer/tiny-distilroberta-base" + + +class RobertaModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def get_config(self): + return RobertaConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + ) + + def get_pipeline_config(self): + config = self.get_config() + config.vocab_size = 300 + return config + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RobertaModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = RobertaModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = RobertaForCausalLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = RobertaForCausalLM(config=config).to(torch_device).eval() + + # make sure that ids don't start with pad token + mask = input_ids.ne(config.pad_token_id).long() + input_ids = input_ids * mask + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + + # make sure that ids don't start with pad token + mask = next_tokens.ne(config.pad_token_id).long() + next_tokens = next_tokens * mask + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # 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)) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RobertaForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = RobertaForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = RobertaForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RobertaForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class RobertaModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + RobertaForCausalLM, + RobertaForMaskedLM, + RobertaModel, + RobertaForSequenceClassification, + RobertaForTokenClassification, + RobertaForMultipleChoice, + RobertaForQuestionAnswering, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (RobertaForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": RobertaModel, + "fill-mask": RobertaForMaskedLM, + "question-answering": RobertaForQuestionAnswering, + "text-classification": RobertaForSequenceClassification, + "text-generation": RobertaForCausalLM, + "token-classification": RobertaForTokenClassification, + "zero-shot": RobertaForSequenceClassification, + } + if is_torch_available() + else {} + ) + fx_compatible = True + model_split_percents = [0.5, 0.8, 0.9] + + def setUp(self): + self.model_tester = RobertaModelTester(self) + self.config_tester = ConfigTester(self, config_class=RobertaConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_as_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_model_as_decoder_with_default_input_mask(self): + # This regression test was failing with PyTorch < 1.3 + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = self.model_tester.prepare_config_and_inputs_for_decoder() + + input_mask = None + + self.model_tester.create_and_check_model_as_decoder( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def test_for_causal_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_for_causal_lm(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs_relative_pos_emb(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + config_and_inputs[0].position_embedding_type = "relative_key" + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = RobertaModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_create_position_ids_respects_padding_index(self): + """Ensure that the default position ids only assign a sequential . This is a regression + test for https://github.com/huggingface/transformers/issues/1761 + + The position ids should be masked with the embedding object's padding index. Therefore, the + first available non-padding position index is RobertaEmbeddings.padding_idx + 1 + """ + config = self.model_tester.prepare_config_and_inputs()[0] + model = RobertaEmbeddings(config=config) + + input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]]) + expected_positions = torch.as_tensor( + [[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]] + ) + + position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx) + self.assertEqual(position_ids.shape, expected_positions.shape) + self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) + + def test_create_position_ids_from_inputs_embeds(self): + """Ensure that the default position ids only assign a sequential . This is a regression + test for https://github.com/huggingface/transformers/issues/1761 + + The position ids should be masked with the embedding object's padding index. Therefore, the + first available non-padding position index is RobertaEmbeddings.padding_idx + 1 + """ + config = self.model_tester.prepare_config_and_inputs()[0] + embeddings = RobertaEmbeddings(config=config) + + inputs_embeds = torch.empty(2, 4, 30) + expected_single_positions = [ + 0 + embeddings.padding_idx + 1, + 1 + embeddings.padding_idx + 1, + 2 + embeddings.padding_idx + 1, + 3 + embeddings.padding_idx + 1, + ] + expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions]) + position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds) + self.assertEqual(position_ids.shape, expected_positions.shape) + self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) + + +@require_torch +class RobertaModelIntegrationTest(TestCasePlus): + @slow + def test_inference_masked_lm(self): + model = RobertaForMaskedLM.from_pretrained("roberta-base") + + input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + with torch.no_grad(): + output = model(input_ids)[0] + expected_shape = torch.Size((1, 11, 50265)) + self.assertEqual(output.shape, expected_shape) + # compare the actual values for a slice. + expected_slice = torch.tensor( + [[[33.8802, -4.3103, 22.7761], [4.6539, -2.8098, 13.6253], [1.8228, -3.6898, 8.8600]]] + ) + + # roberta = torch.hub.load('pytorch/fairseq', 'roberta.base') + # roberta.eval() + # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() + + self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_no_head(self): + model = RobertaModel.from_pretrained("roberta-base") + + input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + with torch.no_grad(): + output = model(input_ids)[0] + # compare the actual values for a slice. + expected_slice = torch.tensor( + [[[-0.0231, 0.0782, 0.0074], [-0.1854, 0.0540, -0.0175], [0.0548, 0.0799, 0.1687]]] + ) + + # roberta = torch.hub.load('pytorch/fairseq', 'roberta.base') + # roberta.eval() + # expected_slice = roberta.extract_features(input_ids)[:, :3, :3].detach() + + self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_classification_head(self): + model = RobertaForSequenceClassification.from_pretrained("roberta-large-mnli") + + input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + with torch.no_grad(): + output = model(input_ids)[0] + expected_shape = torch.Size((1, 3)) + self.assertEqual(output.shape, expected_shape) + expected_tensor = torch.tensor([[-0.9469, 0.3913, 0.5118]]) + + # roberta = torch.hub.load('pytorch/fairseq', 'roberta.large.mnli') + # roberta.eval() + # expected_tensor = roberta.predict("mnli", input_ids, return_logits=True).detach() + + self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_tf_roberta.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_tf_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..2f2859391ad3af25528b2df6540e1049c1266d25 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_modeling_tf_roberta.py @@ -0,0 +1,702 @@ +# coding=utf-8 +# 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. + + +from __future__ import annotations + +import unittest + +from transformers import RobertaConfig, is_tf_available +from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import numpy + import tensorflow as tf + + from transformers.models.roberta.modeling_tf_roberta import ( + TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, + TFRobertaForCausalLM, + TFRobertaForMaskedLM, + TFRobertaForMultipleChoice, + TFRobertaForQuestionAnswering, + TFRobertaForSequenceClassification, + TFRobertaForTokenClassification, + TFRobertaModel, + ) + + +class TFRobertaModelTester: + def __init__( + self, + parent, + ): + self.parent = parent + self.batch_size = 13 + self.seq_length = 7 + self.is_training = True + self.use_input_mask = True + self.use_token_type_ids = True + self.use_labels = True + self.vocab_size = 99 + self.hidden_size = 32 + self.num_hidden_layers = 2 + self.num_attention_heads = 4 + self.intermediate_size = 37 + self.hidden_act = "gelu" + self.hidden_dropout_prob = 0.1 + self.attention_probs_dropout_prob = 0.1 + self.max_position_embeddings = 512 + self.type_vocab_size = 16 + self.type_sequence_label_size = 2 + self.initializer_range = 0.02 + self.num_labels = 3 + self.num_choices = 4 + self.scope = None + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = RobertaConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + ) + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRobertaModel(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs) + + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_causal_lm_base_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.is_decoder = True + + model = TFRobertaModel(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs) + + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRobertaModel(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "encoder_hidden_states": encoder_hidden_states, + "encoder_attention_mask": encoder_attention_mask, + } + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states) + + # Also check the case where encoder outputs are not passed + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_causal_lm_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.is_decoder = True + + model = TFRobertaForCausalLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + prediction_scores = model(inputs)["logits"] + self.parent.assertListEqual( + list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size] + ) + + def create_and_check_causal_lm_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRobertaForCausalLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "encoder_hidden_states": encoder_hidden_states, + "encoder_attention_mask": encoder_attention_mask, + } + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states) + + prediction_scores = result["logits"] + self.parent.assertListEqual( + list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size] + ) + + def create_and_check_causal_lm_model_past( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRobertaForCausalLM(config=config) + + # special to `RobertaEmbeddings` in `Roberta`: + # - its `padding_idx` and its effect on `position_ids` + # (TFRobertaEmbeddings.create_position_ids_from_input_ids) + # - `1` here is `TFRobertaEmbeddings.padding_idx` + input_ids = tf.where(input_ids == 1, 2, input_ids) + + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + past_key_values = outputs.past_key_values + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and attn_mask + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + + output_from_no_past = model(next_input_ids, output_hidden_states=True).hidden_states[0] + output_from_past = model( + next_tokens, past_key_values=past_key_values, output_hidden_states=True + ).hidden_states[0] + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx] + output_from_past_slice = output_from_past[:, 0, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6) + + def create_and_check_causal_lm_model_past_with_attn_mask( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRobertaForCausalLM(config=config) + + # special to `RobertaEmbeddings` in `Roberta`: + # - its `padding_idx` and its effect on `position_ids` + # (TFRobertaEmbeddings.create_position_ids_from_input_ids) + # - `1` here is `TFRobertaEmbeddings.padding_idx` + # avoid `padding_idx` in the past + input_ids = tf.where(input_ids == 1, 2, input_ids) + + # create attention mask + half_seq_length = self.seq_length // 2 + attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32) + attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32) + attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1) + + # first forward pass + outputs = model(input_ids, attention_mask=attn_mask, use_cache=True) + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + past_key_values = outputs.past_key_values + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size) + vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change) + condition = tf.transpose( + tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size)) + ) + input_ids = tf.where(condition, random_other_next_tokens, input_ids) + # avoid `padding_idx` in the past + input_ids = tf.where(input_ids == 1, 2, input_ids) + + # append to next input_ids and + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + attn_mask = tf.concat( + [attn_mask, tf.ones((attn_mask.shape[0], 1), dtype=tf.int32)], + axis=1, + ) + + output_from_no_past = model( + next_input_ids, + attention_mask=attn_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, past_key_values=past_key_values, attention_mask=attn_mask, output_hidden_states=True + ).hidden_states[0] + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx] + output_from_past_slice = output_from_past[:, 0, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6) + + def create_and_check_causal_lm_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRobertaForCausalLM(config=config) + + # special to `RobertaEmbeddings` in `Roberta`: + # - its `padding_idx` and its effect on `position_ids` + # (TFRobertaEmbeddings.create_position_ids_from_input_ids) + # - `1` here is `TFRobertaEmbeddings.padding_idx` + # avoid `padding_idx` in the past + input_ids = tf.where(input_ids == 1, 2, input_ids) + + input_ids = input_ids[:1, :] + input_mask = input_mask[:1, :] + self.batch_size = 1 + + # first forward pass + outputs = model(input_ids, attention_mask=input_mask, use_cache=True) + past_key_values = outputs.past_key_values + + # create hypothetical 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 = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + ).hidden_states[0] + + self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1]) + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRobertaForCausalLM(config=config) + + # special to `RobertaEmbeddings` in `Roberta`: + # - its `padding_idx` and its effect on `position_ids` + # (TFRobertaEmbeddings.create_position_ids_from_input_ids) + # - `1` here is `TFRobertaEmbeddings.padding_idx` + # avoid `padding_idx` in the past + input_ids = tf.where(input_ids == 1, 2, input_ids) + + input_ids = input_ids[:1, :] + input_mask = input_mask[:1, :] + encoder_hidden_states = encoder_hidden_states[:1, :, :] + encoder_attention_mask = encoder_attention_mask[:1, :] + self.batch_size = 1 + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical 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 = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + ).hidden_states[0] + + self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1]) + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRobertaForMaskedLM(config=config) + result = model([input_ids, input_mask, token_type_ids]) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = TFRobertaForTokenClassification(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRobertaForQuestionAnswering(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = TFRobertaForMultipleChoice(config=config) + multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1)) + multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1)) + multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1)) + inputs = { + "input_ids": multiple_choice_inputs_ids, + "attention_mask": multiple_choice_input_mask, + "token_type_ids": multiple_choice_token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_tf +class TFRobertaModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TFRobertaModel, + TFRobertaForCausalLM, + TFRobertaForMaskedLM, + TFRobertaForSequenceClassification, + TFRobertaForTokenClassification, + TFRobertaForQuestionAnswering, + ) + if is_tf_available() + else () + ) + pipeline_model_mapping = ( + { + "feature-extraction": TFRobertaModel, + "fill-mask": TFRobertaForMaskedLM, + "question-answering": TFRobertaForQuestionAnswering, + "text-classification": TFRobertaForSequenceClassification, + "text-generation": TFRobertaForCausalLM, + "token-classification": TFRobertaForTokenClassification, + "zero-shot": TFRobertaForSequenceClassification, + } + if is_tf_available() + else {} + ) + test_head_masking = False + test_onnx = False + + def setUp(self): + self.model_tester = TFRobertaModelTester(self) + self.config_tester = ConfigTester(self, config_class=RobertaConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + """Test the base model""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_causal_lm_base_model(self): + """Test the base model of the causal LM model + + is_deocder=True, no cross_attention, no encoder outputs + """ + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_base_model(*config_and_inputs) + + def test_model_as_decoder(self): + """Test the base model as a decoder (of an encoder-decoder architecture) + + is_deocder=True + cross_attention + pass encoder outputs + """ + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_causal_lm(self): + """Test the causal LM model""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model(*config_and_inputs) + + def test_causal_lm_model_as_decoder(self): + """Test the causal LM model as a decoder""" + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_causal_lm_model_as_decoder(*config_and_inputs) + + def test_causal_lm_model_past(self): + """Test causal LM model with `past_key_values`""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past(*config_and_inputs) + + def test_causal_lm_model_past_with_attn_mask(self): + """Test the causal LM model with `past_key_values` and `attention_mask`""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past_with_attn_mask(*config_and_inputs) + + def test_causal_lm_model_past_with_large_inputs(self): + """Test the causal LM model with `past_key_values` and a longer decoder sequence length""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past_large_inputs(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + """Similar to `test_causal_lm_model_past_with_large_inputs` but with cross-attention""" + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFRobertaModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_tf +@require_sentencepiece +@require_tokenizers +class TFRobertaModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_masked_lm(self): + model = TFRobertaForMaskedLM.from_pretrained("roberta-base") + + input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + output = model(input_ids)[0] + expected_shape = [1, 11, 50265] + self.assertEqual(list(output.numpy().shape), expected_shape) + # compare the actual values for a slice. + expected_slice = tf.constant( + [[[33.8802, -4.3103, 22.7761], [4.6539, -2.8098, 13.6253], [1.8228, -3.6898, 8.8600]]] + ) + self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-4)) + + @slow + def test_inference_no_head(self): + model = TFRobertaModel.from_pretrained("roberta-base") + + input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + output = model(input_ids)[0] + # compare the actual values for a slice. + expected_slice = tf.constant( + [[[-0.0231, 0.0782, 0.0074], [-0.1854, 0.0540, -0.0175], [0.0548, 0.0799, 0.1687]]] + ) + self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-4)) + + @slow + def test_inference_classification_head(self): + model = TFRobertaForSequenceClassification.from_pretrained("roberta-large-mnli") + + input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + output = model(input_ids)[0] + expected_shape = [1, 3] + self.assertEqual(list(output.numpy().shape), expected_shape) + expected_tensor = tf.constant([[-0.9469, 0.3913, 0.5118]]) + self.assertTrue(numpy.allclose(output.numpy(), expected_tensor.numpy(), atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_tokenization_roberta.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_tokenization_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..3190ab13be4ea18ac88b91f862a0d67257fddc6a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta/test_tokenization_roberta.py @@ -0,0 +1,303 @@ +# coding=utf-8 +# 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 itertools +import json +import os +import unittest + +from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast +from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES +from transformers.testing_utils import require_tokenizers, slow + +from ...test_tokenization_common import TokenizerTesterMixin + + +@require_tokenizers +class RobertaTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = RobertaTokenizer + rust_tokenizer_class = RobertaTokenizerFast + test_rust_tokenizer = True + from_pretrained_kwargs = {"cls_token": ""} + + def setUp(self): + super().setUp() + + # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt + 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): + input_text = "lower newer" + output_text = "lower newer" + return input_text, output_text + + def test_full_tokenizer(self): + tokenizer = self.tokenizer_class(self.vocab_file, self.merges_file, **self.special_tokens_map) + text = "lower newer" + bpe_tokens = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"] + tokens = tokenizer.tokenize(text) # , add_prefix_space=True) + self.assertListEqual(tokens, bpe_tokens) + + input_tokens = tokens + [tokenizer.unk_token] + input_bpe_tokens = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] + self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens) + + def roberta_dict_integration_testing(self): + tokenizer = self.get_tokenizer() + + self.assertListEqual(tokenizer.encode("Hello world!", add_special_tokens=False), [0, 31414, 232, 328, 2]) + self.assertListEqual( + tokenizer.encode("Hello world! cécé herlolip 418", add_special_tokens=False), + [0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2], + ) + + @slow + def test_sequence_builders(self): + tokenizer = self.tokenizer_class.from_pretrained("roberta-base") + + text = tokenizer.encode("sequence builders", add_special_tokens=False) + text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False) + + encoded_text_from_decode = tokenizer.encode( + "sequence builders", add_special_tokens=True, add_prefix_space=False + ) + encoded_pair_from_decode = tokenizer.encode( + "sequence builders", "multi-sequence build", add_special_tokens=True, add_prefix_space=False + ) + + encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_sentence == encoded_text_from_decode + assert encoded_pair == encoded_pair_from_decode + + def test_space_encoding(self): + tokenizer = self.get_tokenizer() + + sequence = "Encode this sequence." + space_encoding = tokenizer.byte_encoder[" ".encode("utf-8")[0]] + + # Testing encoder arguments + encoded = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=False) + first_char = tokenizer.convert_ids_to_tokens(encoded[0])[0] + self.assertNotEqual(first_char, space_encoding) + + encoded = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=True) + first_char = tokenizer.convert_ids_to_tokens(encoded[0])[0] + self.assertEqual(first_char, space_encoding) + + tokenizer.add_special_tokens({"bos_token": ""}) + encoded = tokenizer.encode(sequence, add_special_tokens=True) + first_char = tokenizer.convert_ids_to_tokens(encoded[1])[0] + self.assertNotEqual(first_char, space_encoding) + + # Testing spaces after special tokens + mask = "" + tokenizer.add_special_tokens( + {"mask_token": AddedToken(mask, lstrip=True, rstrip=False)} + ) # mask token has a left space + mask_ind = tokenizer.convert_tokens_to_ids(mask) + + sequence = "Encode sequence" + sequence_nospace = "Encode sequence" + + encoded = tokenizer.encode(sequence) + mask_loc = encoded.index(mask_ind) + first_char = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0] + self.assertEqual(first_char, space_encoding) + + encoded = tokenizer.encode(sequence_nospace) + mask_loc = encoded.index(mask_ind) + first_char = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1])[0] + self.assertNotEqual(first_char, space_encoding) + + 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_change_add_prefix_space_and_trim_offsets_args(self): + for trim_offsets, add_prefix_space in itertools.product([True, False], repeat=2): + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + self.tmpdirname, use_fast=True, add_prefix_space=add_prefix_space, trim_offsets=trim_offsets + ) + + pre_tokenizer_state = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__()) + post_processor_state = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__()) + + self.assertEqual(pre_tokenizer_state["add_prefix_space"], add_prefix_space) + + self.assertEqual(post_processor_state["add_prefix_space"], add_prefix_space) + self.assertEqual(post_processor_state["trim_offsets"], trim_offsets) + + def test_offsets_mapping_with_different_add_prefix_space_and_trim_space_arguments(self): + # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and + # `trim_offsets` + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + text_of_1_token = "hello" # `hello` is a token in the vocabulary of `pretrained_name` + text = f"{text_of_1_token} {text_of_1_token}" + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True + ) + encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) + self.assertEqual(encoding.offset_mapping[0], (0, len(text_of_1_token))) + self.assertEqual( + encoding.offset_mapping[1], + (len(text_of_1_token) + 1, len(text_of_1_token) + 1 + len(text_of_1_token)), + ) + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, use_fast=True, add_prefix_space=False, trim_offsets=True + ) + encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) + self.assertEqual(encoding.offset_mapping[0], (0, len(text_of_1_token))) + self.assertEqual( + encoding.offset_mapping[1], + (len(text_of_1_token) + 1, len(text_of_1_token) + 1 + len(text_of_1_token)), + ) + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=False + ) + encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) + self.assertEqual(encoding.offset_mapping[0], (0, len(text_of_1_token))) + self.assertEqual( + encoding.offset_mapping[1], + (len(text_of_1_token), len(text_of_1_token) + 1 + len(text_of_1_token)), + ) + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, use_fast=True, add_prefix_space=False, trim_offsets=False + ) + encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) + self.assertEqual(encoding.offset_mapping[0], (0, len(text_of_1_token))) + self.assertEqual( + encoding.offset_mapping[1], + (len(text_of_1_token), len(text_of_1_token) + 1 + len(text_of_1_token)), + ) + + text = f" {text}" + + # tokenizer_r = self.rust_tokenizer_class.from_pretrained( + # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True + # ) + # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) + # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) + # self.assertEqual( + # encoding.offset_mapping[1], + # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), + # ) + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, use_fast=True, add_prefix_space=False, trim_offsets=True + ) + encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) + self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) + self.assertEqual( + encoding.offset_mapping[1], + (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), + ) + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=False + ) + encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) + self.assertEqual(encoding.offset_mapping[0], (0, 1 + len(text_of_1_token))) + self.assertEqual( + encoding.offset_mapping[1], + (1 + len(text_of_1_token), 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), + ) + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, use_fast=True, add_prefix_space=False, trim_offsets=False + ) + encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) + self.assertEqual(encoding.offset_mapping[0], (0, 1 + len(text_of_1_token))) + self.assertEqual( + encoding.offset_mapping[1], + (1 + len(text_of_1_token), 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_flax_roberta_prelayernorm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_flax_roberta_prelayernorm.py new file mode 100644 index 0000000000000000000000000000000000000000..65dbe65974d4c484c75a89a68e4c382028a4c732 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_flax_roberta_prelayernorm.py @@ -0,0 +1,192 @@ +# Copyright 2022 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 unittest + +import numpy as np + +from transformers import RobertaPreLayerNormConfig, is_flax_available +from transformers.testing_utils import require_flax, slow + +from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask + + +if is_flax_available(): + import jax.numpy as jnp + + from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( + FlaxRobertaPreLayerNormForCausalLM, + FlaxRobertaPreLayerNormForMaskedLM, + FlaxRobertaPreLayerNormForMultipleChoice, + FlaxRobertaPreLayerNormForQuestionAnswering, + FlaxRobertaPreLayerNormForSequenceClassification, + FlaxRobertaPreLayerNormForTokenClassification, + FlaxRobertaPreLayerNormModel, + ) + + +# Copied from tests.models.roberta.test_modeling_flax_roberta.FlaxRobertaModelTester with Roberta->RobertaPreLayerNorm +class FlaxRobertaPreLayerNormModelTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_attention_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_choices=4, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_choices = num_choices + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + config = RobertaPreLayerNormConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + return config, input_ids, token_type_ids, attention_mask + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, token_type_ids, attention_mask = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} + return config, inputs_dict + + def prepare_config_and_inputs_for_decoder(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, token_type_ids, attention_mask = config_and_inputs + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + encoder_hidden_states, + encoder_attention_mask, + ) + + +@require_flax +# Copied from tests.models.roberta.test_modeling_flax_roberta.FlaxRobertaModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 +class FlaxRobertaPreLayerNormModelTest(FlaxModelTesterMixin, unittest.TestCase): + test_head_masking = True + + all_model_classes = ( + ( + FlaxRobertaPreLayerNormModel, + FlaxRobertaPreLayerNormForCausalLM, + FlaxRobertaPreLayerNormForMaskedLM, + FlaxRobertaPreLayerNormForSequenceClassification, + FlaxRobertaPreLayerNormForTokenClassification, + FlaxRobertaPreLayerNormForMultipleChoice, + FlaxRobertaPreLayerNormForQuestionAnswering, + ) + if is_flax_available() + else () + ) + + def setUp(self): + self.model_tester = FlaxRobertaPreLayerNormModelTester(self) + + @slow + def test_model_from_pretrained(self): + for model_class_name in self.all_model_classes: + model = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40", from_pt=True) + outputs = model(np.ones((1, 1))) + self.assertIsNotNone(outputs) + + +@require_flax +class TFRobertaPreLayerNormModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_masked_lm(self): + model = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40", from_pt=True) + + input_ids = np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]], dtype=jnp.int32) + output = model(input_ids)[0] + expected_shape = [1, 11, 50265] + self.assertEqual(list(output.shape), expected_shape) + # compare the actual values for a slice. + EXPECTED_SLICE = np.array( + [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]], dtype=np.float32 + ) + self.assertTrue(np.allclose(output[:, :3, :3], EXPECTED_SLICE, atol=1e-4)) + + @slow + def test_inference_no_head(self): + model = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40", from_pt=True) + + input_ids = np.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]], dtype=jnp.int32) + output = model(input_ids)[0] + # compare the actual values for a slice. + EXPECTED_SLICE = np.array( + [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]], dtype=np.float32 + ) + self.assertTrue(np.allclose(output[:, :3, :3], EXPECTED_SLICE, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_roberta_prelayernorm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_roberta_prelayernorm.py new file mode 100644 index 0000000000000000000000000000000000000000..c975718778daf477bf6ffc11fde672f48476ddb3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_roberta_prelayernorm.py @@ -0,0 +1,565 @@ +# coding=utf-8 +# Copyright 2022 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 unittest + +from transformers import RobertaPreLayerNormConfig, is_torch_available +from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + RobertaPreLayerNormForCausalLM, + RobertaPreLayerNormForMaskedLM, + RobertaPreLayerNormForMultipleChoice, + RobertaPreLayerNormForQuestionAnswering, + RobertaPreLayerNormForSequenceClassification, + RobertaPreLayerNormForTokenClassification, + RobertaPreLayerNormModel, + ) + from transformers.models.roberta_prelayernorm.modeling_roberta_prelayernorm import ( + ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, + RobertaPreLayerNormEmbeddings, + create_position_ids_from_input_ids, + ) + + +# Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTester with Roberta->RobertaPreLayerNorm +class RobertaPreLayerNormModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def get_config(self): + return RobertaPreLayerNormConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + ) + + def get_pipeline_config(self): + config = self.get_config() + config.vocab_size = 300 + return config + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RobertaPreLayerNormModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = RobertaPreLayerNormModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = RobertaPreLayerNormForCausalLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = RobertaPreLayerNormForCausalLM(config=config).to(torch_device).eval() + + # make sure that ids don't start with pad token + mask = input_ids.ne(config.pad_token_id).long() + input_ids = input_ids * mask + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + + # make sure that ids don't start with pad token + mask = next_tokens.ne(config.pad_token_id).long() + next_tokens = next_tokens * mask + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # 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)) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RobertaPreLayerNormForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = RobertaPreLayerNormForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = RobertaPreLayerNormForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RobertaPreLayerNormForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class RobertaPreLayerNormModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + RobertaPreLayerNormForCausalLM, + RobertaPreLayerNormForMaskedLM, + RobertaPreLayerNormModel, + RobertaPreLayerNormForSequenceClassification, + RobertaPreLayerNormForTokenClassification, + RobertaPreLayerNormForMultipleChoice, + RobertaPreLayerNormForQuestionAnswering, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (RobertaPreLayerNormForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": RobertaPreLayerNormModel, + "fill-mask": RobertaPreLayerNormForMaskedLM, + "question-answering": RobertaPreLayerNormForQuestionAnswering, + "text-classification": RobertaPreLayerNormForSequenceClassification, + "text-generation": RobertaPreLayerNormForCausalLM, + "token-classification": RobertaPreLayerNormForTokenClassification, + "zero-shot": RobertaPreLayerNormForSequenceClassification, + } + if is_torch_available() + else {} + ) + fx_compatible = False + model_split_percents = [0.5, 0.8, 0.9] + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.setUp with Roberta->RobertaPreLayerNorm + def setUp(self): + self.model_tester = RobertaPreLayerNormModelTester(self) + self.config_tester = ConfigTester(self, config_class=RobertaPreLayerNormConfig, hidden_size=37) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_config + def test_config(self): + self.config_tester.run_common_tests() + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model_various_embeddings + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model_as_decoder + def test_model_as_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model_as_decoder_with_default_input_mask + def test_model_as_decoder_with_default_input_mask(self): + # This regression test was failing with PyTorch < 1.3 + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = self.model_tester.prepare_config_and_inputs_for_decoder() + + input_mask = None + + self.model_tester.create_and_check_model_as_decoder( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_causal_lm + def test_for_causal_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_for_causal_lm(*config_and_inputs) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_decoder_model_past_with_large_inputs + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_masked_lm + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_token_classification + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_multiple_choice + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_for_question_answering + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + @slow + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_model_from_pretrained with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm + def test_model_from_pretrained(self): + for model_name in ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = RobertaPreLayerNormModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_create_position_ids_respects_padding_index with Roberta->RobertaPreLayerNorm + def test_create_position_ids_respects_padding_index(self): + """Ensure that the default position ids only assign a sequential . This is a regression + test for https://github.com/huggingface/transformers/issues/1761 + + The position ids should be masked with the embedding object's padding index. Therefore, the + first available non-padding position index is RobertaPreLayerNormEmbeddings.padding_idx + 1 + """ + config = self.model_tester.prepare_config_and_inputs()[0] + model = RobertaPreLayerNormEmbeddings(config=config) + + input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]]) + expected_positions = torch.as_tensor( + [[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]] + ) + + position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx) + self.assertEqual(position_ids.shape, expected_positions.shape) + self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) + + # Copied from tests.models.roberta.test_modeling_roberta.RobertaModelTest.test_create_position_ids_from_inputs_embeds with Roberta->RobertaPreLayerNorm + def test_create_position_ids_from_inputs_embeds(self): + """Ensure that the default position ids only assign a sequential . This is a regression + test for https://github.com/huggingface/transformers/issues/1761 + + The position ids should be masked with the embedding object's padding index. Therefore, the + first available non-padding position index is RobertaPreLayerNormEmbeddings.padding_idx + 1 + """ + config = self.model_tester.prepare_config_and_inputs()[0] + embeddings = RobertaPreLayerNormEmbeddings(config=config) + + inputs_embeds = torch.empty(2, 4, 30) + expected_single_positions = [ + 0 + embeddings.padding_idx + 1, + 1 + embeddings.padding_idx + 1, + 2 + embeddings.padding_idx + 1, + 3 + embeddings.padding_idx + 1, + ] + expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions]) + position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds) + self.assertEqual(position_ids.shape, expected_positions.shape) + self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) + + +@require_torch +class RobertaPreLayerNormModelIntegrationTest(TestCasePlus): + @slow + def test_inference_masked_lm(self): + model = RobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40") + + input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + with torch.no_grad(): + output = model(input_ids)[0] + expected_shape = torch.Size((1, 11, 50265)) + self.assertEqual(output.shape, expected_shape) + # compare the actual values for a slice. + EXPECTED_SLICE = torch.tensor( + [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]] + ) + + self.assertTrue(torch.allclose(output[:, :3, :3], EXPECTED_SLICE, atol=1e-4)) + + @slow + def test_inference_no_head(self): + model = RobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40") + + input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + with torch.no_grad(): + output = model(input_ids)[0] + # compare the actual values for a slice. + EXPECTED_SLICE = torch.tensor( + [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]] + ) + + self.assertTrue(torch.allclose(output[:, :3, :3], EXPECTED_SLICE, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_tf_roberta_prelayernorm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_tf_roberta_prelayernorm.py new file mode 100644 index 0000000000000000000000000000000000000000..384fa2e9e4001329be6d2e7673fe78ae04e6fa55 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roberta_prelayernorm/test_modeling_tf_roberta_prelayernorm.py @@ -0,0 +1,693 @@ +# coding=utf-8 +# Copyright 2022 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. + + +from __future__ import annotations + +import unittest + +from transformers import RobertaPreLayerNormConfig, is_tf_available +from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import numpy + import tensorflow as tf + + from transformers.models.roberta_prelayernorm.modeling_tf_roberta_prelayernorm import ( + TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, + TFRobertaPreLayerNormForCausalLM, + TFRobertaPreLayerNormForMaskedLM, + TFRobertaPreLayerNormForMultipleChoice, + TFRobertaPreLayerNormForQuestionAnswering, + TFRobertaPreLayerNormForSequenceClassification, + TFRobertaPreLayerNormForTokenClassification, + TFRobertaPreLayerNormModel, + ) + + +# Copied from tests.models.roberta.test_modeling_tf_roberta.TFRobertaModelTester with Roberta->RobertaPreLayerNorm +class TFRobertaPreLayerNormModelTester: + def __init__( + self, + parent, + ): + self.parent = parent + self.batch_size = 13 + self.seq_length = 7 + self.is_training = True + self.use_input_mask = True + self.use_token_type_ids = True + self.use_labels = True + self.vocab_size = 99 + self.hidden_size = 32 + self.num_hidden_layers = 2 + self.num_attention_heads = 4 + self.intermediate_size = 37 + self.hidden_act = "gelu" + self.hidden_dropout_prob = 0.1 + self.attention_probs_dropout_prob = 0.1 + self.max_position_embeddings = 512 + self.type_vocab_size = 16 + self.type_sequence_label_size = 2 + self.initializer_range = 0.02 + self.num_labels = 3 + self.num_choices = 4 + self.scope = None + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = RobertaPreLayerNormConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + ) + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRobertaPreLayerNormModel(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs) + + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_causal_lm_base_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.is_decoder = True + + model = TFRobertaPreLayerNormModel(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs) + + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRobertaPreLayerNormModel(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "encoder_hidden_states": encoder_hidden_states, + "encoder_attention_mask": encoder_attention_mask, + } + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states) + + # Also check the case where encoder outputs are not passed + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_causal_lm_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.is_decoder = True + + model = TFRobertaPreLayerNormForCausalLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + prediction_scores = model(inputs)["logits"] + self.parent.assertListEqual( + list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size] + ) + + def create_and_check_causal_lm_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRobertaPreLayerNormForCausalLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "encoder_hidden_states": encoder_hidden_states, + "encoder_attention_mask": encoder_attention_mask, + } + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states) + + prediction_scores = result["logits"] + self.parent.assertListEqual( + list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size] + ) + + def create_and_check_causal_lm_model_past( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRobertaPreLayerNormForCausalLM(config=config) + + # special to `RobertaPreLayerNormEmbeddings` in `RobertaPreLayerNorm`: + # - its `padding_idx` and its effect on `position_ids` + # (TFRobertaPreLayerNormEmbeddings.create_position_ids_from_input_ids) + # - `1` here is `TFRobertaPreLayerNormEmbeddings.padding_idx` + input_ids = tf.where(input_ids == 1, 2, input_ids) + + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + past_key_values = outputs.past_key_values + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and attn_mask + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + + output_from_no_past = model(next_input_ids, output_hidden_states=True).hidden_states[0] + output_from_past = model( + next_tokens, past_key_values=past_key_values, output_hidden_states=True + ).hidden_states[0] + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx] + output_from_past_slice = output_from_past[:, 0, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6) + + def create_and_check_causal_lm_model_past_with_attn_mask( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRobertaPreLayerNormForCausalLM(config=config) + + # special to `RobertaPreLayerNormEmbeddings` in `RobertaPreLayerNorm`: + # - its `padding_idx` and its effect on `position_ids` + # (TFRobertaPreLayerNormEmbeddings.create_position_ids_from_input_ids) + # - `1` here is `TFRobertaPreLayerNormEmbeddings.padding_idx` + # avoid `padding_idx` in the past + input_ids = tf.where(input_ids == 1, 2, input_ids) + + # create attention mask + half_seq_length = self.seq_length // 2 + attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32) + attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32) + attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1) + + # first forward pass + outputs = model(input_ids, attention_mask=attn_mask, use_cache=True) + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + past_key_values = outputs.past_key_values + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size) + vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change) + condition = tf.transpose( + tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size)) + ) + input_ids = tf.where(condition, random_other_next_tokens, input_ids) + # avoid `padding_idx` in the past + input_ids = tf.where(input_ids == 1, 2, input_ids) + + # append to next input_ids and + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + attn_mask = tf.concat( + [attn_mask, tf.ones((attn_mask.shape[0], 1), dtype=tf.int32)], + axis=1, + ) + + output_from_no_past = model( + next_input_ids, + attention_mask=attn_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, past_key_values=past_key_values, attention_mask=attn_mask, output_hidden_states=True + ).hidden_states[0] + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx] + output_from_past_slice = output_from_past[:, 0, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6) + + def create_and_check_causal_lm_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.is_decoder = True + + model = TFRobertaPreLayerNormForCausalLM(config=config) + + # special to `RobertaPreLayerNormEmbeddings` in `RobertaPreLayerNorm`: + # - its `padding_idx` and its effect on `position_ids` + # (TFRobertaPreLayerNormEmbeddings.create_position_ids_from_input_ids) + # - `1` here is `TFRobertaPreLayerNormEmbeddings.padding_idx` + # avoid `padding_idx` in the past + input_ids = tf.where(input_ids == 1, 2, input_ids) + + input_ids = input_ids[:1, :] + input_mask = input_mask[:1, :] + self.batch_size = 1 + + # first forward pass + outputs = model(input_ids, attention_mask=input_mask, use_cache=True) + past_key_values = outputs.past_key_values + + # create hypothetical 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 = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + ).hidden_states[0] + + self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1]) + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + + model = TFRobertaPreLayerNormForCausalLM(config=config) + + # special to `RobertaPreLayerNormEmbeddings` in `RobertaPreLayerNorm`: + # - its `padding_idx` and its effect on `position_ids` + # (TFRobertaPreLayerNormEmbeddings.create_position_ids_from_input_ids) + # - `1` here is `TFRobertaPreLayerNormEmbeddings.padding_idx` + # avoid `padding_idx` in the past + input_ids = tf.where(input_ids == 1, 2, input_ids) + + input_ids = input_ids[:1, :] + input_mask = input_mask[:1, :] + encoder_hidden_states = encoder_hidden_states[:1, :, :] + encoder_attention_mask = encoder_attention_mask[:1, :] + self.batch_size = 1 + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical 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 = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + ).hidden_states[0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + ).hidden_states[0] + + self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1]) + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRobertaPreLayerNormForMaskedLM(config=config) + result = model([input_ids, input_mask, token_type_ids]) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = TFRobertaPreLayerNormForTokenClassification(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRobertaPreLayerNormForQuestionAnswering(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = TFRobertaPreLayerNormForMultipleChoice(config=config) + multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1)) + multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1)) + multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1)) + inputs = { + "input_ids": multiple_choice_inputs_ids, + "attention_mask": multiple_choice_input_mask, + "token_type_ids": multiple_choice_token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_tf +# Copied from tests.models.roberta.test_modeling_tf_roberta.TFRobertaModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm +class TFRobertaPreLayerNormModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TFRobertaPreLayerNormModel, + TFRobertaPreLayerNormForCausalLM, + TFRobertaPreLayerNormForMaskedLM, + TFRobertaPreLayerNormForSequenceClassification, + TFRobertaPreLayerNormForTokenClassification, + TFRobertaPreLayerNormForQuestionAnswering, + ) + if is_tf_available() + else () + ) + pipeline_model_mapping = ( + { + "feature-extraction": TFRobertaPreLayerNormModel, + "fill-mask": TFRobertaPreLayerNormForMaskedLM, + "question-answering": TFRobertaPreLayerNormForQuestionAnswering, + "text-classification": TFRobertaPreLayerNormForSequenceClassification, + "text-generation": TFRobertaPreLayerNormForCausalLM, + "token-classification": TFRobertaPreLayerNormForTokenClassification, + "zero-shot": TFRobertaPreLayerNormForSequenceClassification, + } + if is_tf_available() + else {} + ) + test_head_masking = False + test_onnx = False + + def setUp(self): + self.model_tester = TFRobertaPreLayerNormModelTester(self) + self.config_tester = ConfigTester(self, config_class=RobertaPreLayerNormConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + """Test the base model""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_causal_lm_base_model(self): + """Test the base model of the causal LM model + + is_deocder=True, no cross_attention, no encoder outputs + """ + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_base_model(*config_and_inputs) + + def test_model_as_decoder(self): + """Test the base model as a decoder (of an encoder-decoder architecture) + + is_deocder=True + cross_attention + pass encoder outputs + """ + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_causal_lm(self): + """Test the causal LM model""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model(*config_and_inputs) + + def test_causal_lm_model_as_decoder(self): + """Test the causal LM model as a decoder""" + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_causal_lm_model_as_decoder(*config_and_inputs) + + def test_causal_lm_model_past(self): + """Test causal LM model with `past_key_values`""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past(*config_and_inputs) + + def test_causal_lm_model_past_with_attn_mask(self): + """Test the causal LM model with `past_key_values` and `attention_mask`""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past_with_attn_mask(*config_and_inputs) + + def test_causal_lm_model_past_with_large_inputs(self): + """Test the causal LM model with `past_key_values` and a longer decoder sequence length""" + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causal_lm_model_past_large_inputs(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + """Similar to `test_causal_lm_model_past_with_large_inputs` but with cross-attention""" + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFRobertaPreLayerNormModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_tf +@require_sentencepiece +@require_tokenizers +class TFRobertaPreLayerNormModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_masked_lm(self): + model = TFRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40") + + input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + output = model(input_ids)[0] + expected_shape = [1, 11, 50265] + self.assertEqual(list(output.numpy().shape), expected_shape) + # compare the actual values for a slice. + EXPECTED_SLICE = tf.constant( + [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]] + ) + self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), EXPECTED_SLICE.numpy(), atol=1e-4)) + + @slow + def test_inference_no_head(self): + model = TFRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40") + + input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + output = model(input_ids)[0] + # compare the actual values for a slice. + EXPECTED_SLICE = tf.constant( + [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]] + ) + self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), EXPECTED_SLICE.numpy(), atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_modeling_roc_bert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_modeling_roc_bert.py new file mode 100644 index 0000000000000000000000000000000000000000..d1caca6b6f9417c7cf79d78ed6477aad80210836 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_modeling_roc_bert.py @@ -0,0 +1,745 @@ +# coding=utf-8 +# Copyright 2022 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 RoCBert model. """ + +import unittest + +from transformers import RoCBertConfig, is_torch_available +from transformers.models.auto import get_values +from transformers.testing_utils import require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + MODEL_FOR_PRETRAINING_MAPPING, + RoCBertForCausalLM, + RoCBertForMaskedLM, + RoCBertForMultipleChoice, + RoCBertForPreTraining, + RoCBertForQuestionAnswering, + RoCBertForSequenceClassification, + RoCBertForTokenClassification, + RoCBertModel, + ) + from transformers.models.roc_bert.modeling_roc_bert import ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST + + +class RoCBertModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + pronunciation_vocab_size=99, + shape_vocab_size=99, + pronunciation_embed_dim=32, + shape_embed_dim=32, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + self.use_labels = use_labels + self.vocab_size = vocab_size + self.pronunciation_vocab_size = pronunciation_vocab_size + self.shape_vocab_size = shape_vocab_size + self.pronunciation_embed_dim = pronunciation_embed_dim + self.shape_embed_dim = shape_embed_dim + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + input_shape_ids = ids_tensor([self.batch_size, self.seq_length], self.shape_vocab_size) + input_pronunciation_ids = ids_tensor([self.batch_size, self.seq_length], self.pronunciation_vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return ( + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) + + def get_config(self): + return RoCBertConfig( + vocab_size=self.vocab_size, + shape_vocab_size=self.shape_vocab_size, + pronunciation_vocab_size=self.pronunciation_vocab_size, + shape_embed_dim=self.shape_embed_dim, + pronunciation_embed_dim=self.pronunciation_embed_dim, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + model = RoCBertModel(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + ) + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + token_type_ids=token_type_ids, + ) + result = model(input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = RoCBertModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + ) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = RoCBertForCausalLM(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=token_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_masked_lm( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + model = RoCBertForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=token_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = RoCBertForCausalLM(config=config) + model.to(torch_device) + model.eval() + + # first forward pass + outputs = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_shape_tokens = ids_tensor((self.batch_size, 3), config.shape_vocab_size) + next_pronunciation_tokens = ids_tensor((self.batch_size, 3), config.pronunciation_vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_input_shape_ids = torch.cat([input_shape_ids, next_shape_tokens], dim=-1) + next_input_pronunciation_ids = torch.cat([input_pronunciation_ids, next_pronunciation_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + input_shape_ids=next_input_shape_ids, + input_pronunciation_ids=next_input_pronunciation_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + input_shape_ids=next_shape_tokens, + input_pronunciation_ids=next_pronunciation_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # 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)) + + def create_and_check_for_question_answering( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + model = RoCBertForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_for_sequence_classification( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.num_labels = self.num_labels + model = RoCBertForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=sequence_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_token_classification( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.num_labels = self.num_labels + model = RoCBertForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + input_shape_ids=input_shape_ids, + input_pronunciation_ids=input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=token_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + config.num_choices = self.num_choices + model = RoCBertForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_inputs_shape_ids = input_shape_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_inputs_pronunciation_ids = ( + input_pronunciation_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + ) + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + input_shape_ids=multiple_choice_inputs_shape_ids, + input_pronunciation_ids=multiple_choice_inputs_pronunciation_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = { + "input_ids": input_ids, + "input_shape_ids": input_shape_ids, + "input_pronunciation_ids": input_pronunciation_ids, + "token_type_ids": token_type_ids, + "attention_mask": input_mask, + } + return config, inputs_dict + + def create_and_check_for_pretraining( + self, + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + model = RoCBertForPreTraining(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + input_shape_ids, + input_pronunciation_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + attack_input_ids=input_ids, + attack_input_shape_ids=input_shape_ids, + attack_input_pronunciation_ids=input_pronunciation_ids, + attack_attention_mask=input_mask, + attack_token_type_ids=token_type_ids, + labels_input_ids=token_labels, + labels_input_shape_ids=input_shape_ids, + labels_input_pronunciation_ids=input_pronunciation_ids, + labels_attention_mask=input_mask, + labels_token_type_ids=token_type_ids, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + +@require_torch +class RoCBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + RoCBertModel, + RoCBertForMaskedLM, + RoCBertForCausalLM, + RoCBertForMultipleChoice, + RoCBertForQuestionAnswering, + RoCBertForSequenceClassification, + RoCBertForTokenClassification, + RoCBertForPreTraining, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (RoCBertForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": RoCBertModel, + "fill-mask": RoCBertForMaskedLM, + "question-answering": RoCBertForQuestionAnswering, + "text-classification": RoCBertForSequenceClassification, + "text-generation": RoCBertForCausalLM, + "token-classification": RoCBertForTokenClassification, + "zero-shot": RoCBertForSequenceClassification, + } + if is_torch_available() + else {} + ) + + # TODO: Fix the failed tests when this model gets more usage + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name in [ + "FillMaskPipelineTests", + "FeatureExtractionPipelineTests", + "TextClassificationPipelineTests", + "TokenClassificationPipelineTests", + ]: + # Get error: IndexError: index out of range in self. + # `word_shape_file` and `word_pronunciation_file` should be shrunk during tiny model creation, + # otherwise `IndexError` could occur in some embedding layers. Skip for now until this model has + # more usage. + return True + + return False + + # special case for ForPreTraining model + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) + + if return_labels: + if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING): + inputs_dict["labels_input_ids"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + inputs_dict["labels_input_shape_ids"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + inputs_dict["labels_input_pronunciation_ids"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + inputs_dict["attack_input_ids"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + inputs_dict["attack_input_shape_ids"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + inputs_dict["attack_input_pronunciation_ids"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + return inputs_dict + + def setUp(self): + self.model_tester = RoCBertModelTester(self) + self.config_tester = ConfigTester(self, config_class=RoCBertConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs_relative_pos_emb(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + config_and_inputs[0].position_embedding_type = "relative_key" + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_for_pretraining(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_pretraining(*config_and_inputs) + + def test_model_as_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_model_as_decoder_with_default_input_mask(self): + # This regression test was failing with PyTorch < 1.3 + ( + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = self.model_tester.prepare_config_and_inputs_for_decoder() + + input_mask = None + + self.model_tester.create_and_check_model_as_decoder( + config, + input_ids, + input_shape_ids, + input_pronunciation_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + @slow + def test_model_from_pretrained(self): + for model_name in ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = RoCBertModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_torch +class RoCBertModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_masked_lm(self): + model = RoCBertForMaskedLM.from_pretrained("weiweishi/roc-bert-base-zh") + + # input_text: ['[CLS]', 'b', 'a', '里', '系', '[MASK]', '国', '的', '首', '都', '[SEP]'] is the adversarial text + # of ['[CLS]', '巴', '黎', '是', '[MASK]', '国', '的', '首', '都', '[SEP]'], means + # "Paris is the [MASK] of France" in English + input_ids = torch.tensor([[101, 144, 143, 7027, 5143, 103, 1744, 4638, 7674, 6963, 102]]) + input_shape_ids = torch.tensor([[2, 20324, 23690, 8740, 706, 1, 10900, 23343, 20205, 5850, 2]]) + input_pronunciation_ids = torch.tensor([[2, 718, 397, 52, 61, 1, 168, 273, 180, 243, 2]]) + + output = model(input_ids, input_shape_ids, input_pronunciation_ids) + output_ids = torch.argmax(output.logits, dim=2) + + # convert to tokens is: ['[CLS]', '巴', '*', '黎', '是', '法', '国', '的', '首', '都', '[SEP]'] + expected_output = torch.tensor([[101, 2349, 115, 7944, 3221, 3791, 1744, 4638, 7674, 6963, 102]]) + + assert torch.allclose(output_ids, expected_output) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_tokenization_roc_bert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_tokenization_roc_bert.py new file mode 100644 index 0000000000000000000000000000000000000000..6a24514b3c2c2bdaa1c731fff0f05d888b9ff214 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roc_bert/test_tokenization_roc_bert.py @@ -0,0 +1,320 @@ +# coding=utf-8 +# Copyright 2022 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 transformers.models.roc_bert.tokenization_roc_bert import ( + VOCAB_FILES_NAMES, + RoCBertBasicTokenizer, + RoCBertTokenizer, + RoCBertWordpieceTokenizer, + _is_control, + _is_punctuation, + _is_whitespace, +) +from transformers.testing_utils import require_tokenizers, slow + +from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english + + +@require_tokenizers +class BertTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = RoCBertTokenizer + rust_tokenizer_class = None + test_rust_tokenizer = False + space_between_special_tokens = True + from_pretrained_filter = filter_non_english + + def setUp(self): + super().setUp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] + word_shape = {} + word_pronunciation = {} + for i, value in enumerate(vocab_tokens): + word_shape[value] = i + word_pronunciation[value] = i + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + self.word_shape_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["word_shape_file"]) + self.word_pronunciation_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["word_pronunciation_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + with open(self.word_shape_file, "w", encoding="utf-8") as word_shape_writer: + json.dump(word_shape, word_shape_writer, ensure_ascii=False) + with open(self.word_pronunciation_file, "w", encoding="utf-8") as word_pronunciation_writer: + json.dump(word_pronunciation, word_pronunciation_writer, ensure_ascii=False) + + def test_full_tokenizer(self): + tokenizer = self.tokenizer_class(self.vocab_file, self.word_shape_file, self.word_pronunciation_file) + + tokens = tokenizer.tokenize("你好[SEP]你是谁") + self.assertListEqual(tokens, ["你", "好", "[SEP]", "你", "是", "谁"]) + self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [5, 6, 2, 5, 7, 8]) + self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(tokens), [5, 6, 2, 5, 7, 8]) + self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(tokens), [5, 6, 2, 5, 7, 8]) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_chinese with BasicTokenizer->RoCBertBasicTokenizer + def test_chinese(self): + tokenizer = RoCBertBasicTokenizer() + + self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"), ["ah", "\u535A", "\u63A8", "zz"]) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_lower with BasicTokenizer->RoCBertBasicTokenizer + def test_basic_tokenizer_lower(self): + tokenizer = RoCBertBasicTokenizer(do_lower_case=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["hello", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_lower_strip_accents_false with BasicTokenizer->RoCBertBasicTokenizer + def test_basic_tokenizer_lower_strip_accents_false(self): + tokenizer = RoCBertBasicTokenizer(do_lower_case=True, strip_accents=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hällo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["h\u00E9llo"]) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_lower_strip_accents_true with BasicTokenizer->RoCBertBasicTokenizer + def test_basic_tokenizer_lower_strip_accents_true(self): + tokenizer = RoCBertBasicTokenizer(do_lower_case=True, strip_accents=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_lower_strip_accents_default with BasicTokenizer->RoCBertBasicTokenizer + def test_basic_tokenizer_lower_strip_accents_default(self): + tokenizer = RoCBertBasicTokenizer(do_lower_case=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_no_lower with BasicTokenizer->RoCBertBasicTokenizer + def test_basic_tokenizer_no_lower(self): + tokenizer = RoCBertBasicTokenizer(do_lower_case=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["HeLLo", "!", "how", "Are", "yoU", "?"] + ) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_no_lower_strip_accents_false with BasicTokenizer->RoCBertBasicTokenizer + def test_basic_tokenizer_no_lower_strip_accents_false(self): + tokenizer = RoCBertBasicTokenizer(do_lower_case=False, strip_accents=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HäLLo", "!", "how", "Are", "yoU", "?"] + ) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_no_lower_strip_accents_true with BasicTokenizer->RoCBertBasicTokenizer + def test_basic_tokenizer_no_lower_strip_accents_true(self): + tokenizer = RoCBertBasicTokenizer(do_lower_case=False, strip_accents=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HaLLo", "!", "how", "Are", "yoU", "?"] + ) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_basic_tokenizer_respects_never_split_tokens with BasicTokenizer->RoCBertBasicTokenizer + def test_basic_tokenizer_respects_never_split_tokens(self): + tokenizer = RoCBertBasicTokenizer(do_lower_case=False, never_split=["[UNK]"]) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]"), ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] + ) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_wordpiece_tokenizer with WordpieceTokenizer->RoCBertWordpieceTokenizer + def test_wordpiece_tokenizer(self): + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] + + vocab = {} + for i, token in enumerate(vocab_tokens): + vocab[token] = i + tokenizer = RoCBertWordpieceTokenizer(vocab=vocab, unk_token="[UNK]") + + self.assertListEqual(tokenizer.tokenize(""), []) + + self.assertListEqual(tokenizer.tokenize("unwanted running"), ["un", "##want", "##ed", "runn", "##ing"]) + + self.assertListEqual(tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"]) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_is_whitespace + def test_is_whitespace(self): + self.assertTrue(_is_whitespace(" ")) + self.assertTrue(_is_whitespace("\t")) + self.assertTrue(_is_whitespace("\r")) + self.assertTrue(_is_whitespace("\n")) + self.assertTrue(_is_whitespace("\u00A0")) + + self.assertFalse(_is_whitespace("A")) + self.assertFalse(_is_whitespace("-")) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_is_control + def test_is_control(self): + self.assertTrue(_is_control("\u0005")) + + self.assertFalse(_is_control("A")) + self.assertFalse(_is_control(" ")) + self.assertFalse(_is_control("\t")) + self.assertFalse(_is_control("\r")) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_is_punctuation + def test_is_punctuation(self): + self.assertTrue(_is_punctuation("-")) + self.assertTrue(_is_punctuation("$")) + self.assertTrue(_is_punctuation("`")) + self.assertTrue(_is_punctuation(".")) + + self.assertFalse(_is_punctuation("A")) + self.assertFalse(_is_punctuation(" ")) + + def test_clean_text(self): + tokenizer = self.get_tokenizer() + + # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 + self.assertListEqual([tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], [], ["[UNK]"]]) + + if self.test_rust_tokenizer: + rust_tokenizer = self.get_rust_tokenizer() + self.assertListEqual( + [rust_tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], [], ["[UNK]"]] + ) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_offsets_with_special_characters + def test_offsets_with_special_characters(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) + + sentence = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." + tokens = tokenizer_r.encode_plus( + sentence, + return_attention_mask=False, + return_token_type_ids=False, + return_offsets_mapping=True, + add_special_tokens=True, + ) + + do_lower_case = tokenizer_r.do_lower_case if hasattr(tokenizer_r, "do_lower_case") else False + expected_results = ( + [ + ((0, 0), tokenizer_r.cls_token), + ((0, 1), "A"), + ((1, 2), ","), + ((3, 5), "na"), + ((5, 6), "##ï"), + ((6, 8), "##ve"), + ((9, 15), tokenizer_r.mask_token), + ((16, 21), "Allen"), + ((21, 23), "##NL"), + ((23, 24), "##P"), + ((25, 33), "sentence"), + ((33, 34), "."), + ((0, 0), tokenizer_r.sep_token), + ] + if not do_lower_case + else [ + ((0, 0), tokenizer_r.cls_token), + ((0, 1), "a"), + ((1, 2), ","), + ((3, 8), "naive"), + ((9, 15), tokenizer_r.mask_token), + ((16, 21), "allen"), + ((21, 23), "##nl"), + ((23, 24), "##p"), + ((25, 33), "sentence"), + ((33, 34), "."), + ((0, 0), tokenizer_r.sep_token), + ] + ) + + self.assertEqual( + [e[1] for e in expected_results], tokenizer_r.convert_ids_to_tokens(tokens["input_ids"]) + ) + self.assertEqual([e[0] for e in expected_results], tokens["offset_mapping"]) + + # Copied from tests.models.bert.test_tokenization_bert.BertTokenizationTest.test_change_tokenize_chinese_chars + def test_change_tokenize_chinese_chars(self): + list_of_commun_chinese_char = ["的", "人", "有"] + text_with_chinese_char = "".join(list_of_commun_chinese_char) + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + kwargs["tokenize_chinese_chars"] = True + tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs) + tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + ids_without_spe_char_p = tokenizer_p.encode(text_with_chinese_char, add_special_tokens=False) + ids_without_spe_char_r = tokenizer_r.encode(text_with_chinese_char, add_special_tokens=False) + + tokens_without_spe_char_r = tokenizer_r.convert_ids_to_tokens(ids_without_spe_char_r) + tokens_without_spe_char_p = tokenizer_p.convert_ids_to_tokens(ids_without_spe_char_p) + + # it is expected that each Chinese character is not preceded by "##" + self.assertListEqual(tokens_without_spe_char_p, list_of_commun_chinese_char) + self.assertListEqual(tokens_without_spe_char_r, list_of_commun_chinese_char) + + kwargs["tokenize_chinese_chars"] = False + tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + ids_without_spe_char_r = tokenizer_r.encode(text_with_chinese_char, add_special_tokens=False) + ids_without_spe_char_p = tokenizer_p.encode(text_with_chinese_char, add_special_tokens=False) + + tokens_without_spe_char_r = tokenizer_r.convert_ids_to_tokens(ids_without_spe_char_r) + tokens_without_spe_char_p = tokenizer_p.convert_ids_to_tokens(ids_without_spe_char_p) + + # it is expected that only the first Chinese character is not preceded by "##". + expected_tokens = [ + f"##{token}" if idx != 0 else token for idx, token in enumerate(list_of_commun_chinese_char) + ] + self.assertListEqual(tokens_without_spe_char_p, expected_tokens) + self.assertListEqual(tokens_without_spe_char_r, expected_tokens) + + @slow + def test_sequence_builders(self): + tokenizer = self.tokenizer_class(self.vocab_file, self.word_shape_file, self.word_pronunciation_file) + + text = tokenizer.encode("你好", add_special_tokens=False) + text_2 = tokenizer.encode("你是谁", add_special_tokens=False) + + encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_sentence == [1] + text + [2] + assert encoded_pair == [1] + text + [2] + text_2 + [2] + + def test_prepare_for_model(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + string_sequence = "你好,你是谁" + tokens = tokenizer.tokenize(string_sequence) + tokens_ids = tokenizer.convert_tokens_to_ids(tokens) + tokens_shape_ids = tokenizer.convert_tokens_to_shape_ids(tokens) + tokens_proun_ids = tokenizer.convert_tokens_to_pronunciation_ids(tokens) + prepared_input_dict = tokenizer.prepare_for_model( + tokens_ids, tokens_shape_ids, tokens_proun_ids, add_special_tokens=True + ) + + input_dict = tokenizer.encode_plus(string_sequence, add_special_tokens=True) + + self.assertEqual(input_dict, prepared_input_dict) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_flax_roformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_flax_roformer.py new file mode 100644 index 0000000000000000000000000000000000000000..8364e121b42a308329c785ba7a8770d9e89ca830 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_flax_roformer.py @@ -0,0 +1,163 @@ +# Copyright 2021 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 unittest + +import numpy as np + +from transformers import RoFormerConfig, is_flax_available +from transformers.testing_utils import require_flax, slow + +from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask + + +if is_flax_available(): + import jax.numpy as jnp + + from transformers.models.roformer.modeling_flax_roformer import ( + FlaxRoFormerForMaskedLM, + FlaxRoFormerForMultipleChoice, + FlaxRoFormerForQuestionAnswering, + FlaxRoFormerForSequenceClassification, + FlaxRoFormerForTokenClassification, + FlaxRoFormerModel, + ) + + +class FlaxRoFormerModelTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_attention_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_choices=4, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_choices = num_choices + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + config = RoFormerConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + return config, input_ids, token_type_ids, attention_mask + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, token_type_ids, attention_mask = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_flax +class FlaxRoFormerModelTest(FlaxModelTesterMixin, unittest.TestCase): + test_head_masking = True + + all_model_classes = ( + ( + FlaxRoFormerModel, + FlaxRoFormerForMaskedLM, + FlaxRoFormerForSequenceClassification, + FlaxRoFormerForTokenClassification, + FlaxRoFormerForMultipleChoice, + FlaxRoFormerForQuestionAnswering, + ) + if is_flax_available() + else () + ) + + def setUp(self): + self.model_tester = FlaxRoFormerModelTester(self) + + @slow + def test_model_from_pretrained(self): + for model_class_name in self.all_model_classes: + model = model_class_name.from_pretrained("junnyu/roformer_chinese_small", from_pt=True) + outputs = model(np.ones((1, 1))) + self.assertIsNotNone(outputs) + + +@require_flax +class FlaxRoFormerModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_masked_lm(self): + model = FlaxRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base") + input_ids = jnp.array([[0, 1, 2, 3, 4, 5]]) + output = model(input_ids)[0] + + vocab_size = 50000 + + expected_shape = (1, 6, vocab_size) + self.assertEqual(output.shape, expected_shape) + + expected_slice = jnp.array( + [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] + ) + + self.assertTrue(jnp.allclose(output[:, :3, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_roformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_roformer.py new file mode 100644 index 0000000000000000000000000000000000000000..6c130ae1746c035f47ad5b130a206c74c2c519d7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_roformer.py @@ -0,0 +1,611 @@ +# coding=utf-8 +# 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 RoFormer model. """ + + +import unittest + +from transformers import RoFormerConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + RoFormerForCausalLM, + RoFormerForMaskedLM, + RoFormerForMultipleChoice, + RoFormerForQuestionAnswering, + RoFormerForSequenceClassification, + RoFormerForTokenClassification, + RoFormerModel, + ) + from transformers.models.roformer.modeling_roformer import ( + ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, + RoFormerSelfAttention, + RoFormerSinusoidalPositionalEmbedding, + ) + + +class RoFormerModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def get_config(self): + return RoFormerConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RoFormerModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = RoFormerModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = RoFormerForCausalLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_generate_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ): + model = RoFormerForCausalLM(config=config).to(torch_device).eval() + torch.manual_seed(0) + output_without_past_cache = model.generate( + input_ids[:1], num_beams=2, max_length=15, do_sample=True, use_cache=False + ) + torch.manual_seed(0) + output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=15, do_sample=True) + self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache)) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RoFormerForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = RoFormerForCausalLM(config=config) + model.to(torch_device) + model.eval() + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # 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)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = RoFormerForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_for_sequence_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = RoFormerForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = RoFormerForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = RoFormerForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class RoFormerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + RoFormerModel, + RoFormerForMaskedLM, + RoFormerForCausalLM, + RoFormerForMultipleChoice, + RoFormerForQuestionAnswering, + RoFormerForSequenceClassification, + RoFormerForTokenClassification, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (RoFormerForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": RoFormerModel, + "fill-mask": RoFormerForMaskedLM, + "question-answering": RoFormerForQuestionAnswering, + "text-classification": RoFormerForSequenceClassification, + "text-generation": RoFormerForCausalLM, + "token-classification": RoFormerForTokenClassification, + "zero-shot": RoFormerForSequenceClassification, + } + if is_torch_available() + else {} + ) + + def setUp(self): + self.model_tester = RoFormerModelTester(self) + self.config_tester = ConfigTester(self, config_class=RoFormerConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_generate_causal_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_generate_causal_lm(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_model_as_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_model_as_decoder_with_default_input_mask(self): + # This regression test was failing with PyTorch < 1.3 + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = self.model_tester.prepare_config_and_inputs_for_decoder() + + input_mask = None + + self.model_tester.create_and_check_model_as_decoder( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + @slow + def test_model_from_pretrained(self): + for model_name in ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = RoFormerModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + +@require_torch +class RoFormerModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_masked_lm(self): + model = RoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base") + input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) + with torch.no_grad(): + output = model(input_ids)[0] + + # TODO Replace vocab size + vocab_size = 50000 + + expected_shape = torch.Size((1, 6, vocab_size)) + self.assertEqual(output.shape, expected_shape) + + # TODO Replace values below with what was printed above. + expected_slice = torch.tensor( + [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] + ) + + self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4)) + + +@require_torch +class RoFormerSinusoidalPositionalEmbeddingTest(unittest.TestCase): + tolerance = 1e-4 + + def test_basic(self): + input_ids = torch.tensor([[4, 10]], dtype=torch.long, device=torch_device) + emb1 = RoFormerSinusoidalPositionalEmbedding(num_positions=6, embedding_dim=6).to(torch_device) + emb = emb1(input_ids.shape) + desired_weights = torch.tensor( + [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] + ).to(torch_device) + self.assertTrue( + torch.allclose(emb, desired_weights, atol=self.tolerance), + msg=f"\nexp:\n{desired_weights}\ngot:\n{emb[0]}\n", + ) + + def test_positional_emb_weights_against_roformer(self): + desired_weights = torch.tensor( + [ + [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], + [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], + ] + ).to(torch_device) + emb1 = RoFormerSinusoidalPositionalEmbedding(num_positions=512, embedding_dim=512).to(torch_device) + weights = emb1.weight.data[:3, :5].to(torch_device) + + self.assertTrue( + torch.allclose(weights, desired_weights, atol=self.tolerance), + msg=f"\nexp:\n{desired_weights}\ngot:\n{weights}\n", + ) + + +@require_torch +class RoFormerSelfAttentionRotaryPositionEmbeddingTest(unittest.TestCase): + tolerance = 1e-4 + + def test_apply_rotary_position_embeddings(self): + # 2,12,16,64 + query_layer = ( + torch.arange(2 * 12 * 16 * 64, dtype=torch.float, device=torch_device).reshape(2, 12, 16, 64) / 100 + ).to(torch_device) + key_layer = ( + -torch.arange(2 * 12 * 16 * 64, dtype=torch.float, device=torch_device).reshape(2, 12, 16, 64) / 100 + ).to(torch_device) + embed_positions = RoFormerSinusoidalPositionalEmbedding(num_positions=32, embedding_dim=64).to(torch_device) + sinusoidal_pos = embed_positions([2, 16, 768])[None, None, :, :] + + query_layer, key_layer = RoFormerSelfAttention.apply_rotary_position_embeddings( + sinusoidal_pos, query_layer, key_layer + ) + + desired_query_layer = torch.tensor( + [ + [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], + [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], + [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], + [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], + [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], + [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], + ] + ).to(torch_device) + desired_key_layer = torch.tensor( + [ + [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], + [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], + [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], + [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], + [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], + [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], + ] + ).to(torch_device) + + self.assertTrue( + torch.allclose(query_layer[0, 0, :6, :8], desired_query_layer, atol=self.tolerance), + msg=f"\nexp:\n{desired_query_layer}\ngot:\n{query_layer}\n", + ) + self.assertTrue( + torch.allclose(key_layer[0, 0, :6, :8], desired_key_layer, atol=self.tolerance), + msg=f"\nexp:\n{desired_key_layer}\ngot:\n{key_layer}\n", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_tf_roformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_tf_roformer.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e795b6dd9c620601372ba64dd8660fb574f13d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_modeling_tf_roformer.py @@ -0,0 +1,424 @@ +# coding=utf-8 +# 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. + + +from __future__ import annotations + +import unittest + +from transformers import RoFormerConfig, is_tf_available +from transformers.testing_utils import require_tf, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import ( + TFRoFormerForCausalLM, + TFRoFormerForMaskedLM, + TFRoFormerForMultipleChoice, + TFRoFormerForQuestionAnswering, + TFRoFormerForSequenceClassification, + TFRoFormerForTokenClassification, + TFRoFormerModel, + ) + from transformers.models.roformer.modeling_tf_roformer import ( + TFRoFormerSelfAttention, + TFRoFormerSinusoidalPositionalEmbedding, + ) + + +class TFRoFormerModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = 13 + self.seq_length = 7 + self.is_training = True + self.use_input_mask = True + self.use_token_type_ids = True + self.use_labels = True + self.vocab_size = 99 + self.hidden_size = 32 + self.num_hidden_layers = 2 + self.num_attention_heads = 4 + self.intermediate_size = 37 + self.hidden_act = "gelu" + self.hidden_dropout_prob = 0.1 + self.attention_probs_dropout_prob = 0.1 + self.max_position_embeddings = 512 + self.type_vocab_size = 16 + self.type_sequence_label_size = 2 + self.initializer_range = 0.02 + self.num_labels = 3 + self.num_choices = 4 + self.scope = None + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = RoFormerConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + return_dict=True, + ) + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRoFormerModel(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + + inputs = [input_ids, input_mask] + result = model(inputs) + + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_lm_head( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.is_decoder = True + model = TFRoFormerForCausalLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + prediction_scores = model(inputs)["logits"] + self.parent.assertListEqual( + list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size] + ) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRoFormerForMaskedLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_sequence_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = TFRoFormerForSequenceClassification(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = TFRoFormerForMultipleChoice(config=config) + multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1)) + multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1)) + multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1)) + inputs = { + "input_ids": multiple_choice_inputs_ids, + "attention_mask": multiple_choice_input_mask, + "token_type_ids": multiple_choice_token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = TFRoFormerForTokenClassification(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = TFRoFormerForQuestionAnswering(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + + result = model(inputs) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_tf +class TFRoFormerModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TFRoFormerModel, + TFRoFormerForCausalLM, + TFRoFormerForMaskedLM, + TFRoFormerForQuestionAnswering, + TFRoFormerForSequenceClassification, + TFRoFormerForTokenClassification, + TFRoFormerForMultipleChoice, + ) + if is_tf_available() + else () + ) + pipeline_model_mapping = ( + { + "feature-extraction": TFRoFormerModel, + "fill-mask": TFRoFormerForMaskedLM, + "question-answering": TFRoFormerForQuestionAnswering, + "text-classification": TFRoFormerForSequenceClassification, + "text-generation": TFRoFormerForCausalLM, + "token-classification": TFRoFormerForTokenClassification, + "zero-shot": TFRoFormerForSequenceClassification, + } + if is_tf_available() + else {} + ) + + test_head_masking = False + test_onnx = False + + # TODO: add `prepare_inputs_for_generation` for `TFRoFormerForCausalLM` + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "TextGenerationPipelineTests": + return True + + return False + + def setUp(self): + self.model_tester = TFRoFormerModelTester(self) + self.config_tester = ConfigTester(self, config_class=RoFormerConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_causal_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_lm_head(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + model = TFRoFormerModel.from_pretrained("junnyu/roformer_chinese_base") + self.assertIsNotNone(model) + + +@require_tf +class TFRoFormerModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_masked_lm(self): + model = TFRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base") + input_ids = tf.constant([[0, 1, 2, 3, 4, 5]]) + output = model(input_ids)[0] + + # TODO Replace vocab size + vocab_size = 50000 + + expected_shape = [1, 6, vocab_size] + self.assertEqual(output.shape, expected_shape) + + print(output[:, :3, :3]) + + # TODO Replace values below with what was printed above. + expected_slice = tf.constant( + [ + [ + [-0.12053341, -1.0264901, 0.29221946], + [-1.5133783, 0.197433, 0.15190607], + [-5.0135403, -3.900256, -0.84038764], + ] + ] + ) + tf.debugging.assert_near(output[:, :3, :3], expected_slice, atol=1e-4) + + +@require_tf +class TFRoFormerSinusoidalPositionalEmbeddingTest(unittest.TestCase): + tolerance = 1e-4 + + def test_basic(self): + input_ids = tf.constant([[4, 10]]) + emb1 = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6, embedding_dim=6) + + emb = emb1(input_ids.shape) + desired_weights = tf.constant( + [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] + ) + + tf.debugging.assert_near(emb, desired_weights, atol=self.tolerance) + + def test_positional_emb_weights_against_roformer(self): + desired_weights = tf.constant( + [ + [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], + [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], + ] + ) + emb1 = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512, embedding_dim=512) + emb1([2, 16, 512]) + weights = emb1.weight[:3, :5] + + tf.debugging.assert_near(weights, desired_weights, atol=self.tolerance) + + +@require_tf +class TFRoFormerSelfAttentionRotaryPositionEmbeddingTest(unittest.TestCase): + tolerance = 1e-4 + + def test_apply_rotary_position_embeddings(self): + # 2,12,16,64 + query_layer = tf.reshape(tf.range(2 * 12 * 16 * 64, dtype=tf.float32), shape=(2, 12, 16, 64)) / 100 + + key_layer = -tf.reshape(tf.range(2 * 12 * 16 * 64, dtype=tf.float32), shape=(2, 12, 16, 64)) / 100 + + embed_positions = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32, embedding_dim=64) + sinusoidal_pos = embed_positions([2, 16, 768])[None, None, :, :] + + query_layer, key_layer = TFRoFormerSelfAttention.apply_rotary_position_embeddings( + sinusoidal_pos, query_layer, key_layer + ) + + desired_query_layer = tf.constant( + [ + [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], + [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], + [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], + [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], + [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], + [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], + ] + ) + desired_key_layer = tf.constant( + [ + [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], + [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], + [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], + [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], + [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], + [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], + ] + ) + + tf.debugging.assert_near(query_layer[0, 0, :6, :8], desired_query_layer, atol=self.tolerance) + tf.debugging.assert_near(key_layer[0, 0, :6, :8], desired_key_layer, atol=self.tolerance) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_tokenization_roformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_tokenization_roformer.py new file mode 100644 index 0000000000000000000000000000000000000000..2d674100f02bfc0c89a996912f2349dc741a56e4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/roformer/test_tokenization_roformer.py @@ -0,0 +1,76 @@ +# coding=utf-8 +# Copyright 2021 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 unittest + +from transformers import RoFormerTokenizer, RoFormerTokenizerFast +from transformers.testing_utils import require_rjieba, require_tokenizers + +from ...test_tokenization_common import TokenizerTesterMixin + + +@require_rjieba +@require_tokenizers +class RoFormerTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = RoFormerTokenizer + rust_tokenizer_class = RoFormerTokenizerFast + space_between_special_tokens = True + test_rust_tokenizer = True + + def setUp(self): + super().setUp() + + def get_tokenizer(self, **kwargs): + return self.tokenizer_class.from_pretrained("junnyu/roformer_chinese_base", **kwargs) + + def get_rust_tokenizer(self, **kwargs): + return self.rust_tokenizer_class.from_pretrained("junnyu/roformer_chinese_base", **kwargs) + + def get_chinese_input_output_texts(self): + input_text = "永和服装饰品有限公司,今天天气非常好" + output_text = "永和 服装 饰品 有限公司 , 今 天 天 气 非常 好" + return input_text, output_text + + def test_tokenizer(self): + tokenizer = self.get_tokenizer() + input_text, output_text = self.get_chinese_input_output_texts() + tokens = tokenizer.tokenize(input_text) + + self.assertListEqual(tokens, output_text.split()) + + input_tokens = tokens + [tokenizer.unk_token] + exp_tokens = [22943, 21332, 34431, 45904, 117, 306, 1231, 1231, 2653, 33994, 1266, 100] + self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), exp_tokens) + + def test_rust_tokenizer(self): + tokenizer = self.get_rust_tokenizer() + input_text, output_text = self.get_chinese_input_output_texts() + tokens = tokenizer.tokenize(input_text) + self.assertListEqual(tokens, output_text.split()) + input_tokens = tokens + [tokenizer.unk_token] + exp_tokens = [22943, 21332, 34431, 45904, 117, 306, 1231, 1231, 2653, 33994, 1266, 100] + self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), exp_tokens) + + # can't train new_tokenizer via Tokenizers lib + def test_training_new_tokenizer(self): + pass + + # can't train new_tokenizer via Tokenizers lib + def test_training_new_tokenizer_with_special_tokens_change(self): + pass + + # can't serialise custom PreTokenizer + def test_save_slow_from_fast_and_reload_fast(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rwkv/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rwkv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rwkv/test_modeling_rwkv.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rwkv/test_modeling_rwkv.py new file mode 100644 index 0000000000000000000000000000000000000000..4ca5cfdf9e130b22000456de932709c4ed5e7b90 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/rwkv/test_modeling_rwkv.py @@ -0,0 +1,455 @@ +# coding=utf-8 +# Copyright 2023 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 unittest +from unittest.util import safe_repr + +from transformers import AutoTokenizer, RwkvConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + RWKV_PRETRAINED_MODEL_ARCHIVE_LIST, + RwkvForCausalLM, + RwkvModel, + ) + from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_0 +else: + is_torch_greater_or_equal_than_2_0 = False + + +class RwkvModelTester: + def __init__( + self, + parent, + batch_size=14, + seq_length=7, + is_training=True, + use_token_type_ids=False, + use_input_mask=True, + use_labels=True, + use_mc_token_ids=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_token_type_ids = use_token_type_ids + self.use_input_mask = use_input_mask + self.use_labels = use_labels + self.use_mc_token_ids = use_mc_token_ids + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + self.bos_token_id = vocab_size - 1 + self.eos_token_id = vocab_size - 1 + self.pad_token_id = vocab_size - 1 + + def get_large_model_config(self): + return RwkvConfig.from_pretrained("sgugger/rwkv-4-pile-7b") + + def prepare_config_and_inputs( + self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False + ): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + mc_token_ids = None + if self.use_mc_token_ids: + mc_token_ids = ids_tensor([self.batch_size, self.num_choices], self.seq_length) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config( + gradient_checkpointing=gradient_checkpointing, + scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx, + reorder_and_upcast_attn=reorder_and_upcast_attn, + ) + + return ( + config, + input_ids, + input_mask, + None, + token_type_ids, + mc_token_ids, + sequence_labels, + token_labels, + choice_labels, + ) + + def get_config( + self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False + ): + return RwkvConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + intermediate_size=self.intermediate_size, + activation_function=self.hidden_act, + resid_pdrop=self.hidden_dropout_prob, + attn_pdrop=self.attention_probs_dropout_prob, + n_positions=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + use_cache=True, + bos_token_id=self.bos_token_id, + eos_token_id=self.eos_token_id, + pad_token_id=self.pad_token_id, + gradient_checkpointing=gradient_checkpointing, + scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx, + reorder_and_upcast_attn=reorder_and_upcast_attn, + ) + + def get_pipeline_config(self): + config = self.get_config() + config.vocab_size = 300 + return config + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + input_mask, + head_mask, + token_type_ids, + mc_token_ids, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + input_mask, + head_mask, + token_type_ids, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_rwkv_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args): + config.output_hidden_states = True + model = RwkvModel(config=config) + model.to(torch_device) + model.eval() + + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(len(result.hidden_states), config.num_hidden_layers + 1) + + def create_and_check_causl_lm(self, config, input_ids, input_mask, head_mask, token_type_ids, *args): + model = RwkvForCausalLM(config) + model.to(torch_device) + model.eval() + + result = model(input_ids, labels=input_ids) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_state_equivalency(self, config, input_ids, input_mask, head_mask, token_type_ids, *args): + model = RwkvModel(config=config) + model.to(torch_device) + model.eval() + + outputs = model(input_ids) + output_whole = outputs.last_hidden_state + + outputs = model(input_ids[:, :2]) + output_one = outputs.last_hidden_state + + # Using the state computed on the first inputs, we will get the same output + outputs = model(input_ids[:, 2:], state=outputs.state) + output_two = outputs.last_hidden_state + + self.parent.assertTrue(torch.allclose(torch.cat([output_one, output_two], dim=1), output_whole, atol=1e-5)) + + def create_and_check_forward_and_backwards( + self, config, input_ids, input_mask, head_mask, token_type_ids, *args, gradient_checkpointing=False + ): + model = RwkvForCausalLM(config) + model.to(torch_device) + if gradient_checkpointing: + model.gradient_checkpointing_enable() + + result = model(input_ids, labels=input_ids) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + result.loss.backward() + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + + ( + config, + input_ids, + input_mask, + head_mask, + token_type_ids, + mc_token_ids, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + + inputs_dict = {"input_ids": input_ids} + + return config, inputs_dict + + +@unittest.skipIf( + not is_torch_greater_or_equal_than_2_0, reason="See https://github.com/huggingface/transformers/pull/24204" +) +@require_torch +class RwkvModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (RwkvModel, RwkvForCausalLM) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": RwkvModel, "text-generation": RwkvForCausalLM} if is_torch_available() else {} + ) + # all_generative_model_classes = (RwkvForCausalLM,) if is_torch_available() else () + fx_compatible = False + test_missing_keys = False + test_model_parallel = False + test_pruning = False + test_head_masking = False # Rwkv does not support head masking + + def setUp(self): + self.model_tester = RwkvModelTester(self) + self.config_tester = ConfigTester( + self, config_class=RwkvConfig, n_embd=37, common_properties=["hidden_size", "num_hidden_layers"] + ) + + def assertInterval(self, member, container, msg=None): + r""" + Simple utility function to check if a member is inside an interval. + """ + if isinstance(member, torch.Tensor): + max_value, min_value = member.max().item(), member.min().item() + elif isinstance(member, list) or isinstance(member, tuple): + max_value, min_value = max(member), min(member) + + if not isinstance(container, list): + raise TypeError("container should be a list or tuple") + elif len(container) != 2: + raise ValueError("container should have 2 elements") + + expected_min, expected_max = container + + is_inside_interval = (min_value >= expected_min) and (max_value <= expected_max) + + if not is_inside_interval: + standardMsg = "%s not found in %s" % (safe_repr(member), safe_repr(container)) + self.fail(self._formatMessage(msg, standardMsg)) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_rwkv_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_rwkv_model(*config_and_inputs) + + def test_rwkv_lm_head_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_causl_lm(*config_and_inputs) + + def test_state_equivalency(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_state_equivalency(*config_and_inputs) + + def test_initialization(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config=config) + for name, param in model.named_parameters(): + if "time_decay" in name: + if param.requires_grad: + self.assertTrue(param.data.max().item() == 3.0) + self.assertTrue(param.data.min().item() == -5.0) + elif "time_first" in name: + if param.requires_grad: + # check if it's a ones like + self.assertTrue(torch.allclose(param.data, torch.ones_like(param.data), atol=1e-5, rtol=1e-5)) + elif any(x in name for x in ["time_mix_key", "time_mix_receptance"]): + if param.requires_grad: + self.assertInterval( + param.data, + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + elif "time_mix_value" in name: + if param.requires_grad: + self.assertInterval( + param.data, + [0.0, 1.3], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def test_attention_outputs(self): + r""" + Overriding the test_attention_outputs test as the attention outputs of Rwkv are different from other models + it has a shape `batch_size, seq_len, hidden_size`. + """ + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = self._prepare_for_class(inputs_dict, model_class) + batch_size = inputs["input_ids"].shape[0] + with torch.no_grad(): + outputs = model(**inputs) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = self._prepare_for_class(inputs_dict, model_class) + batch_size = inputs["input_ids"].shape[0] + with torch.no_grad(): + outputs = model(**inputs) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [batch_size, seq_len, config.hidden_size], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = self._prepare_for_class(inputs_dict, model_class) + batch_size = inputs["input_ids"].shape[0] + with torch.no_grad(): + outputs = model(**inputs) + + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [batch_size, seq_len, config.hidden_size], + ) + + @slow + def test_model_from_pretrained(self): + for model_name in RWKV_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = RwkvModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@unittest.skipIf( + not is_torch_greater_or_equal_than_2_0, reason="See https://github.com/huggingface/transformers/pull/24204" +) +@slow +class RWKVIntegrationTests(unittest.TestCase): + def setUp(self): + self.model_id = "RWKV/rwkv-4-169m-pile" + self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) + + def test_simple_generate(self): + expected_output = "Hello my name is Jasmine and I am a newbie to the" + model = RwkvForCausalLM.from_pretrained(self.model_id).to(torch_device) + + input_ids = self.tokenizer("Hello my name is", return_tensors="pt").input_ids.to(torch_device) + output = model.generate(input_ids, max_new_tokens=10) + output_sentence = self.tokenizer.decode(output[0].tolist()) + + self.assertEqual(output_sentence, expected_output) + + def test_simple_generate_bf16(self): + expected_output = "Hello my name is Jasmine and I am a newbie to the" + + input_ids = self.tokenizer("Hello my name is", return_tensors="pt").input_ids.to(torch_device) + model = RwkvForCausalLM.from_pretrained(self.model_id, torch_dtype=torch.bfloat16).to(torch_device) + + output = model.generate(input_ids, max_new_tokens=10) + output_sentence = self.tokenizer.decode(output[0].tolist()) + + self.assertEqual(output_sentence, expected_output) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_modeling_sam.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_modeling_sam.py new file mode 100644 index 0000000000000000000000000000000000000000..3e63edb23a0c6d75de909edad336f546360878b8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_modeling_sam.py @@ -0,0 +1,763 @@ +# coding=utf-8 +# Copyright 2023 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 SAM model. """ + + +import gc +import unittest + +import requests + +from transformers import SamConfig, SamMaskDecoderConfig, SamPromptEncoderConfig, SamVisionConfig, pipeline +from transformers.testing_utils import backend_empty_cache, require_torch, slow, torch_device +from transformers.utils import is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import SamModel, SamProcessor + from transformers.models.sam.modeling_sam import SAM_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + +class SamPromptEncoderTester: + def __init__( + self, + hidden_size=32, + input_image_size=24, + patch_size=2, + mask_input_channels=4, + num_point_embeddings=4, + hidden_act="gelu", + ): + self.hidden_size = hidden_size + self.input_image_size = input_image_size + self.patch_size = patch_size + self.mask_input_channels = mask_input_channels + self.num_point_embeddings = num_point_embeddings + self.hidden_act = hidden_act + + def get_config(self): + return SamPromptEncoderConfig( + image_size=self.input_image_size, + patch_size=self.patch_size, + mask_input_channels=self.mask_input_channels, + hidden_size=self.hidden_size, + num_point_embeddings=self.num_point_embeddings, + hidden_act=self.hidden_act, + ) + + def prepare_config_and_inputs(self): + dummy_points = floats_tensor([self.batch_size, 3, 2]) + config = self.get_config() + + return config, dummy_points + + +class SamMaskDecoderTester: + def __init__( + self, + hidden_size=32, + hidden_act="relu", + mlp_dim=64, + num_hidden_layers=2, + num_attention_heads=4, + attention_downsample_rate=2, + num_multimask_outputs=3, + iou_head_depth=3, + iou_head_hidden_dim=32, + layer_norm_eps=1e-6, + ): + self.hidden_size = hidden_size + self.hidden_act = hidden_act + self.mlp_dim = mlp_dim + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.attention_downsample_rate = attention_downsample_rate + self.num_multimask_outputs = num_multimask_outputs + self.iou_head_depth = iou_head_depth + self.iou_head_hidden_dim = iou_head_hidden_dim + self.layer_norm_eps = layer_norm_eps + + def get_config(self): + return SamMaskDecoderConfig( + hidden_size=self.hidden_size, + hidden_act=self.hidden_act, + mlp_dim=self.mlp_dim, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + attention_downsample_rate=self.attention_downsample_rate, + num_multimask_outputs=self.num_multimask_outputs, + iou_head_depth=self.iou_head_depth, + iou_head_hidden_dim=self.iou_head_hidden_dim, + layer_norm_eps=self.layer_norm_eps, + ) + + def prepare_config_and_inputs(self): + config = self.get_config() + + dummy_inputs = { + "image_embedding": floats_tensor([self.batch_size, self.hidden_size]), + } + + return config, dummy_inputs + + +class SamModelTester: + def __init__( + self, + parent, + hidden_size=36, + intermediate_size=72, + projection_dim=62, + output_channels=32, + num_hidden_layers=2, + num_attention_heads=4, + num_channels=3, + image_size=24, + patch_size=2, + hidden_act="gelu", + layer_norm_eps=1e-06, + dropout=0.0, + attention_dropout=0.0, + initializer_range=0.02, + initializer_factor=1.0, + qkv_bias=True, + mlp_ratio=4.0, + use_abs_pos=True, + use_rel_pos=True, + rel_pos_zero_init=False, + window_size=14, + global_attn_indexes=[2, 5, 8, 11], + num_pos_feats=16, + mlp_dim=None, + batch_size=2, + ): + self.parent = parent + self.image_size = image_size + self.patch_size = patch_size + self.output_channels = output_channels + self.num_channels = num_channels + self.hidden_size = hidden_size + self.projection_dim = projection_dim + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.intermediate_size = intermediate_size + self.dropout = dropout + self.attention_dropout = attention_dropout + self.initializer_range = initializer_range + self.initializer_factor = initializer_factor + self.hidden_act = hidden_act + self.layer_norm_eps = layer_norm_eps + self.qkv_bias = qkv_bias + self.mlp_ratio = mlp_ratio + self.use_abs_pos = use_abs_pos + self.use_rel_pos = use_rel_pos + self.rel_pos_zero_init = rel_pos_zero_init + self.window_size = window_size + self.global_attn_indexes = global_attn_indexes + self.num_pos_feats = num_pos_feats + self.mlp_dim = mlp_dim + self.batch_size = batch_size + + # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = num_patches + 1 + + self.prompt_encoder_tester = SamPromptEncoderTester() + self.mask_decoder_tester = SamMaskDecoderTester() + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + config = self.get_config() + + return config, pixel_values + + def get_config(self): + vision_config = SamVisionConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + projection_dim=self.projection_dim, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + dropout=self.dropout, + attention_dropout=self.attention_dropout, + initializer_range=self.initializer_range, + initializer_factor=self.initializer_factor, + output_channels=self.output_channels, + qkv_bias=self.qkv_bias, + mlp_ratio=self.mlp_ratio, + use_abs_pos=self.use_abs_pos, + use_rel_pos=self.use_rel_pos, + rel_pos_zero_init=self.rel_pos_zero_init, + window_size=self.window_size, + global_attn_indexes=self.global_attn_indexes, + num_pos_feats=self.num_pos_feats, + mlp_dim=self.mlp_dim, + ) + + prompt_encoder_config = self.prompt_encoder_tester.get_config() + + mask_decoder_config = self.mask_decoder_tester.get_config() + + return SamConfig( + vision_config=vision_config, + prompt_encoder_config=prompt_encoder_config, + mask_decoder_config=mask_decoder_config, + ) + + def create_and_check_model(self, config, pixel_values): + model = SamModel(config=config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + result = model(pixel_values) + self.parent.assertEqual(result.iou_scores.shape, (self.batch_size, 1, 3)) + self.parent.assertEqual(result.pred_masks.shape[:3], (self.batch_size, 1, 3)) + + def create_and_check_get_image_features(self, config, pixel_values): + model = SamModel(config=config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + result = model.get_image_embeddings(pixel_values) + self.parent.assertEqual(result[0].shape, (self.output_channels, 12, 12)) + + def create_and_check_get_image_hidden_states(self, config, pixel_values): + model = SamModel(config=config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + result = model.vision_encoder( + pixel_values, + output_hidden_states=True, + return_dict=True, + ) + + # after computing the convolutional features + expected_hidden_states_shape = (self.batch_size, 12, 12, 36) + self.parent.assertEqual(len(result[1]), self.num_hidden_layers + 1) + self.parent.assertEqual(result[1][0].shape, expected_hidden_states_shape) + + with torch.no_grad(): + result = model.vision_encoder( + pixel_values, + output_hidden_states=True, + return_dict=False, + ) + + # after computing the convolutional features + expected_hidden_states_shape = (self.batch_size, 12, 12, 36) + self.parent.assertEqual(len(result[1]), self.num_hidden_layers + 1) + self.parent.assertEqual(result[1][0].shape, expected_hidden_states_shape) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class SamModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as SAM's vision encoder does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (SamModel,) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": SamModel, "mask-generation": SamModel} if is_torch_available() else {} + ) + fx_compatible = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + test_torchscript = False + + # TODO: Fix me @Arthur: `run_batch_test` in `tests/test_pipeline_mixin.py` not working + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + return True + + def setUp(self): + self.model_tester = SamModelTester(self) + self.vision_config_tester = ConfigTester(self, config_class=SamVisionConfig, has_text_modality=False) + self.prompt_encoder_config_tester = ConfigTester( + self, + config_class=SamPromptEncoderConfig, + has_text_modality=False, + num_attention_heads=12, + num_hidden_layers=2, + ) + self.mask_decoder_config_tester = ConfigTester( + self, config_class=SamMaskDecoderConfig, has_text_modality=False + ) + + def test_config(self): + self.vision_config_tester.run_common_tests() + self.prompt_encoder_config_tester.run_common_tests() + self.mask_decoder_config_tester.run_common_tests() + + @unittest.skip(reason="SAM's vision encoder does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_get_image_features(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_get_image_features(*config_and_inputs) + + def test_image_hidden_states(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_get_image_hidden_states(*config_and_inputs) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + expected_vision_attention_shape = ( + self.model_tester.batch_size * self.model_tester.num_attention_heads, + 196, + 196, + ) + expected_mask_decoder_attention_shape = (self.model_tester.batch_size, 1, 144, 32) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + vision_attentions = outputs.vision_attentions + self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers) + + mask_decoder_attentions = outputs.mask_decoder_attentions + self.assertEqual(len(mask_decoder_attentions), self.model_tester.mask_decoder_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + vision_attentions = outputs.vision_attentions + self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers) + + mask_decoder_attentions = outputs.mask_decoder_attentions + self.assertEqual(len(mask_decoder_attentions), self.model_tester.mask_decoder_tester.num_hidden_layers) + + self.assertListEqual( + list(vision_attentions[0].shape[-4:]), + list(expected_vision_attention_shape), + ) + + self.assertListEqual( + list(mask_decoder_attentions[0].shape[-4:]), + list(expected_mask_decoder_attention_shape), + ) + + @unittest.skip(reason="SamModel does not support training") + def test_training(self): + pass + + @unittest.skip(reason="SamModel does not support training") + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + @unittest.skip(reason="SamModel has no base class and is not available in MODEL_MAPPING") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip(reason="SamModel has no base class and is not available in MODEL_MAPPING") + def test_save_load_fast_init_to_base(self): + pass + + @unittest.skip(reason="SamModel does not support training") + def test_retain_grad_hidden_states_attentions(self): + pass + + @unittest.skip(reason="Hidden_states is tested in create_and_check_model tests") + def test_hidden_states_output(self): + pass + + def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=5e-5, name="outputs", attributes=None): + # Use a slightly higher default tol to make the tests non-flaky + super().check_pt_tf_outputs(tf_outputs, pt_outputs, model_class, tol=tol, name=name, attributes=attributes) + + @slow + def test_model_from_pretrained(self): + for model_name in SAM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SamModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +def prepare_image(): + img_url = "https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png" + raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB") + return raw_image + + +def prepare_dog_img(): + img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dog-sam.png" + raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB") + return raw_image + + +@slow +class SamModelIntegrationTest(unittest.TestCase): + def tearDown(self): + super().tearDown() + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + backend_empty_cache(torch_device) + + def test_inference_mask_generation_no_point(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + inputs = processor(images=raw_image, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + masks = outputs.pred_masks[0, 0, 0, 0, :3] + self.assertTrue(torch.allclose(scores[-1], torch.tensor(0.4515), atol=2e-4)) + self.assertTrue(torch.allclose(masks, torch.tensor([-4.1800, -3.4948, -3.4481]).to(torch_device), atol=2e-4)) + + def test_inference_mask_generation_one_point_one_bb(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + input_boxes = [[[650, 900, 1000, 1250]]] + input_points = [[[820, 1080]]] + + inputs = processor( + images=raw_image, input_boxes=input_boxes, input_points=input_points, return_tensors="pt" + ).to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + masks = outputs.pred_masks[0, 0, 0, 0, :3] + self.assertTrue(torch.allclose(scores[-1], torch.tensor(0.9566), atol=2e-4)) + self.assertTrue( + torch.allclose(masks, torch.tensor([-12.7729, -12.3665, -12.6061]).to(torch_device), atol=2e-4) + ) + + def test_inference_mask_generation_batched_points_batched_images(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + input_points = [ + [[[820, 1080]], [[820, 1080]], [[820, 1080]], [[820, 1080]]], + [[[510, 1080]], [[820, 1080]], [[820, 1080]], [[820, 1080]]], + ] + + inputs = processor(images=[raw_image, raw_image], input_points=input_points, return_tensors="pt").to( + torch_device + ) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze().cpu() + masks = outputs.pred_masks[0, 0, 0, 0, :3].cpu() + + EXPECTED_SCORES = torch.tensor( + [ + [ + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + ], + [ + [0.3317, 0.7264, 0.7646], + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + ], + ] + ) + EXPECTED_MASKS = torch.tensor([-2.8550, -2.7988, -2.9625]) + self.assertTrue(torch.allclose(scores, EXPECTED_SCORES, atol=1e-3)) + self.assertTrue(torch.allclose(masks, EXPECTED_MASKS, atol=1e-3)) + + def test_inference_mask_generation_one_point_one_bb_zero(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + input_boxes = [[[620, 900, 1000, 1255]]] + input_points = [[[820, 1080]]] + labels = [[0]] + + inputs = processor( + images=raw_image, + input_boxes=input_boxes, + input_points=input_points, + input_labels=labels, + return_tensors="pt", + ).to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + + self.assertTrue(torch.allclose(scores[-1], torch.tensor(0.7894), atol=1e-4)) + + def test_inference_mask_generation_one_point(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + + input_points = [[[400, 650]]] + input_labels = [[1]] + + inputs = processor( + images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt" + ).to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + self.assertTrue(torch.allclose(scores[-1], torch.tensor(0.9675), atol=1e-4)) + + # With no label + input_points = [[[400, 650]]] + + inputs = processor(images=raw_image, input_points=input_points, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + self.assertTrue(torch.allclose(scores[-1], torch.tensor(0.9675), atol=1e-4)) + + def test_inference_mask_generation_two_points(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + + input_points = [[[400, 650], [800, 650]]] + input_labels = [[1, 1]] + + inputs = processor( + images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt" + ).to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + self.assertTrue(torch.allclose(scores[-1], torch.tensor(0.9762), atol=1e-4)) + + # no labels + inputs = processor(images=raw_image, input_points=input_points, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + + self.assertTrue(torch.allclose(scores[-1], torch.tensor(0.9762), atol=1e-4)) + + def test_inference_mask_generation_two_points_batched(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + + input_points = [[[400, 650], [800, 650]], [[400, 650]]] + input_labels = [[1, 1], [1]] + + inputs = processor( + images=[raw_image, raw_image], input_points=input_points, input_labels=input_labels, return_tensors="pt" + ).to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + self.assertTrue(torch.allclose(scores[0][-1], torch.tensor(0.9762), atol=1e-4)) + self.assertTrue(torch.allclose(scores[1][-1], torch.tensor(0.9637), atol=1e-4)) + + def test_inference_mask_generation_one_box(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + + input_boxes = [[[75, 275, 1725, 850]]] + + inputs = processor(images=raw_image, input_boxes=input_boxes, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores = outputs.iou_scores.squeeze() + self.assertTrue(torch.allclose(scores[-1], torch.tensor(0.7937), atol=1e-4)) + + def test_inference_mask_generation_batched_image_one_point(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + raw_dog_image = prepare_dog_img() + + input_points = [[[820, 1080]], [[220, 470]]] + + inputs = processor(images=[raw_image, raw_dog_image], input_points=input_points, return_tensors="pt").to( + torch_device + ) + + with torch.no_grad(): + outputs = model(**inputs) + scores_batched = outputs.iou_scores.squeeze() + + input_points = [[[220, 470]]] + + inputs = processor(images=raw_dog_image, input_points=input_points, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + scores_single = outputs.iou_scores.squeeze() + self.assertTrue(torch.allclose(scores_batched[1, :], scores_single, atol=1e-4)) + + def test_inference_mask_generation_two_points_point_batch(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + + input_points = torch.Tensor([[[400, 650]], [[220, 470]]]).cpu() # fmt: skip + + input_points = input_points.unsqueeze(0) + + inputs = processor(raw_image, input_points=input_points, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + + iou_scores = outputs.iou_scores.cpu() + self.assertTrue(iou_scores.shape == (1, 2, 3)) + torch.testing.assert_allclose( + iou_scores, torch.tensor([[[0.9105, 0.9825, 0.9675], [0.7646, 0.7943, 0.7774]]]), atol=1e-4, rtol=1e-4 + ) + + def test_inference_mask_generation_three_boxes_point_batch(self): + model = SamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + model.to(torch_device) + model.eval() + + raw_image = prepare_image() + + # fmt: off + input_boxes = torch.Tensor([[[620, 900, 1000, 1255]], [[75, 275, 1725, 850]], [[75, 275, 1725, 850]]]).cpu() + EXPECTED_IOU = torch.tensor([[[0.9773, 0.9881, 0.9522], + [0.5996, 0.7661, 0.7937], + [0.5996, 0.7661, 0.7937]]]) + # fmt: on + input_boxes = input_boxes.unsqueeze(0) + + inputs = processor(raw_image, input_boxes=input_boxes, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + + iou_scores = outputs.iou_scores.cpu() + self.assertTrue(iou_scores.shape == (1, 3, 3)) + torch.testing.assert_allclose(iou_scores, EXPECTED_IOU, atol=1e-4, rtol=1e-4) + + def test_dummy_pipeline_generation(self): + generator = pipeline("mask-generation", model="facebook/sam-vit-base", device=torch_device) + raw_image = prepare_image() + + _ = generator(raw_image, points_per_batch=64) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_modeling_tf_sam.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_modeling_tf_sam.py new file mode 100644 index 0000000000000000000000000000000000000000..4478815e7ce9e61e0ce518bc949c47efd982d662 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_modeling_tf_sam.py @@ -0,0 +1,670 @@ +# coding=utf-8 +# Copyright 2023 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 TensorFlow SAM model. """ + + +from __future__ import annotations + +import inspect +import unittest + +import numpy as np +import requests + +from transformers import SamConfig, SamMaskDecoderConfig, SamPromptEncoderConfig, SamVisionConfig +from transformers.testing_utils import require_tf, slow +from transformers.utils import is_tf_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import SamProcessor, TFSamModel + +if is_vision_available(): + from PIL import Image + + +class TFSamPromptEncoderTester: + def __init__( + self, + hidden_size=32, + input_image_size=24, + patch_size=2, + mask_input_channels=4, + num_point_embeddings=4, + hidden_act="gelu", + ): + self.hidden_size = hidden_size + self.input_image_size = input_image_size + self.patch_size = patch_size + self.mask_input_channels = mask_input_channels + self.num_point_embeddings = num_point_embeddings + self.hidden_act = hidden_act + + def get_config(self): + return SamPromptEncoderConfig( + image_size=self.input_image_size, + patch_size=self.patch_size, + mask_input_channels=self.mask_input_channels, + hidden_size=self.hidden_size, + num_point_embeddings=self.num_point_embeddings, + hidden_act=self.hidden_act, + ) + + def prepare_config_and_inputs(self): + dummy_points = floats_tensor([self.batch_size, 3, 2]) + config = self.get_config() + + return config, dummy_points + + +class TFSamMaskDecoderTester: + def __init__( + self, + hidden_size=32, + hidden_act="relu", + mlp_dim=64, + num_hidden_layers=2, + num_attention_heads=4, + attention_downsample_rate=2, + num_multimask_outputs=3, + iou_head_depth=3, + iou_head_hidden_dim=32, + layer_norm_eps=1e-6, + ): + self.hidden_size = hidden_size + self.hidden_act = hidden_act + self.mlp_dim = mlp_dim + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.attention_downsample_rate = attention_downsample_rate + self.num_multimask_outputs = num_multimask_outputs + self.iou_head_depth = iou_head_depth + self.iou_head_hidden_dim = iou_head_hidden_dim + self.layer_norm_eps = layer_norm_eps + + def get_config(self): + return SamMaskDecoderConfig( + hidden_size=self.hidden_size, + hidden_act=self.hidden_act, + mlp_dim=self.mlp_dim, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + attention_downsample_rate=self.attention_downsample_rate, + num_multimask_outputs=self.num_multimask_outputs, + iou_head_depth=self.iou_head_depth, + iou_head_hidden_dim=self.iou_head_hidden_dim, + layer_norm_eps=self.layer_norm_eps, + ) + + def prepare_config_and_inputs(self): + config = self.get_config() + + dummy_inputs = { + "image_embedding": floats_tensor([self.batch_size, self.hidden_size]), + } + + return config, dummy_inputs + + +class TFSamModelTester: + def __init__( + self, + parent, + hidden_size=36, + intermediate_size=72, + projection_dim=62, + output_channels=32, + num_hidden_layers=2, + num_attention_heads=4, + num_channels=3, + image_size=24, + patch_size=2, + hidden_act="gelu", + layer_norm_eps=1e-06, + dropout=0.0, + attention_dropout=0.0, + initializer_range=0.02, + initializer_factor=1.0, + qkv_bias=True, + mlp_ratio=4.0, + use_abs_pos=True, + use_rel_pos=True, + rel_pos_zero_init=False, + window_size=14, + global_attn_indexes=[2, 5, 8, 11], + num_pos_feats=16, + mlp_dim=None, + batch_size=2, + ): + self.parent = parent + self.image_size = image_size + self.patch_size = patch_size + self.output_channels = output_channels + self.num_channels = num_channels + self.hidden_size = hidden_size + self.projection_dim = projection_dim + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.intermediate_size = intermediate_size + self.dropout = dropout + self.attention_dropout = attention_dropout + self.initializer_range = initializer_range + self.initializer_factor = initializer_factor + self.hidden_act = hidden_act + self.layer_norm_eps = layer_norm_eps + self.qkv_bias = qkv_bias + self.mlp_ratio = mlp_ratio + self.use_abs_pos = use_abs_pos + self.use_rel_pos = use_rel_pos + self.rel_pos_zero_init = rel_pos_zero_init + self.window_size = window_size + self.global_attn_indexes = global_attn_indexes + self.num_pos_feats = num_pos_feats + self.mlp_dim = mlp_dim + self.batch_size = batch_size + + # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = num_patches + 1 + + self.prompt_encoder_tester = TFSamPromptEncoderTester() + self.mask_decoder_tester = TFSamMaskDecoderTester() + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + config = self.get_config() + + return config, pixel_values + + def get_config(self): + vision_config = SamVisionConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + projection_dim=self.projection_dim, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + dropout=self.dropout, + attention_dropout=self.attention_dropout, + initializer_range=self.initializer_range, + initializer_factor=self.initializer_factor, + output_channels=self.output_channels, + qkv_bias=self.qkv_bias, + mlp_ratio=self.mlp_ratio, + use_abs_pos=self.use_abs_pos, + use_rel_pos=self.use_rel_pos, + rel_pos_zero_init=self.rel_pos_zero_init, + window_size=self.window_size, + global_attn_indexes=self.global_attn_indexes, + num_pos_feats=self.num_pos_feats, + mlp_dim=self.mlp_dim, + ) + + prompt_encoder_config = self.prompt_encoder_tester.get_config() + + mask_decoder_config = self.mask_decoder_tester.get_config() + + return SamConfig( + vision_config=vision_config, + prompt_encoder_config=prompt_encoder_config, + mask_decoder_config=mask_decoder_config, + ) + + def create_and_check_model(self, config, pixel_values): + model = TFSamModel(config=config) + result = model(pixel_values) + self.parent.assertEqual(result.iou_scores.shape, (self.batch_size, 1, 3)) + self.parent.assertEqual(result.pred_masks.shape[:3], (self.batch_size, 1, 3)) + + def create_and_check_get_image_features(self, config, pixel_values): + model = TFSamModel(config=config) + result = model.get_image_embeddings(pixel_values) + self.parent.assertEqual(result[0].shape, (self.output_channels, 12, 12)) + + def create_and_check_get_image_hidden_states(self, config, pixel_values): + model = TFSamModel(config=config) + result = model.vision_encoder( + pixel_values, + output_hidden_states=True, + return_dict=True, + ) + + # after computing the convolutional features + expected_hidden_states_shape = (self.batch_size, 12, 12, 36) + self.parent.assertEqual(len(result[1]), self.num_hidden_layers + 1) + self.parent.assertEqual(result[1][0].shape, expected_hidden_states_shape) + + result = model.vision_encoder( + pixel_values, + output_hidden_states=True, + return_dict=False, + ) + + # after computing the convolutional features + expected_hidden_states_shape = (self.batch_size, 12, 12, 36) + self.parent.assertEqual(len(result[1]), self.num_hidden_layers + 1) + self.parent.assertEqual(result[1][0].shape, expected_hidden_states_shape) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_tf +class TFSamModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as SAM's vision encoder does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (TFSamModel,) if is_tf_available() else () + pipeline_model_mapping = ( + {"feature-extraction": TFSamModel, "mask-generation": TFSamModel} if is_tf_available() else {} + ) + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + test_onnx = False + + # TODO: Fix me @Arthur: `run_batch_test` in `tests/test_pipeline_mixin.py` not working + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + return True + + def setUp(self): + self.model_tester = TFSamModelTester(self) + self.vision_config_tester = ConfigTester(self, config_class=SamVisionConfig, has_text_modality=False) + self.prompt_encoder_config_tester = ConfigTester( + self, + config_class=SamPromptEncoderConfig, + has_text_modality=False, + num_attention_heads=12, + num_hidden_layers=2, + ) + self.mask_decoder_config_tester = ConfigTester( + self, config_class=SamMaskDecoderConfig, has_text_modality=False + ) + + def test_config(self): + self.vision_config_tester.run_common_tests() + self.prompt_encoder_config_tester.run_common_tests() + self.mask_decoder_config_tester.run_common_tests() + + @unittest.skip(reason="SAM's vision encoder does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (tf.keras.layers.Layer)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, tf.keras.layers.Dense)) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_get_image_features(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_get_image_features(*config_and_inputs) + + def test_image_hidden_states(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_get_image_hidden_states(*config_and_inputs) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + expected_vision_attention_shape = ( + self.model_tester.batch_size * self.model_tester.num_attention_heads, + 196, + 196, + ) + expected_mask_decoder_attention_shape = (self.model_tester.batch_size, 1, 144, 32) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + vision_attentions = outputs.vision_attentions + self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers) + + mask_decoder_attentions = outputs.mask_decoder_attentions + self.assertEqual(len(mask_decoder_attentions), self.model_tester.mask_decoder_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + vision_attentions = outputs.vision_attentions + self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers) + + mask_decoder_attentions = outputs.mask_decoder_attentions + self.assertEqual(len(mask_decoder_attentions), self.model_tester.mask_decoder_tester.num_hidden_layers) + + self.assertListEqual( + list(vision_attentions[0].shape[-4:]), + list(expected_vision_attention_shape), + ) + + self.assertListEqual( + list(mask_decoder_attentions[0].shape[-4:]), + list(expected_mask_decoder_attention_shape), + ) + + @unittest.skip(reason="Hidden_states is tested in create_and_check_model tests") + def test_hidden_states_output(self): + pass + + @slow + def test_model_from_pretrained(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") # sam-vit-huge blows out our memory + self.assertIsNotNone(model) + + def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=5e-4, name="outputs", attributes=None): + super().check_pt_tf_outputs( + tf_outputs=tf_outputs, + pt_outputs=pt_outputs, + model_class=model_class, + tol=tol, + name=name, + attributes=attributes, + ) + + +def prepare_image(): + img_url = "https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png" + raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB") + return raw_image + + +def prepare_dog_img(): + img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dog-sam.png" + raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB") + return raw_image + + +@require_tf +@slow +class TFSamModelIntegrationTest(unittest.TestCase): + def test_inference_mask_generation_no_point(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + inputs = processor(images=raw_image, return_tensors="tf") + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + masks = outputs.pred_masks[0, 0, 0, 0, :3] + self.assertTrue(np.allclose(scores[-1].numpy(), np.array(0.4515), atol=2e-4)) + self.assertTrue(np.allclose(masks.numpy(), np.array([-4.1807, -3.4949, -3.4483]), atol=1e-2)) + + def test_inference_mask_generation_one_point_one_bb(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + input_boxes = [[[650, 900, 1000, 1250]]] + input_points = [[[820, 1080]]] + + inputs = processor(images=raw_image, input_boxes=input_boxes, input_points=input_points, return_tensors="tf") + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + masks = outputs.pred_masks[0, 0, 0, 0, :3] + + self.assertTrue(np.allclose(scores[-1], np.array(0.9566), atol=2e-4)) + self.assertTrue(np.allclose(masks.numpy(), np.array([-12.7657, -12.3683, -12.5985]), atol=2e-2)) + + def test_inference_mask_generation_batched_points_batched_images(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + input_points = [ + [[[820, 1080]], [[820, 1080]], [[820, 1080]], [[820, 1080]]], + [[[510, 1080]], [[820, 1080]], [[820, 1080]], [[820, 1080]]], + ] + + inputs = processor(images=[raw_image, raw_image], input_points=input_points, return_tensors="tf") + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + masks = outputs.pred_masks[0, 0, 0, 0, :3] + + EXPECTED_SCORES = np.array( + [ + [ + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + ], + [ + [0.3317, 0.7264, 0.7646], + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + [0.6765, 0.9379, 0.8803], + ], + ] + ) + EXPECTED_MASKS = np.array([-2.8552, -2.7990, -2.9612]) + self.assertTrue(np.allclose(scores.numpy(), EXPECTED_SCORES, atol=1e-3)) + self.assertTrue(np.allclose(masks.numpy(), EXPECTED_MASKS, atol=3e-2)) + + def test_inference_mask_generation_one_point_one_bb_zero(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + input_boxes = [[[620, 900, 1000, 1255]]] + input_points = [[[820, 1080]]] + labels = [[0]] + + inputs = processor( + images=raw_image, + input_boxes=input_boxes, + input_points=input_points, + input_labels=labels, + return_tensors="tf", + ) + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + self.assertTrue(np.allclose(scores[-1].numpy(), np.array(0.7894), atol=1e-4)) + + def test_inference_mask_generation_one_point(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + + input_points = [[[400, 650]]] + input_labels = [[1]] + + inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="tf") + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + + self.assertTrue(np.allclose(scores[-1], np.array(0.9675), atol=1e-4)) + + # With no label + input_points = [[[400, 650]]] + + inputs = processor(images=raw_image, input_points=input_points, return_tensors="tf") + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + + self.assertTrue(np.allclose(scores[-1].numpy(), np.array(0.9675), atol=1e-4)) + + def test_inference_mask_generation_two_points(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + raw_image = prepare_image() + + input_points = [[[400, 650], [800, 650]]] + input_labels = [[1, 1]] + + inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="tf") + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + + self.assertTrue(np.allclose(scores[-1].numpy(), np.array(0.9762), atol=1e-4)) + + # no labels + inputs = processor(images=raw_image, input_points=input_points, return_tensors="tf") + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + + self.assertTrue(np.allclose(scores[-1].numpy(), np.array(0.9762), atol=1e-4)) + + def test_inference_mask_generation_two_points_batched(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + + input_points = [[[400, 650], [800, 650]], [[400, 650]]] + input_labels = [[1, 1], [1]] + + inputs = processor( + images=[raw_image, raw_image], input_points=input_points, input_labels=input_labels, return_tensors="tf" + ) + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + + self.assertTrue(np.allclose(scores[0][-1].numpy(), np.array(0.9762), atol=1e-4)) + self.assertTrue(np.allclose(scores[1][-1], np.array(0.9637), atol=1e-4)) + + def test_inference_mask_generation_one_box(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + + input_boxes = [[[75, 275, 1725, 850]]] + + inputs = processor(images=raw_image, input_boxes=input_boxes, return_tensors="tf") + + outputs = model(**inputs) + scores = tf.squeeze(outputs.iou_scores) + + self.assertTrue(np.allclose(scores[-1].numpy(), np.array(0.7937), atol=1e-4)) + + def test_inference_mask_generation_batched_image_one_point(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + raw_dog_image = prepare_dog_img() + + input_points = [[[820, 1080]], [[220, 470]]] + + inputs = processor(images=[raw_image, raw_dog_image], input_points=input_points, return_tensors="tf") + + outputs = model(**inputs) + scores_batched = tf.squeeze(outputs.iou_scores) + + input_points = [[[220, 470]]] + + inputs = processor(images=raw_dog_image, input_points=input_points, return_tensors="tf") + + outputs = model(**inputs) + scores_single = tf.squeeze(outputs.iou_scores) + self.assertTrue(np.allclose(scores_batched[1, :].numpy(), scores_single.numpy(), atol=1e-4)) + + def test_inference_mask_generation_two_points_point_batch(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + + input_points = tf.convert_to_tensor([[[400, 650]], [[220, 470]]]) # fmt: skip + + input_points = tf.expand_dims(input_points, 0) + + inputs = processor(raw_image, input_points=input_points, return_tensors="tf") + + outputs = model(**inputs) + + iou_scores = outputs.iou_scores + self.assertTrue(iou_scores.shape == (1, 2, 3)) + self.assertTrue( + np.allclose( + iou_scores.numpy(), + np.array([[[0.9105, 0.9825, 0.9675], [0.7646, 0.7943, 0.7774]]]), + atol=1e-4, + rtol=1e-4, + ) + ) + + def test_inference_mask_generation_three_boxes_point_batch(self): + model = TFSamModel.from_pretrained("facebook/sam-vit-base") + processor = SamProcessor.from_pretrained("facebook/sam-vit-base") + + raw_image = prepare_image() + + # fmt: off + input_boxes = tf.convert_to_tensor([[[620, 900, 1000, 1255]], [[75, 275, 1725, 850]], [[75, 275, 1725, 850]]]) + EXPECTED_IOU = np.array([[[0.9773, 0.9881, 0.9522], + [0.5996, 0.7661, 0.7937], + [0.5996, 0.7661, 0.7937]]]) + # fmt: on + input_boxes = tf.expand_dims(input_boxes, 0) + + inputs = processor(raw_image, input_boxes=input_boxes, return_tensors="tf") + + outputs = model(**inputs) + + iou_scores = outputs.iou_scores + self.assertTrue(iou_scores.shape == (1, 3, 3)) + self.assertTrue(np.allclose(iou_scores.numpy(), EXPECTED_IOU, atol=1e-4, rtol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_processor_sam.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_processor_sam.py new file mode 100644 index 0000000000000000000000000000000000000000..7d669bb969143c4e9c9009a196c47859bd1819e4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sam/test_processor_sam.py @@ -0,0 +1,276 @@ +# Copyright 2023 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 shutil +import tempfile +import unittest + +import numpy as np + +from transformers.testing_utils import ( + is_pt_tf_cross_test, + require_tf, + require_torch, + require_torchvision, + require_vision, +) +from transformers.utils import is_tf_available, is_torch_available, is_vision_available + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoProcessor, SamImageProcessor, SamProcessor + +if is_torch_available(): + import torch + +if is_tf_available(): + import tensorflow as tf + + +@require_vision +@require_torchvision +class SamProcessorTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + image_processor = SamImageProcessor() + processor = SamProcessor(image_processor) + processor.save_pretrained(self.tmpdirname) + + def get_image_processor(self, **kwargs): + return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def prepare_image_inputs(self): + """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, + or a list of PyTorch tensors if one specifies torchify=True. + """ + + image_inputs = [np.random.randint(255, size=(3, 30, 400), dtype=np.uint8)] + + image_inputs = [Image.fromarray(np.moveaxis(x, 0, -1)) for x in image_inputs] + + return image_inputs + + def test_save_load_pretrained_additional_features(self): + processor = SamProcessor(image_processor=self.get_image_processor()) + processor.save_pretrained(self.tmpdirname) + + image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0) + + processor = SamProcessor.from_pretrained(self.tmpdirname, do_normalize=False, padding_value=1.0) + + self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.image_processor, SamImageProcessor) + + def test_image_processor(self): + image_processor = self.get_image_processor() + + processor = SamProcessor(image_processor=image_processor) + + image_input = self.prepare_image_inputs() + + input_feat_extract = image_processor(image_input, return_tensors="np") + input_processor = processor(images=image_input, return_tensors="np") + + input_feat_extract.pop("original_sizes") # pop original_sizes as it is popped in the processor + input_feat_extract.pop("reshaped_input_sizes") # pop original_sizes as it is popped in the processor + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + @require_torch + def test_post_process_masks(self): + image_processor = self.get_image_processor() + + processor = SamProcessor(image_processor=image_processor) + dummy_masks = [torch.ones((1, 3, 5, 5))] + + original_sizes = [[1764, 2646]] + + reshaped_input_size = [[683, 1024]] + masks = processor.post_process_masks(dummy_masks, original_sizes, reshaped_input_size) + self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) + + masks = processor.post_process_masks( + dummy_masks, torch.tensor(original_sizes), torch.tensor(reshaped_input_size) + ) + self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) + + # should also work with np + dummy_masks = [np.ones((1, 3, 5, 5))] + masks = processor.post_process_masks(dummy_masks, np.array(original_sizes), np.array(reshaped_input_size)) + + self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) + + dummy_masks = [[1, 0], [0, 1]] + with self.assertRaises(ValueError): + masks = processor.post_process_masks(dummy_masks, np.array(original_sizes), np.array(reshaped_input_size)) + + +@require_vision +@require_tf +class TFSamProcessorTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + image_processor = SamImageProcessor() + processor = SamProcessor(image_processor) + processor.save_pretrained(self.tmpdirname) + + def get_image_processor(self, **kwargs): + return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def prepare_image_inputs(self): + """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, + or a list of PyTorch tensors if one specifies torchify=True. + """ + + image_inputs = [np.random.randint(255, size=(3, 30, 400), dtype=np.uint8)] + + image_inputs = [Image.fromarray(np.moveaxis(x, 0, -1)) for x in image_inputs] + + return image_inputs + + def test_save_load_pretrained_additional_features(self): + processor = SamProcessor(image_processor=self.get_image_processor()) + processor.save_pretrained(self.tmpdirname) + + image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0) + + processor = SamProcessor.from_pretrained(self.tmpdirname, do_normalize=False, padding_value=1.0) + + self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.image_processor, SamImageProcessor) + + def test_image_processor(self): + image_processor = self.get_image_processor() + + processor = SamProcessor(image_processor=image_processor) + + image_input = self.prepare_image_inputs() + + input_feat_extract = image_processor(image_input, return_tensors="np") + input_processor = processor(images=image_input, return_tensors="np") + + input_feat_extract.pop("original_sizes") # pop original_sizes as it is popped in the processor + input_feat_extract.pop("reshaped_input_sizes") # pop reshaped_input_sizes as it is popped in the processor + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + @require_tf + def test_post_process_masks(self): + image_processor = self.get_image_processor() + + processor = SamProcessor(image_processor=image_processor) + dummy_masks = [tf.ones((1, 3, 5, 5))] + + original_sizes = [[1764, 2646]] + + reshaped_input_size = [[683, 1024]] + masks = processor.post_process_masks(dummy_masks, original_sizes, reshaped_input_size, return_tensors="tf") + self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) + + masks = processor.post_process_masks( + dummy_masks, + tf.convert_to_tensor(original_sizes), + tf.convert_to_tensor(reshaped_input_size), + return_tensors="tf", + ) + self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) + + # should also work with np + dummy_masks = [np.ones((1, 3, 5, 5))] + masks = processor.post_process_masks( + dummy_masks, np.array(original_sizes), np.array(reshaped_input_size), return_tensors="tf" + ) + + self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) + + dummy_masks = [[1, 0], [0, 1]] + with self.assertRaises(tf.errors.InvalidArgumentError): + masks = processor.post_process_masks( + dummy_masks, np.array(original_sizes), np.array(reshaped_input_size), return_tensors="tf" + ) + + +@require_vision +@require_torchvision +class SamProcessorEquivalenceTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + image_processor = SamImageProcessor() + processor = SamProcessor(image_processor) + processor.save_pretrained(self.tmpdirname) + + def get_image_processor(self, **kwargs): + return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def prepare_image_inputs(self): + """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, + or a list of PyTorch tensors if one specifies torchify=True. + """ + + image_inputs = [np.random.randint(255, size=(3, 30, 400), dtype=np.uint8)] + + image_inputs = [Image.fromarray(np.moveaxis(x, 0, -1)) for x in image_inputs] + + return image_inputs + + @is_pt_tf_cross_test + def test_post_process_masks_equivalence(self): + image_processor = self.get_image_processor() + + processor = SamProcessor(image_processor=image_processor) + dummy_masks = np.random.randint(0, 2, size=(1, 3, 5, 5)).astype(np.float32) + tf_dummy_masks = [tf.convert_to_tensor(dummy_masks)] + pt_dummy_masks = [torch.tensor(dummy_masks)] + + original_sizes = [[1764, 2646]] + + reshaped_input_size = [[683, 1024]] + tf_masks = processor.post_process_masks( + tf_dummy_masks, original_sizes, reshaped_input_size, return_tensors="tf" + ) + pt_masks = processor.post_process_masks( + pt_dummy_masks, original_sizes, reshaped_input_size, return_tensors="pt" + ) + + self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy())) + + @is_pt_tf_cross_test + def test_image_processor_equivalence(self): + image_processor = self.get_image_processor() + + processor = SamProcessor(image_processor=image_processor) + + image_input = self.prepare_image_inputs() + + pt_input_feat_extract = image_processor(image_input, return_tensors="pt")["pixel_values"].numpy() + pt_input_processor = processor(images=image_input, return_tensors="pt")["pixel_values"].numpy() + + tf_input_feat_extract = image_processor(image_input, return_tensors="tf")["pixel_values"].numpy() + tf_input_processor = processor(images=image_input, return_tensors="tf")["pixel_values"].numpy() + + self.assertTrue(np.allclose(pt_input_feat_extract, pt_input_processor)) + self.assertTrue(np.allclose(pt_input_feat_extract, tf_input_feat_extract)) + self.assertTrue(np.allclose(pt_input_feat_extract, tf_input_processor)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_feature_extraction_seamless_m4t.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_feature_extraction_seamless_m4t.py new file mode 100644 index 0000000000000000000000000000000000000000..2b55a61d812ad8867d514b39e0e6d8f950c861e4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_feature_extraction_seamless_m4t.py @@ -0,0 +1,223 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 itertools +import os +import random +import tempfile +import unittest + +import numpy as np +from datasets import load_dataset + +from transformers import SeamlessM4TFeatureExtractor, is_speech_available +from transformers.testing_utils import check_json_file_has_correct_format, require_torch +from transformers.utils.import_utils import is_torch_available + +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +if is_torch_available(): + import torch + +global_rng = random.Random() + + +# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +@require_torch +class SeamlessM4TFeatureExtractionTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + min_seq_length=400, + max_seq_length=2000, + feature_size=10, + padding_value=0.0, + sampling_rate=4_000, + return_attention_mask=True, + do_normalize=True, + stride=2, + ): + self.parent = parent + self.batch_size = batch_size + self.min_seq_length = min_seq_length + self.max_seq_length = max_seq_length + self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) + self.padding_value = padding_value + self.sampling_rate = sampling_rate + self.return_attention_mask = return_attention_mask + self.do_normalize = do_normalize + self.feature_size = feature_size + self.stride = stride + self.num_mel_bins = feature_size + + def prepare_feat_extract_dict(self): + return { + "feature_size": self.feature_size, + "num_mel_bins": self.num_mel_bins, + "padding_value": self.padding_value, + "sampling_rate": self.sampling_rate, + "stride": self.stride, + "return_attention_mask": self.return_attention_mask, + "do_normalize": self.do_normalize, + } + + # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTester.prepare_inputs_for_common + def prepare_inputs_for_common(self, equal_length=False, numpify=False): + def _flatten(list_of_lists): + return list(itertools.chain(*list_of_lists)) + + if equal_length: + speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] + else: + # make sure that inputs increase in size + speech_inputs = [ + floats_list((x, self.feature_size)) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + return speech_inputs + + +@require_torch +class SeamlessM4TFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = SeamlessM4TFeatureExtractor if is_speech_available() else None + + def setUp(self): + self.feat_extract_tester = SeamlessM4TFeatureExtractionTester(self) + + def test_feat_extract_from_and_save_pretrained(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = feat_extract_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + self.assertDictEqual(dict_first, dict_second) + + def test_feat_extract_to_json_file(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "feat_extract.json") + feat_extract_first.to_json_file(json_file_path) + feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + self.assertEqual(dict_first, dict_second) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test feature size + input_features = feature_extractor(np_speech_inputs, padding=True, return_tensors="np").input_features + self.assertTrue(input_features.ndim == 3) + self.assertTrue(input_features.shape[0] == 3) + self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size * feature_extractor.stride) + + # Test not batched input + encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_features + self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) + + # Test batched + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test 2-D numpy arrays are batched. + speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] + np_speech_inputs = np.asarray(speech_inputs) + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + @require_torch + # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest.test_double_precision_pad + def test_double_precision_pad(self): + import torch + + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + np_speech_inputs = np.random.rand(100, 32).astype(np.float64) + py_speech_inputs = np_speech_inputs.tolist() + + for inputs in [py_speech_inputs, np_speech_inputs]: + np_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="np") + self.assertTrue(np_processed.input_features.dtype == np.float32) + pt_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="pt") + self.assertTrue(pt_processed.input_features.dtype == torch.float32) + + def _load_datasample(self, id): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_sample = ds.sort("id")[id]["audio"]["array"] + + return torch.from_numpy(speech_sample).unsqueeze(0) + + def test_integration(self): + # fmt: off + EXPECTED_INPUT_FEATURES = torch.tensor( + [ + -1.5621, -1.4236, -1.3335, -1.3991, -1.2881, -1.1133, -0.9710, -0.8895, + -0.8280, -0.7376, -0.7194, -0.6896, -0.6849, -0.6788, -0.6545, -0.6610, + -0.6566, -0.5738, -0.5252, -0.5533, -0.5887, -0.6116, -0.5971, -0.4956, + -0.2881, -0.1512, 0.0299, 0.1762, 0.2728, 0.2236 + ] + ) + # fmt: on + + input_speech = self._load_datasample(10) + feature_extractor = SeamlessM4TFeatureExtractor() + input_features = feature_extractor(input_speech, return_tensors="pt").input_features + + feature_extractor(input_speech, return_tensors="pt").input_features[0, 5, :30] + self.assertEqual(input_features.shape, (1, 279, 160)) + self.assertTrue(torch.allclose(input_features[0, 5, :30], EXPECTED_INPUT_FEATURES, atol=1e-4)) + + def test_zero_mean_unit_variance_normalization_trunc_np_longest(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + audio = self._load_datasample(1) + audio = ((audio - audio.min()) / (audio.max() - audio.min())) * 65535 # Rescale to [0, 65535] to show issue + audio = feat_extract.zero_mean_unit_var_norm([audio], attention_mask=None)[0] + + self.assertTrue((audio.mean() < 1e-3).all()) + self.assertTrue(((audio.var() - 1).abs() < 1e-3).all()) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_modeling_seamless_m4t.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_modeling_seamless_m4t.py new file mode 100644 index 0000000000000000000000000000000000000000..cddaddda183cd7d1af45af17c56a076d8aed58b0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_modeling_seamless_m4t.py @@ -0,0 +1,1130 @@ +# coding=utf-8 +# Copyright 2023 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 SeamlessM4T model. """ + + +import copy +import tempfile +import unittest + +from transformers import SeamlessM4TConfig, is_speech_available, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device +from transformers.trainer_utils import set_seed +from transformers.utils import cached_property + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + SeamlessM4TForSpeechToSpeech, + SeamlessM4TForSpeechToText, + SeamlessM4TForTextToSpeech, + SeamlessM4TForTextToText, + SeamlessM4TModel, + ) + from transformers.models.seamless_m4t.modeling_seamless_m4t import ( + SEAMLESS_M4T_PRETRAINED_MODEL_ARCHIVE_LIST, + ) + +if is_speech_available(): + from transformers import SeamlessM4TProcessor + + +class SeamlessM4TModelTester: + def __init__( + self, + parent, + input_modality="speech", + batch_size=2, + seq_length=4, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + initializer_range=0.02, + max_new_tokens=None, + num_labels=3, + num_choices=4, + scope=None, + vocab_size=20, + t2u_vocab_size=20, + hidden_size=6, + num_hidden_layers=2, + intermediate_size=6, + max_position_embeddings=256, + encoder_layers=2, + decoder_layers=2, + encoder_ffn_dim=6, + decoder_ffn_dim=6, + t2u_encoder_layers=2, + t2u_decoder_layers=2, + t2u_encoder_ffn_dim=6, + t2u_decoder_ffn_dim=6, + num_heads=2, + vocoder_num_spkrs=5, + vocoder_num_langs=5, + upsample_initial_channel=32, + unit_embed_dim=25, + spkr_embed_dim=6, + lang_embed_dim=6, + num_conv_pos_embeddings=8, + unit_hifi_gan_vocab_size=20, + t2u_num_langs=0, + t2u_max_new_tokens=25, + t2u_offset_tgt_lang=0, + vocoder_offset=0, + ): + self.parent = parent + self.input_modality = input_modality + + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + self.vocab_size = vocab_size + self.t2u_vocab_size = t2u_vocab_size + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.intermediate_size = intermediate_size + self.max_position_embeddings = max_position_embeddings + self.encoder_layers = encoder_layers + self.decoder_layers = decoder_layers + self.encoder_ffn_dim = encoder_ffn_dim + self.decoder_ffn_dim = decoder_ffn_dim + self.t2u_encoder_layers = t2u_encoder_layers + self.t2u_decoder_layers = t2u_decoder_layers + self.t2u_encoder_ffn_dim = t2u_encoder_ffn_dim + self.t2u_decoder_ffn_dim = t2u_decoder_ffn_dim + self.num_heads = num_heads + self.num_attention_heads = num_heads + + self.vocoder_num_spkrs = vocoder_num_spkrs + self.vocoder_num_langs = vocoder_num_langs + self.upsample_initial_channel = upsample_initial_channel + self.unit_embed_dim = unit_embed_dim + self.spkr_embed_dim = spkr_embed_dim + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.lang_embed_dim = lang_embed_dim + + self.max_new_tokens = max_new_tokens + + self.unit_hifi_gan_vocab_size = unit_hifi_gan_vocab_size + self.t2u_num_langs = t2u_num_langs + self.t2u_max_new_tokens = t2u_max_new_tokens + self.t2u_offset_tgt_lang = t2u_offset_tgt_lang + self.vocoder_offset = vocoder_offset + + def prepare_config_and_inputs(self): + if self.input_modality == "text": + inputs = ids_tensor([self.batch_size, self.seq_length], self.vocab_size - 1) + else: + inputs = ids_tensor([self.batch_size, self.seq_length, 160], self.vocab_size - 1).float() + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size - 1) + + lm_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + + config = self.get_config() + + return config, inputs, decoder_input_ids, input_mask, lm_labels + + def get_config(self): + return SeamlessM4TConfig( + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + t2u_vocab_size=self.t2u_vocab_size, + hidden_size=self.hidden_size, + speech_encoder_layers=self.num_heads, + speech_encoder_intermediate_size=self.intermediate_size, + max_position_embeddings=self.max_position_embeddings, + encoder_layers=self.encoder_layers, + decoder_layers=self.decoder_layers, + encoder_ffn_dim=self.encoder_ffn_dim, + decoder_ffn_dim=self.decoder_ffn_dim, + t2u_encoder_layers=self.t2u_encoder_layers, + t2u_decoder_layers=self.t2u_decoder_layers, + t2u_encoder_ffn_dim=self.t2u_encoder_ffn_dim, + t2u_decoder_ffn_dim=self.t2u_decoder_ffn_dim, + num_attention_heads=self.num_heads, + encoder_attention_heads=self.num_heads, + decoder_attention_heads=self.num_heads, + t2u_encoder_attention_heads=self.num_heads, + t2u_decoder_attention_heads=self.num_heads, + speech_encoder_attention_heads=self.num_heads, + unit_hifigan_vocab_vise=self.t2u_vocab_size, + vocoder_num_spkrs=self.vocoder_num_spkrs, + vocoder_num_langs=self.vocoder_num_langs, + upsample_initial_channel=self.upsample_initial_channel, + unit_embed_dim=self.unit_embed_dim, + spkr_embed_dim=self.spkr_embed_dim, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + lang_embed_dim=self.lang_embed_dim, + max_new_tokens=self.max_new_tokens, + unit_hifi_gan_vocab_size=self.unit_hifi_gan_vocab_size, + t2u_num_langs=self.t2u_num_langs, + t2u_max_new_tokens=self.t2u_max_new_tokens, + t2u_offset_tgt_lang=self.t2u_offset_tgt_lang, + vocoder_offset=self.vocoder_offset, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + decoder_input_ids, + input_mask, + lm_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + decoder_input_ids, + input_mask, + lm_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model(self, config, input_ids, decoder_input_ids, input_mask, labels): + model = SeamlessM4TModel(config=config) + model.to(torch_device) + model.eval() + if self.input_modality == "text": + result = model(input_ids=input_ids, attention_mask=input_mask, decoder_input_ids=decoder_input_ids) + result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + else: + result = model(input_features=input_ids, attention_mask=input_mask, decoder_input_ids=decoder_input_ids) + result = model(input_features=input_ids, decoder_input_ids=decoder_input_ids) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + decoder_output = result.logits + decoder_past = result.past_key_values + encoder_output = result.encoder_last_hidden_state + + if self.input_modality == "text": + seq_length = self.seq_length + else: + # if speech, expected length has been subsampled. + seq_length = model._compute_sub_sample_lengths_from_attention_mask(input_mask).max().item() + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, seq_length, self.hidden_size)) + self.parent.assertEqual(decoder_output.size(), (self.batch_size, decoder_input_ids.shape[1], self.vocab_size)) + # There should be `num_layers` key value embeddings stored in decoder_past + self.parent.assertEqual(len(decoder_past), config.decoder_layers) + # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple + self.parent.assertEqual(len(decoder_past[0]), 4) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + decoder_input_ids, + input_mask, + lm_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + model = SeamlessM4TModel(config=config) + model.to(torch_device) + model.eval() + + # make sure no pad token in decoder_input_ids + decoder_input_ids = torch.clamp(decoder_input_ids, config.pad_token_id + 1) + + # first forward pass + outputs = model( + input_ids, decoder_input_ids=decoder_input_ids, decoder_attention_mask=input_mask, use_cache=True + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([decoder_input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + input_ids, + decoder_input_ids=next_input_ids, + decoder_attention_mask=next_attention_mask, + output_hidden_states=True, + ) + output_from_no_past = output_from_no_past["decoder_hidden_states"][0] + output_from_past = model( + input_ids, + decoder_input_ids=next_tokens, + decoder_attention_mask=next_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["decoder_hidden_states"][0] + + # 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)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + decoder_input_ids, + input_mask, + lm_labels, + ) = config_and_inputs + + input_name = "input_ids" if self.input_modality == "text" else "input_features" + + inputs_dict = { + input_name: input_ids, + "attention_mask": input_mask, + "decoder_input_ids": decoder_input_ids, + "labels": lm_labels, + } + return config, inputs_dict + + +@require_torch +class SeamlessM4TModelWithSpeechInputTest(ModelTesterMixin, unittest.TestCase): + is_encoder_decoder = True + fx_compatible = False + test_missing_keys = False + test_pruning = False + test_model_parallel = False + test_resize_embeddings = False + test_headmasking = False + test_torchscript = False + + all_model_classes = ( + ( + SeamlessM4TModel, + SeamlessM4TForSpeechToSpeech, + SeamlessM4TForSpeechToText, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (SeamlessM4TForSpeechToText,) if is_torch_available() else () + + input_name = "input_features" + + def setUp(self): + self.model_tester = SeamlessM4TModelTester(self, input_modality="speech") + self.config_tester = ConfigTester(self, config_class=SeamlessM4TConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in SEAMLESS_M4T_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SeamlessM4TModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def _get_input_ids_and_config(self, batch_size=2): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_ids = inputs_dict[self.input_name] + + # cut to half length & take max batch_size 3 + sequence_length = input_ids.shape[-1] // 2 + input_ids = input_ids[:batch_size, :sequence_length] + + # generate max 3 tokens + max_length = input_ids.shape[-1] + 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()` + if isinstance(config.eos_token_id, int): + config.eos_token_id = [config.eos_token_id] + config.pad_token_id = config.eos_token_id[0] + + attention_mask = torch.ones(input_ids.shape[:2], dtype=torch.long)[:batch_size, :sequence_length] + + return config, input_ids.float(), attention_mask, max_length + + @staticmethod + def _get_encoder_outputs( + model, input_ids, attention_mask, output_attentions=None, output_hidden_states=None, num_interleave=1 + ): + 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 = ( + torch.zeros(input_ids.shape[:2], dtype=torch.int64, layout=input_ids.layout, device=input_ids.device) + + model._get_decoder_start_token_id() + ) + attention_mask = None + return encoder_outputs, input_ids, attention_mask + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "pos_bias_v", + "pos_bias_u", + "pointwise_conv1", + "pointwise_conv2", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "objective.weight", + "adapter", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + @unittest.skip(reason="SeamlessM4TSpeechEncoder doesn't have an embedding layer") + def test_inputs_embeds(self): + pass + + @unittest.skip( + reason="Expected missing keys serve when using SeamlessM4TForXXX.from_pretrained from a checkpoint saved by SeamlessM4TModel.save_pretrained." + ) + def test_model_weights_reload_no_missing_tied_weights(self): + pass + + @unittest.skip( + reason="SeamlessM4TModel is base class but has actually a bigger architecture than seamlessM4T task-specific models." + ) + def test_save_load_fast_init_to_base(self): + pass + + @unittest.skip(reason="SeamlessM4TModel can takes input_ids or input_features") + def test_forward_signature(self): + pass + + @unittest.skip(reason="SeamlessM4T has no base model") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + def test_attention_outputs(self): + # expected length is subsampled so need to change a bit this test + if not self.has_attentions: + self.skipTest(reason="Model does not output attentions") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + # no more chunk_length test + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + out_len = len(outputs) + + if self.is_encoder_decoder: + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + + sub_sampled_length = ( + model._compute_sub_sample_lengths_from_attention_mask(inputs_dict["attention_mask"]).max().item() + ) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + sub_sampled_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + elif self.is_encoder_decoder: + added_hidden_states = 2 + else: + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + +@require_torch +class SeamlessM4TModelWithTextInputTest( + ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase +): + is_encoder_decoder = True + fx_compatible = False + test_missing_keys = False + test_pruning = False + test_model_parallel = False + test_resize_embeddings = True + test_headmasking = False + test_torchscript = False + + all_model_classes = ( + ( + SeamlessM4TModel, + SeamlessM4TForTextToSpeech, + SeamlessM4TForTextToText, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (SeamlessM4TForTextToText,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "automatic-speech-recognition": SeamlessM4TForSpeechToText, + "conversational": SeamlessM4TForTextToText, + "feature-extraction": SeamlessM4TModel, + "summarization": SeamlessM4TForTextToText, + "text-to-audio": SeamlessM4TForTextToSpeech, + "text2text-generation": SeamlessM4TForTextToText, + "translation": SeamlessM4TForTextToText, + } + if is_torch_available() + else {} + ) + + def setUp(self): + self.model_tester = SeamlessM4TModelTester(self, input_modality="text") + self.config_tester = ConfigTester(self, config_class=SeamlessM4TConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in SEAMLESS_M4T_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SeamlessM4TModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "pos_bias_v", + "pos_bias_u", + "pointwise_conv1", + "pointwise_conv2", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "objective.weight", + "adapter", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + @unittest.skip( + reason="Expected missing keys serve when using SeamlessM4TForXXX.from_pretrained from a checkpoint saved by SeamlessM4TModel.save_pretrained." + ) + def test_model_weights_reload_no_missing_tied_weights(self): + pass + + @unittest.skip(reason="SeamlessM4TModel can take input_ids or input_features") + def test_forward_signature(self): + pass + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + @unittest.skip( + reason="SeamlessM4TModel is base class but has actually a bigger architecture than seamlessM4T task-specific models." + ) + def test_save_load_fast_init_to_base(self): + pass + + @unittest.skip(reason="SeamlessM4T has no base model") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + +@require_torch +class SeamlessM4TGenerationTest(unittest.TestCase): + # test that non-standard generation works + # test generation of: SeamlessM4TModel, SeamlessM4TForSpeechToSpeech, SeamlessM4TForSpeechToText, SeamlessM4TForTextToSpeech + + def setUp(self): + self.speech_model_tester = SeamlessM4TModelTester(self, input_modality="speech") + self.text_model_tester = SeamlessM4TModelTester(self, input_modality="text") + self.tmpdirname = tempfile.mkdtemp() + + def update_generation(self, model): + lang_code_to_id = { + "fra": 4, + "eng": 4, + } + + generation_config = copy.deepcopy(model.generation_config) + + generation_config.__setattr__("text_decoder_lang_to_code_id", lang_code_to_id) + generation_config.__setattr__("t2u_lang_code_to_id", lang_code_to_id) + generation_config.__setattr__("vocoder_lang_code_to_id", lang_code_to_id) + + generation_config._from_model_config = False + + model.generation_config = generation_config + + def prepare_text_input(self): + config, inputs, decoder_input_ids, input_mask, lm_labels = self.text_model_tester.prepare_config_and_inputs() + + input_dict = { + "input_ids": inputs, + "attention_mask": input_mask, + "tgt_lang": "eng", + "num_beams": 2, + "do_sample": True, + } + + return config, input_dict + + def prepare_speech_input(self): + config, inputs, decoder_input_ids, input_mask, lm_labels = self.speech_model_tester.prepare_config_and_inputs() + + input_dict = { + "input_features": inputs, + "attention_mask": input_mask, + "tgt_lang": "fra", + "num_beams": 2, + "do_sample": True, + } + + return config, input_dict + + def prepare_speech_and_text_input(self): + config, inputs, decoder_input_ids, input_mask, lm_labels = self.speech_model_tester.prepare_config_and_inputs() + + input_speech = { + "input_features": inputs, + "attention_mask": input_mask, + "tgt_lang": "fra", + "num_beams": 2, + "do_sample": True, + } + + config, inputs, decoder_input_ids, input_mask, lm_labels = self.text_model_tester.prepare_config_and_inputs() + + input_text = { + "input_ids": inputs, + "attention_mask": input_mask, + "tgt_lang": "eng", + "num_beams": 2, + "do_sample": True, + } + return config, input_speech, input_text + + def factory_generation_speech_test(self, model, inputs): + set_seed(0) + output = model.generate(**inputs) + return output + + def test_speech_generation(self): + config, input_speech, input_text = self.prepare_speech_and_text_input() + + model = SeamlessM4TModel(config=config) + self.update_generation(model) + model.save_pretrained(self.tmpdirname) + model.to(torch_device) + model.eval() + + output_original_text = self.factory_generation_speech_test(model, input_text) + output_original_speech = self.factory_generation_speech_test(model, input_speech) + + state_dict = model.state_dict() + + text_model = SeamlessM4TForTextToSpeech.from_pretrained(self.tmpdirname) + self.update_generation(text_model) + text_model.to(torch_device) + text_model.eval() + + output_text = self.factory_generation_speech_test(model, input_text) + + speech_model = SeamlessM4TForSpeechToSpeech.from_pretrained(self.tmpdirname) + self.update_generation(speech_model) + speech_model.to(torch_device) + speech_model.eval() + + for name, tensor in speech_model.state_dict().items(): + right_tensor = state_dict.get(name) + self.assertEqual(tensor.tolist(), right_tensor.tolist(), f"Tensor {name}") + + output_speech = self.factory_generation_speech_test(model, input_speech) + + # test same text output from input text + self.assertListEqual(output_original_text[0].ravel().tolist(), output_text[0].ravel().tolist()) + self.assertListEqual(output_original_text[1].ravel().tolist(), output_text[1].ravel().tolist()) + + # test same speech output from input text + # assertTrue because super long list makes this hang in case of failure + self.assertTrue( + output_original_speech[0].ravel().tolist() == output_speech[0].ravel().tolist(), + "Speech generated was different", + ) + self.assertTrue( + output_original_speech[1].ravel().tolist() == output_speech[1].ravel().tolist(), + "Speech generated was different", + ) + + def test_text_generation(self): + config, input_speech, input_text = self.prepare_speech_and_text_input() + + # to return speech + input_speech["generate_speech"] = False + input_text["generate_speech"] = False + + model = SeamlessM4TModel(config=config) + self.update_generation(model) + model.save_pretrained(self.tmpdirname) + model.to(torch_device) + model.eval() + + output_original_text = self.factory_generation_speech_test(model, input_text) + output_original_speech = self.factory_generation_speech_test(model, input_speech) + + # other models don't need it + input_speech.pop("generate_speech") + input_text.pop("generate_speech") + + state_dict = model.state_dict() + + text_model = SeamlessM4TForTextToText.from_pretrained(self.tmpdirname) + self.update_generation(text_model) + text_model.to(torch_device) + text_model.eval() + + for name, tensor in text_model.state_dict().items(): + right_tensor = state_dict.get(name) + self.assertEqual(tensor.tolist(), right_tensor.tolist()) + + output_text = self.factory_generation_speech_test(text_model, input_text) + + speech_model = SeamlessM4TForSpeechToText.from_pretrained(self.tmpdirname) + + for name, tensor in speech_model.state_dict().items(): + right_tensor = state_dict.get(name) + self.assertEqual(tensor.tolist(), right_tensor.tolist(), f"Tensor {name}") + + self.update_generation(speech_model) + speech_model.to(torch_device) + speech_model.eval() + + output_speech = self.factory_generation_speech_test(speech_model, input_speech) + + # test same text output from input text + self.assertListEqual(output_original_text[0].ravel().tolist(), output_text.ravel().tolist()) + + # test same speech output from input text + self.assertListEqual(output_original_speech[0].ravel().tolist(), output_speech.ravel().tolist()) + + def test_generation(self): + config, input_speech, input_text = self.prepare_speech_and_text_input() + + input_speech["num_beams"] = 3 + input_speech["do_sample"] = True + input_speech["num_return_sequences"] = 3 + + input_text["num_beams"] = 3 + input_text["do_sample"] = True + input_text["num_return_sequences"] = 3 + + for model_class in [SeamlessM4TForSpeechToSpeech, SeamlessM4TForSpeechToText, SeamlessM4TModel]: + model = model_class(config=config) + self.update_generation(model) + model.to(torch_device) + model.eval() + + output = model.generate(**input_speech) + output = output[0] if isinstance(output, tuple) else output + + self.assertEqual(output.shape[0], 3 * input_speech["input_features"].shape[0]) + + for model_class in [SeamlessM4TForTextToSpeech, SeamlessM4TForTextToText, SeamlessM4TModel]: + model = model_class(config=config) + self.update_generation(model) + model.to(torch_device) + model.eval() + + output = model.generate(**input_text) + + output = output[0] if isinstance(output, tuple) else output + + self.assertEqual(output.shape[0], 3 * input_text["input_ids"].shape[0]) + + +@require_torch +class SeamlessM4TModelIntegrationTest(unittest.TestCase): + repo_id = "facebook/hf-seamless-m4t-medium" + + def assertListAlmostEqual(self, list1, list2, tol=1e-3): + self.assertEqual(len(list1), len(list2)) + for a, b in zip(list1, list2): + self.assertAlmostEqual(a, b, delta=tol) + + @cached_property + def processor(self): + return SeamlessM4TProcessor.from_pretrained(self.repo_id) + + @cached_property + def input_text(self): + # corresponds to "C'est un test." with seamlessM4T_medium checkpoint + + input_ids = torch.tensor([[256057, 152, 248116, 354, 159, 7356, 248075, 3]]) # fmt: skip + + input_ids = input_ids.to(torch_device) + + attention_mask = torch.ones_like(input_ids).to(torch_device) + + inputs = { + "attention_mask": attention_mask, + "input_ids": input_ids, + } + + return inputs + + @cached_property + def input_audio(self): + set_seed(0) + seq_len = 20000 + sampling_rate = 16000 + input_features = torch.rand((2, seq_len)) + + return self.processor(audios=[input_features.tolist()], sampling_rate=sampling_rate, return_tensors="pt").to( + torch_device + ) + + def factory_test_task(self, class1, class2, inputs, class1_kwargs, class2_kwargs): + model1 = class1.from_pretrained(self.repo_id).to(torch_device) + model2 = class2.from_pretrained(self.repo_id).to(torch_device) + + set_seed(0) + output_1 = model1.generate(**inputs, **class1_kwargs) + set_seed(0) + output_2 = model2.generate(**inputs, **class2_kwargs) + + for key in output_1: + if isinstance(output_1[key], torch.Tensor): + if len(output_1[key].shape) == 0: + self.assertEqual(output_1[key].item(), output_2[key].item()) + else: + self.assertListAlmostEqual(output_1[key].squeeze().tolist(), output_2[key].squeeze().tolist()) + + @slow + def test_to_eng_text(self): + model = SeamlessM4TModel.from_pretrained(self.repo_id).to(torch_device) + + # test text - tgt lang: eng + + expected_text_tokens = [3, 256047, 3291, 248116, 248066, 9, 7356, 248075, 3] # fmt: skip + + # fmt: off + expected_unit_tokens = [ + 2,10051,8980,8212,949,1270,4311,1123,5918,2333,5311,3882,2415,5284,1123,612,8816,6370,5386,7334,4345,5645, + 9437,5748,1378,9818,4319,7968,7375,2909,9119,5151,8728,5335,3896,4013,8939,8885,6048,9530,3167,5833,1072,693, + 431,9867,364,7909,4608,5938,1889,9984,7947,4944,6171,3767,9861,9169,1187,8365,4571,7635,7784,7635,800,2393, + 32,5380,5852,8289,2530,2762,1833,2056,3553,4641,3553,5683,370,2288,1344,1518,7534,703,8359,7699,2 + ] + # fmt: on + + expected_wav_slice = [-3e-05, -0.0004, -0.00037, -0.00013, -6e-05, 0.00012, -0.00016, 0.00025, 7e-05, -3e-05] # fmt: skip + + set_seed(0) + output = model.generate(**self.input_text, num_beams=1, tgt_lang="eng", return_intermediate_token_ids=True) + + self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) + # FOR NOW, only first units correspondance + self.assertListEqual(expected_unit_tokens[:10], output.unit_sequences.squeeze().tolist()[:10]) + + self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) + + @slow + def test_to_swh_text(self): + model = SeamlessM4TModel.from_pretrained(self.repo_id).to(torch_device) + + # test text - tgt lang: swh + + expected_text_tokens = [3, 256168, 1665, 188589, 7040, 248075, 3] # fmt: skip + + # fmt: off + expected_unit_tokens = [ + 2,10071,5729,9995,3089,7546,1204,1721,2532,4340,5623,3496,432,7730,9096,7677,3143,8211,6447,8399,4248,3565, + 4529,7700,9308,217,6476,3485,9667,3194,8476,4923,5593,1148,4466,7416,4872,463,4872,253,2348,4640,3450,2133, + 6318,2806,817,7613,2698,6563,8712,8344,9286,6878,6387,4281,6387,640,6387,3200,640,8355,640,6708,979,1738,2 + ] + # fmt: on + + expected_wav_slice = [1e-05, -7e-05, -4e-05, -4e-05, -6e-05, -9e-05, -0.0001, -2e-05, -7e-05, -2e-05] # fmt: skip + + set_seed(0) + output = model.generate(**self.input_text, num_beams=1, tgt_lang="swh", return_intermediate_token_ids=True) + + self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) + self.assertListEqual(expected_unit_tokens[:10], output.unit_sequences.squeeze().tolist()[:10]) + + self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) + + @slow + def test_to_rus_speech(self): + model = SeamlessM4TModel.from_pretrained(self.repo_id).to(torch_device) + + # test audio - tgt lang: rus + + expected_text_tokens = [3, 256147, 1197, 73565, 3413, 537, 233331, 248075, 3] # fmt: skip + + # fmt: off + expected_unit_tokens = [ + 2, 10067, 5729, 4798, 9631, 8378, 4446, 2393, 6901, 5983, 2817, 4629, 8532, 1991, 2931, 8576, 8857, 5936, 4317, + 9000, 7740, 7995, 1225, 5980, 6094, 1420, 5373, 8771, 6600, 4487, 7029, 3630, 6740, 4870, 1483, 3003, 5585, 5511, + 7465, 3222, 32, 6272, 1950, 3120, 5368, 639, 3713, 5935, 7943, 567, 6129, 6822, 1226, 5063, 9878, 7756, 8825, 1078, 5943, + 457, 9282, 9668, 817, 7613, 2698, 6563, 8712, 8704, 9286, 8704, 6387, 4281, 6387, 640, 3200, 6387, 640, 8355, 6708, 979, 1738, 2 + ] + # fmt: on + + expected_wav_slice = [0.00013, 0.00012, 0.00014, 3e-05, 0.0, -6e-05, -0.00018, -0.00016, -0.00021, -0.00018] # fmt: skip + + set_seed(0) + output = model.generate(**self.input_audio, num_beams=1, tgt_lang="rus", return_intermediate_token_ids=True) + + self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) + self.assertListEqual(expected_unit_tokens[:10], output.unit_sequences.squeeze().tolist()[:10]) + + self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) + + @slow + def test_text_to_text_model(self): + kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True, "generate_speech": False} + kwargs2 = { + "tgt_lang": "eng", + "output_hidden_states": True, + "return_dict_in_generate": True, + "output_scores": True, + } + self.factory_test_task(SeamlessM4TModel, SeamlessM4TForTextToText, self.input_text, kwargs1, kwargs2) + + @slow + def test_speech_to_text_model(self): + kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True, "generate_speech": False} + kwargs2 = { + "tgt_lang": "eng", + "output_hidden_states": True, + "return_dict_in_generate": True, + "output_scores": True, + } + self.factory_test_task(SeamlessM4TModel, SeamlessM4TForSpeechToText, self.input_audio, kwargs1, kwargs2) + + @slow + def test_speech_to_speech_model(self): + kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True} + self.factory_test_task(SeamlessM4TModel, SeamlessM4TForSpeechToSpeech, self.input_audio, kwargs1, kwargs1) + + @slow + def test_text_to_speech_model(self): + kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True} + + self.factory_test_task(SeamlessM4TModel, SeamlessM4TForTextToSpeech, self.input_text, kwargs1, kwargs1) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_processor_seamless_m4t.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_processor_seamless_m4t.py new file mode 100644 index 0000000000000000000000000000000000000000..7beefb16bda7ea5d5826c5492a734ee57b34131b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_processor_seamless_m4t.py @@ -0,0 +1,126 @@ +# Copyright 2023 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 shutil +import tempfile +import unittest + +from transformers import SeamlessM4TFeatureExtractor, SeamlessM4TProcessor +from transformers.models.seamless_m4t import ( + SeamlessM4TTokenizer, + SeamlessM4TTokenizerFast, +) +from transformers.testing_utils import require_torch + +from .test_feature_extraction_seamless_m4t import floats_list + + +@require_torch +class SeamlessM4TProcessorTest(unittest.TestCase): + def setUp(self): + self.checkpoint = "facebook/hf-seamless-m4t-medium" + self.tmpdirname = tempfile.mkdtemp() + + def get_tokenizer(self, **kwargs): + return SeamlessM4TTokenizer.from_pretrained(self.checkpoint, **kwargs) + + def get_feature_extractor(self, **kwargs): + return SeamlessM4TFeatureExtractor.from_pretrained(self.checkpoint, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_save_load_pretrained_default(self): + tokenizer = self.get_tokenizer() + feature_extractor = self.get_feature_extractor() + + processor = SeamlessM4TProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + processor.save_pretrained(self.tmpdirname) + processor = SeamlessM4TProcessor.from_pretrained(self.tmpdirname) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) + tokenizer_instance = isinstance(processor.tokenizer, SeamlessM4TTokenizerFast) or isinstance( + processor.tokenizer, SeamlessM4TTokenizer + ) + self.assertTrue(tokenizer_instance) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string()) + self.assertIsInstance(processor.feature_extractor, SeamlessM4TFeatureExtractor) + + def test_save_load_pretrained_additional_features(self): + processor = SeamlessM4TProcessor( + tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor() + ) + processor.save_pretrained(self.tmpdirname) + tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)") + feature_extractor_add_kwargs = self.get_feature_extractor(do_normalize=False, padding_value=1.0) + + processor = SeamlessM4TProcessor.from_pretrained( + self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0 + ) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.feature_extractor, SeamlessM4TFeatureExtractor) + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) + + tokenizer_instance = isinstance(processor.tokenizer, SeamlessM4TTokenizerFast) or isinstance( + processor.tokenizer, SeamlessM4TTokenizer + ) + self.assertTrue(tokenizer_instance) + + # Copied from test.models.whisper.test_processor_whisper.WhisperProcessorTest.test_feature_extractor with Whisper->SeamlessM4T + def test_feature_extractor(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SeamlessM4TProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + raw_speech = floats_list((3, 1000)) + + input_feat_extract = feature_extractor(raw_speech, return_tensors="np") + input_processor = processor(audios=raw_speech, return_tensors="np") + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + # Copied from test.models.whisper.test_processor_whisper.WhisperProcessorTest.test_tokenizer with Whisper->SeamlessM4T + def test_tokenizer(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SeamlessM4TProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + input_str = "This is a test string" + + encoded_processor = processor(text=input_str) + + encoded_tok = tokenizer(input_str) + + for key in encoded_tok.keys(): + self.assertListEqual(encoded_tok[key], encoded_processor[key]) + + # Copied from test.models.whisper.test_processor_whisper.WhisperProcessorTest.test_tokenizer_decode with Whisper->SeamlessM4T + def test_tokenizer_decode(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SeamlessM4TProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] + + decoded_processor = processor.batch_decode(predicted_ids) + decoded_tok = tokenizer.batch_decode(predicted_ids) + + self.assertListEqual(decoded_tok, decoded_processor) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_tokenization_seamless_m4t.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_tokenization_seamless_m4t.py new file mode 100644 index 0000000000000000000000000000000000000000..7752156eab64482b8cc42aa52ea6e024e742e19c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t/test_tokenization_seamless_m4t.py @@ -0,0 +1,668 @@ +# Copyright 2022 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 tempfile +import unittest + +from transformers import ( + SPIECE_UNDERLINE, + AddedToken, + BatchEncoding, + PreTrainedTokenizerFast, + SeamlessM4TTokenizer, + SeamlessM4TTokenizerFast, + is_torch_available, +) +from transformers.testing_utils import ( + get_tests_dir, + nested_simplify, + require_sentencepiece, + require_tokenizers, + require_torch, +) + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + + +if is_torch_available(): + from transformers.models.m2m_100.modeling_m2m_100 import shift_tokens_right + +EN_CODE = 256047 +RO_CODE = 256145 + +SMALL_TRAINING_CORPUS = [ + ["This is the first sentence.", "This is the second one."], + ["This sentence (contains #) over symbols and numbers 12 3.", "But not this one."], +] + + +@require_sentencepiece +@require_tokenizers +class SeamlessM4TTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = SeamlessM4TTokenizer + rust_tokenizer_class = SeamlessM4TTokenizerFast + test_rust_tokenizer = True + test_sentencepiece = True + from_pretrained_kwargs = {} + + def setUp(self): + super().setUp() + + # We have a SentencePiece fixture for testing + tokenizer = SeamlessM4TTokenizer(SAMPLE_VOCAB, keep_accents=True) + tokenizer.save_pretrained(self.tmpdirname) + + def test_full_tokenizer(self): + tokenizer = SeamlessM4TTokenizer(SAMPLE_VOCAB, keep_accents=True) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "é", + ".", + ], + ) + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual( + ids, + [ + value + tokenizer.fairseq_offset + for value in [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] + ], + ) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual( + back_tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "", + ".", + ], + ) + + def test_maximum_encoding_length_single_input(self): + tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20) + + sequence = tokenizer.encode(seq_0, add_special_tokens=False) + total_length = len(sequence) + + self.assertGreater( + total_length, 4, "Issue with the testing sequence, please update it, it's too short" + ) + + # Test with max model input length + model_max_length = tokenizer.model_max_length + self.assertEqual(model_max_length, 100) + seq_1 = seq_0 * model_max_length + + sequence1 = tokenizer(seq_1, add_special_tokens=False) + total_length1 = len(sequence1["input_ids"]) + self.assertGreater( + total_length1, + model_max_length, + "Issue with the testing sequence, please update it, it's too short", + ) + + # Simple + padding_strategies = ( + [False, True, "longest"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False] + ) + for padding_state in padding_strategies: + with self.subTest(f"Padding: {padding_state}"): + for truncation_state in [True, "longest_first", "only_first"]: + with self.subTest(f"Truncation: {truncation_state}"): + output = tokenizer(seq_1, padding=padding_state, truncation=truncation_state) + self.assertEqual(len(output["input_ids"]), model_max_length) + + output = tokenizer([seq_1], padding=padding_state, truncation=truncation_state) + self.assertEqual(len(output["input_ids"][0]), model_max_length) + + # Simple with no truncation + # Reset warnings + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer(seq_1, padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer([seq_1], padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"][0]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + # Overflowing tokens + stride = 2 + + # modify padding because it's activated by default in seamlessM4T + information = tokenizer( + seq_0, + max_length=total_length - 2, + add_special_tokens=False, + stride=stride, + truncation="longest_first", + return_overflowing_tokens=True, + padding=False, + # add_prefix_space=False, + ) + + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + truncated_sequence = information["input_ids"][0] + overflowing_tokens = information["input_ids"][1] + self.assertEqual(len(information["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), total_length - 2) + self.assertEqual(truncated_sequence, sequence[:-2]) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :]) + else: + truncated_sequence = information["input_ids"] + overflowing_tokens = information["overflowing_tokens"] + + self.assertEqual(len(truncated_sequence), total_length - 2) + self.assertEqual(truncated_sequence, sequence[:-2]) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :]) + + @unittest.skip("By defaults, uses pad_to_multiple_of which breaks the test") + def test_maximum_encoding_length_pair_input(self): + pass + + def test_padding_to_multiple_of(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.pad_token is None: + self.skipTest("No padding token.") + else: + empty_tokens = tokenizer("", padding=True, pad_to_multiple_of=8) + normal_tokens = tokenizer("This is a sample input", padding=True, pad_to_multiple_of=8) + for key, value in empty_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # default to padding=True so need to precise which padding is called + normal_tokens = tokenizer("This", pad_to_multiple_of=8, padding=False) + for key, value in normal_tokens.items(): + self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # Should also work with truncation + normal_tokens = tokenizer("This", padding=True, truncation=True, pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # truncation to something which is not a multiple of pad_to_multiple_of raises an error + self.assertRaises( + ValueError, + tokenizer.__call__, + "This", + padding=True, + truncation=True, + max_length=12, + pad_to_multiple_of=8, + ) + + @require_torch + def test_prepare_seq2seq_batch(self): + if not self.test_seq2seq: + return + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Longer text that will definitely require truncation. + src_text = [ + " UN Chief Says There Is No Military Solution in Syria", + " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for" + " Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons" + " will only worsen the violence and misery for millions of people.", + ] + tgt_text = [ + "Şeful ONU declară că nu există o soluţie militară în Siria", + "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al" + ' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi' + " că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", + ] + try: + batch = tokenizer.prepare_seq2seq_batch( + src_texts=src_text, + tgt_texts=tgt_text, + max_length=3, + max_target_length=10, + return_tensors="pt", + src_lang="eng", + tgt_lang="ron", + pad_to_multiple_of=None, + ) + except NotImplementedError: + return + self.assertEqual(batch.input_ids.shape[1], 3) + self.assertEqual(batch.labels.shape[1], 10) + + # TODO: not working for tgt_text + # max_target_length will default to max_length if not specified + batch = tokenizer.prepare_seq2seq_batch( + src_texts=src_text, + tgt_texts=tgt_text, + max_length=4, + return_tensors="pt", + pad_to_multiple_of=None, + ) + self.assertEqual(batch.input_ids.shape[1], 4) + self.assertEqual(batch.labels.shape[1], 4) + + batch_encoder_only = tokenizer.prepare_seq2seq_batch( + src_texts=src_text, + max_length=4, + max_target_length=10, + return_tensors="pt", + pad_to_multiple_of=None, + ) + self.assertEqual(batch_encoder_only.input_ids.shape[1], 4) + self.assertEqual(batch_encoder_only.attention_mask.shape[1], 4) + self.assertNotIn("decoder_input_ids", batch_encoder_only) + + @unittest.skip("Unfortunately way too slow to build a BPE with SentencePiece.") + def test_save_slow_from_fast_and_reload_fast(self): + pass + + # Copied from tests.models.nllb.test_tokenization_nllb.NllbTokenizationTest.test_special_tokens_initialization + def test_special_tokens_initialization(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + added_tokens = [AddedToken("", lstrip=True)] + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, additional_special_tokens=added_tokens, **kwargs + ) + r_output = tokenizer_r.encode("Hey this is a token") + + special_token_id = tokenizer_r.encode("", add_special_tokens=False)[0] + + self.assertTrue(special_token_id in r_output) + + if self.test_slow_tokenizer: + tokenizer_cr = self.rust_tokenizer_class.from_pretrained( + pretrained_name, + additional_special_tokens=added_tokens, + **kwargs, # , from_slow=True <- unfortunately too slow to convert + ) + tokenizer_p = self.tokenizer_class.from_pretrained( + pretrained_name, additional_special_tokens=added_tokens, **kwargs + ) + + p_output = tokenizer_p.encode("Hey this is a token") + + cr_output = tokenizer_cr.encode("Hey this is a token") + + self.assertEqual(p_output, r_output) + self.assertEqual(cr_output, r_output) + self.assertTrue(special_token_id in p_output) + self.assertTrue(special_token_id in cr_output) + + @unittest.skip( + "encode_plus and batch_encode_plus are deprecated and __call__ do some processing, so we expect different results." + ) + def test_call(self): + pass + + def test_training_new_tokenizer(self): + # This feature only exists for fast tokenizers + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_rust_tokenizer() + new_tokenizer = tokenizer.train_new_from_iterator(SMALL_TRAINING_CORPUS, 100) + + # Test we can use the new tokenizer with something not seen during training + inputs = new_tokenizer(["This is the first sentence", "This sentence is different 🤗."]) + self.assertEqual(len(inputs["input_ids"]), 2) + decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True) + expected_result = "This is the first sentence" + + if tokenizer.backend_tokenizer.normalizer is not None: + expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result) + self.assertEqual(expected_result, decoded_input) + + # We check that the parameters of the tokenizer remained the same + # Check we have the same number of added_tokens for both pair and non-pair inputs. + # make sure it has the same prefix tokens first + new_tokenizer.tgt_lang = tokenizer.tgt_lang + tokenizer.tgt_lang = tokenizer.tgt_lang + self.assertEqual(tokenizer.num_special_tokens_to_add(False), new_tokenizer.num_special_tokens_to_add(False)) + self.assertEqual(tokenizer.num_special_tokens_to_add(True), new_tokenizer.num_special_tokens_to_add(True)) + + # Check we have the correct max_length for both pair and non-pair inputs. + self.assertEqual(tokenizer.max_len_single_sentence, new_tokenizer.max_len_single_sentence) + self.assertEqual(tokenizer.max_len_sentences_pair, new_tokenizer.max_len_sentences_pair) + + # Assert the set of special tokens match as we didn't ask to change them + self.assertSequenceEqual( + tokenizer.all_special_tokens_extended, + new_tokenizer.all_special_tokens_extended, + ) + + self.assertDictEqual(tokenizer.special_tokens_map, new_tokenizer.special_tokens_map) + + @unittest.skip("Fails because of the hack of adding in _tokenize") + def test_pickle_subword_regularization_tokenizer(self): + pass + + @unittest.skip("Fails because of the hack of adding in _tokenize") + def test_subword_regularization_tokenizer(self): + pass + + +@require_torch +@require_sentencepiece +@require_tokenizers +class SeamlessM4TDistilledIntegrationTest(unittest.TestCase): + checkpoint_name = "facebook/hf-seamless-m4t-medium" + src_text = [ + " UN Chief Says There Is No Military Solution in Syria", + """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", + ] + tgt_text = [ + "Şeful ONU declară că nu există o soluţie militară în Siria", + "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" + ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' + " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", + ] + + expected_src_tokens = [256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 3] # fmt: skip + + @classmethod + def setUpClass(cls): + cls.tokenizer: SeamlessM4TTokenizer = SeamlessM4TTokenizer.from_pretrained( + cls.checkpoint_name, src_lang="eng", tgt_lang="ron" + ) + # cls.pad_token_id = 1 + return cls + + def test_language_codes(self): + self.assertEqual(self.tokenizer.convert_tokens_to_ids("__ace_Latn__"), 256002) + self.assertEqual(self.tokenizer.convert_tokens_to_ids("__shn__"), 256152) + self.assertEqual(self.tokenizer.convert_tokens_to_ids("__eng__"), 256047) + self.assertEqual(self.tokenizer.convert_tokens_to_ids("__fra__"), 256057) + self.assertEqual(self.tokenizer.convert_tokens_to_ids("__quy__"), 256144) + + def test_tokenizer_tgt_lang(self): + ids = self.tokenizer(self.src_text, src_lang="fra").input_ids[0] + self.assertListEqual(self.expected_src_tokens[1:], ids[1 : len(self.expected_src_tokens)]) + self.assertEqual(256057, ids[0]) + + rest_ids = ids[len(self.expected_src_tokens) :] + self.assertListEqual([0] * len(rest_ids), rest_ids) + + ids = self.tokenizer(self.src_text, src_lang="__shn__").input_ids[0] + self.assertListEqual(self.expected_src_tokens[1:], ids[1 : len(self.expected_src_tokens)]) + self.assertEqual(256152, ids[0]) + + # Copied from tests.models.nllb.test_tokenization_nllb.NllbDistilledIntegrationTest.test_enro_tokenizer_decode_ignores_language_codes + def test_enro_tokenizer_decode_ignores_language_codes(self): + self.assertIn(RO_CODE, self.tokenizer.all_special_ids) + generated_ids = [RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047] # fmt: skip + + result = self.tokenizer.decode(generated_ids, skip_special_tokens=True) + expected_romanian = self.tokenizer.decode(generated_ids[1:], skip_special_tokens=True) + self.assertEqual(result, expected_romanian) + self.assertNotIn(self.tokenizer.eos_token, result) + + def test_enro_tokenizer_truncation(self): + src_text = ["this is gunna be a long sentence " * 20] + assert isinstance(src_text[0], str) + desired_max_length = 10 + ids = self.tokenizer(src_text, max_length=desired_max_length, truncation=True).input_ids[0] + self.assertEqual(ids[-1], 3) + self.assertEqual(ids[0], EN_CODE) + self.assertEqual(len(ids), desired_max_length) + + # Copied from tests.models.nllb.test_tokenization_nllb.NllbDistilledIntegrationTest.test_special_tokens_unaffacted_by_save_load with fairseq_tokens_to_ids->additional_special_tokens, Nllb->SeamlessM4T, Dict->List + def test_special_tokens_unaffacted_by_save_load(self): + tmpdirname = tempfile.mkdtemp() + original_special_tokens = self.tokenizer.additional_special_tokens + self.tokenizer.save_pretrained(tmpdirname) + new_tok = SeamlessM4TTokenizer.from_pretrained(tmpdirname) + self.assertListEqual(new_tok.additional_special_tokens, original_special_tokens) + + @require_torch + def test_enro_tokenizer_prepare_batch(self): + batch = self.tokenizer( + self.src_text, + text_target=self.tgt_text, + padding=True, + truncation=True, + max_length=len(self.expected_src_tokens), + pad_to_multiple_of=None, + return_tensors="pt", + ) + batch["decoder_input_ids"] = shift_tokens_right( + batch["labels"], self.tokenizer.pad_token_id, self.tokenizer.convert_tokens_to_ids("__ron__") + ) + + self.assertIsInstance(batch, BatchEncoding) + + self.assertEqual((2, 15), batch.input_ids.shape) + self.assertEqual((2, 15), batch.attention_mask.shape) + result = batch.input_ids.tolist()[0] + self.assertListEqual(self.expected_src_tokens, result) + self.assertEqual(RO_CODE, batch.decoder_input_ids[0, 0]) # EOS + # Test that special tokens are reset + self.assertEqual(self.tokenizer.prefix_tokens, [EN_CODE]) + self.assertEqual(self.tokenizer.suffix_tokens, [self.tokenizer.eos_token_id]) + + def test_seq2seq_max_length(self): + batch = self.tokenizer( + self.src_text, padding=True, truncation=True, max_length=3, return_tensors="pt", pad_to_multiple_of=None + ) + targets = self.tokenizer( + text_target=self.tgt_text, padding=True, truncation=True, max_length=10, return_tensors="pt" + ) + labels = targets["input_ids"] + batch["decoder_input_ids"] = shift_tokens_right( + labels, + self.tokenizer.pad_token_id, + decoder_start_token_id=self.tokenizer.convert_tokens_to_ids(self.tokenizer.tgt_lang), + ) + + self.assertEqual(batch.input_ids.shape[1], 3) + self.assertEqual(batch.decoder_input_ids.shape[1], 10) + + @require_torch + def test_tokenizer_translation(self): + inputs = self.tokenizer._build_translation_inputs( + "A test", return_tensors="pt", src_lang="eng", tgt_lang="fra" + ) + + self.assertEqual( + nested_simplify(inputs), + { + # A, test, EOS, en_XX + "input_ids": [[256047, 70, 7356, 3]], + "attention_mask": [[1, 1, 1, 1]], + # ar_AR + "forced_bos_token_id": 256057, + }, + ) + + +@require_sentencepiece +@require_tokenizers +class CommonSpmIntegrationTests(unittest.TestCase): + """ + A class that regroups important test to make sure that we properly handle the special tokens. + """ + + @classmethod + def setUpClass(cls): + tokenizer = SeamlessM4TTokenizer(SAMPLE_VOCAB, extra_ids=0, add_bos_token=False, legacy=False) + tokenizer.add_special_tokens({"additional_special_tokens": [AddedToken("", rstrip=False, lstrip=False)]}) + cls.tokenizer = tokenizer + return cls + + def test_add_dummy_prefix(self): + # make sure `'▁'` is prepended, and outputs match sp_model's + # `sentencepiece.NormalizerSpec.add_dummy_prefix` attribute + input_ids = self.tokenizer.encode(". Hello") + self.assertEqual(input_ids, [3, 1, 8, 5, 157, 87, 21, 3]) + sp_encode = self.tokenizer.sp_model.encode(". Hello") + + # [bos, lang_id, _] + offset_sp_encode + self.assertEqual(input_ids[:-1], [3, 1, 8] + [i + self.tokenizer.fairseq_offset for i in sp_encode]) + tokens = self.tokenizer.tokenize(". Hello") + self.assertEqual(tokens, ["▁", ".", "▁He", "ll", "o"]) + + tokens = self.tokenizer.tokenize("") + self.assertEqual(tokens, []) + self.assertEqual(tokens, self.tokenizer.sp_model.encode("", out_type=str)) + + tokens = self.tokenizer.tokenize(" ") + self.assertEqual(tokens, []) + self.assertEqual(tokens, self.tokenizer.sp_model.encode(" ", out_type=str)) + + tokens = self.tokenizer.tokenize("▁") + self.assertEqual(tokens, []) + self.assertEqual(tokens, self.tokenizer.sp_model.encode("▁", out_type=str)) + + def test_remove_extra_whitespaces(self): + # make sure the extra spaces are eaten. Since the sample vocab does not have + # `______`. sentencepiece.NormalizerSpec.remove_extra_whitespaces attribute is set to False + + input_ids = self.tokenizer.encode(" . Hello") + self.assertEqual(input_ids, [3, 1, 8, 5, 157, 87, 21, 3]) + sp_encode = self.tokenizer.sp_model.encode(" . Hello") + self.assertEqual([i - self.tokenizer.fairseq_offset for i in input_ids[2:-1]], [7] + sp_encode) + tokens = self.tokenizer.tokenize(" . Hello") + self.assertEqual(tokens, ["▁", ".", "▁He", "ll", "o"]) + + # `'▁'` is also a whitespace + input_ids = self.tokenizer.encode("▁He is not") + self.assertEqual(input_ids, [3, 1, 157, 47, 45, 3]) + tokens = self.tokenizer.tokenize("▁He is not") + sp_encode = [ + self.tokenizer.sp_model.piece_to_id("▁He"), + self.tokenizer.sp_model.piece_to_id("▁is"), + self.tokenizer.sp_model.piece_to_id("▁not"), + ] + self.assertEqual([i - self.tokenizer.fairseq_offset for i in input_ids[2:-1]], sp_encode) + self.assertEqual(tokens, ["▁He", "▁is", "▁not"]) # no extra space added + + input_ids = self.tokenizer.encode("▁He is not ▁He") + self.assertEqual(input_ids, [3, 1, 157, 47, 45, 2, 157, 3]) + tokens = self.tokenizer.tokenize("▁He is not ▁He") + self.assertEqual(tokens, ["▁He", "▁is", "▁not", "", "▁He"]) # spaces are eaten by spm + our strip + # make sure that the output after the extra id is the same as if + # extra_id was not there + input_ids = self.tokenizer.encode("▁He is not ▁He") + self.assertEqual(input_ids, [3, 1, 157, 47, 45, 157, 3]) + tokens = self.tokenizer.tokenize("▁He is not ▁He") + self.assertEqual(tokens, ["▁He", "▁is", "▁not", "▁He"]) # spaces are eaten by spm even if not start + + def test_character_after_special_token(self): + # Make sure that `tokenizer.tokenize` is similar to + # adding the equivalent special token to the vocab + input_ids = self.tokenizer.encode("Hey I") + self.assertEqual(input_ids, [3, 1, 157, 31, 2, 101, 3]) + sp_encode = self.tokenizer.sp_model.encode("Hey .I") + + # the last token besides eos should be 100 offset + self.assertEqual(input_ids[-2] - self.tokenizer.fairseq_offset, sp_encode[-1]) + tokens = self.tokenizer.tokenize("I") + self.assertEqual(tokens, ["", "I"]) + + input_ids = self.tokenizer.encode("Hello, ,") + self.assertEqual(input_ids, [3, 1, 157, 87, 21, 4, 2, 4, 3]) + tokens = self.tokenizer.tokenize("Hello, ,") + self.assertEqual(tokens, ["▁He", "ll", "o", ",", "", ","]) + + def test_special_tokens_strip(self): + input_ids = self.tokenizer.encode(" ,") + self.assertEqual(input_ids, [3, 1, 2, 8, 4, 3]) + tokens = self.tokenizer.tokenize(" ,") + # spaces are eaten by rstrip / lstrip + spm sp_model.encode(" ") = [] + self.assertEqual(tokens, ["", "▁", ","]) + + input_ids = self.tokenizer.encode("No ▁He") + self.assertEqual(input_ids, [3, 1, 285, 2, 157, 3]) + tokens = self.tokenizer.tokenize("No ▁He") + self.assertEqual(tokens, ["▁No", "", "▁He"]) # spaces are eaten by rstrip / lstrip diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t_v2/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t_v2/test_modeling_seamless_m4t_v2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t_v2/test_modeling_seamless_m4t_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..8627220c71aa5199575466dd4c3209165736b21e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/seamless_m4t_v2/test_modeling_seamless_m4t_v2.py @@ -0,0 +1,1165 @@ +# coding=utf-8 +# Copyright 2023 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 SeamlessM4Tv2 model. """ + + +import copy +import tempfile +import unittest + +from transformers import SeamlessM4Tv2Config, is_speech_available, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device +from transformers.trainer_utils import set_seed +from transformers.utils import cached_property + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) + + +if is_torch_available(): + import torch + + from transformers import ( + SeamlessM4Tv2ForSpeechToSpeech, + SeamlessM4Tv2ForSpeechToText, + SeamlessM4Tv2ForTextToSpeech, + SeamlessM4Tv2ForTextToText, + SeamlessM4Tv2Model, + ) + from transformers.models.seamless_m4t_v2.modeling_seamless_m4t_v2 import ( + SEAMLESS_M4T_V2_PRETRAINED_MODEL_ARCHIVE_LIST, + ) + +if is_speech_available(): + from transformers import SeamlessM4TProcessor + + +class SeamlessM4Tv2ModelTester: + def __init__( + self, + parent, + input_modality="speech", + batch_size=2, + seq_length=4, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + initializer_range=0.02, + max_new_tokens=None, + num_labels=3, + num_choices=4, + scope=None, + vocab_size=20, + t2u_vocab_size=20, + hidden_size=6, + num_hidden_layers=2, + intermediate_size=6, + max_position_embeddings=256, + encoder_layers=2, + decoder_layers=2, + encoder_ffn_dim=6, + decoder_ffn_dim=6, + t2u_encoder_layers=2, + t2u_decoder_layers=2, + t2u_encoder_ffn_dim=6, + t2u_decoder_ffn_dim=6, + num_heads=2, + vocoder_num_spkrs=5, + vocoder_num_langs=5, + upsample_initial_channel=32, + unit_embed_dim=25, + spkr_embed_dim=6, + lang_embed_dim=6, + num_conv_pos_embeddings=8, + unit_hifi_gan_vocab_size=20, + t2u_num_langs=0, + t2u_offset_tgt_lang=0, + vocoder_offset=0, + t2u_variance_predictor_hidden_dim=4, + char_vocab_size=4, + left_max_position_embeddings=2, + right_max_position_embeddings=1, + speech_encoder_chunk_size=2, + speech_encoder_left_chunk_num=1, + ): + self.parent = parent + self.input_modality = input_modality + + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + self.vocab_size = vocab_size + self.t2u_vocab_size = t2u_vocab_size + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.intermediate_size = intermediate_size + self.max_position_embeddings = max_position_embeddings + self.encoder_layers = encoder_layers + self.decoder_layers = decoder_layers + self.encoder_ffn_dim = encoder_ffn_dim + self.decoder_ffn_dim = decoder_ffn_dim + self.t2u_encoder_layers = t2u_encoder_layers + self.t2u_decoder_layers = t2u_decoder_layers + self.t2u_encoder_ffn_dim = t2u_encoder_ffn_dim + self.t2u_decoder_ffn_dim = t2u_decoder_ffn_dim + self.num_heads = num_heads + self.num_attention_heads = num_heads + + self.vocoder_num_spkrs = vocoder_num_spkrs + self.vocoder_num_langs = vocoder_num_langs + self.upsample_initial_channel = upsample_initial_channel + self.unit_embed_dim = unit_embed_dim + self.spkr_embed_dim = spkr_embed_dim + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.lang_embed_dim = lang_embed_dim + + self.max_new_tokens = max_new_tokens + + self.unit_hifi_gan_vocab_size = unit_hifi_gan_vocab_size + self.t2u_num_langs = t2u_num_langs + self.t2u_offset_tgt_lang = t2u_offset_tgt_lang + self.vocoder_offset = vocoder_offset + + self.t2u_variance_predictor_hidden_dim = t2u_variance_predictor_hidden_dim + self.char_vocab_size = char_vocab_size + self.left_max_position_embeddings = left_max_position_embeddings + self.right_max_position_embeddings = right_max_position_embeddings + self.speech_encoder_chunk_size = speech_encoder_chunk_size + self.speech_encoder_left_chunk_num = speech_encoder_left_chunk_num + + def prepare_config_and_inputs(self): + if self.input_modality == "text": + inputs = ids_tensor([self.batch_size, self.seq_length], self.vocab_size - 1) + else: + inputs = ids_tensor([self.batch_size, self.seq_length, 160], self.vocab_size - 1).float() + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size - 1) + + lm_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + + config = self.get_config() + + return config, inputs, decoder_input_ids, input_mask, lm_labels + + def get_config(self): + return SeamlessM4Tv2Config( + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + t2u_vocab_size=self.t2u_vocab_size, + hidden_size=self.hidden_size, + speech_encoder_layers=self.num_heads, + speech_encoder_intermediate_size=self.intermediate_size, + max_position_embeddings=self.max_position_embeddings, + encoder_layers=self.encoder_layers, + decoder_layers=self.decoder_layers, + encoder_ffn_dim=self.encoder_ffn_dim, + decoder_ffn_dim=self.decoder_ffn_dim, + t2u_encoder_layers=self.t2u_encoder_layers, + t2u_decoder_layers=self.t2u_decoder_layers, + t2u_encoder_ffn_dim=self.t2u_encoder_ffn_dim, + t2u_decoder_ffn_dim=self.t2u_decoder_ffn_dim, + num_attention_heads=self.num_heads, + encoder_attention_heads=self.num_heads, + decoder_attention_heads=self.num_heads, + t2u_encoder_attention_heads=self.num_heads, + t2u_decoder_attention_heads=self.num_heads, + speech_encoder_attention_heads=self.num_heads, + unit_hifigan_vocab_vise=self.t2u_vocab_size, + vocoder_num_spkrs=self.vocoder_num_spkrs, + vocoder_num_langs=self.vocoder_num_langs, + upsample_initial_channel=self.upsample_initial_channel, + unit_embed_dim=self.unit_embed_dim, + spkr_embed_dim=self.spkr_embed_dim, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + lang_embed_dim=self.lang_embed_dim, + max_new_tokens=self.max_new_tokens, + unit_hifi_gan_vocab_size=self.unit_hifi_gan_vocab_size, + t2u_num_langs=self.t2u_num_langs, + t2u_offset_tgt_lang=self.t2u_offset_tgt_lang, + vocoder_offset=self.vocoder_offset, + t2u_variance_predictor_embed_dim=self.hidden_size, + t2u_variance_predictor_hidden_dim=self.t2u_variance_predictor_hidden_dim, + char_vocab_size=self.char_vocab_size, + left_max_position_embeddings=self.left_max_position_embeddings, + right_max_position_embeddings=self.right_max_position_embeddings, + speech_encoder_chunk_size=self.speech_encoder_chunk_size, + speech_encoder_left_chunk_num=self.speech_encoder_left_chunk_num, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + decoder_input_ids, + input_mask, + lm_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + decoder_input_ids, + input_mask, + lm_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model(self, config, input_ids, decoder_input_ids, input_mask, labels): + model = SeamlessM4Tv2Model(config=config) + model.to(torch_device) + model.eval() + if self.input_modality == "text": + result = model(input_ids=input_ids, attention_mask=input_mask, decoder_input_ids=decoder_input_ids) + result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + else: + result = model(input_features=input_ids, attention_mask=input_mask, decoder_input_ids=decoder_input_ids) + result = model(input_features=input_ids, decoder_input_ids=decoder_input_ids) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + decoder_output = result.logits + decoder_past = result.past_key_values + encoder_output = result.encoder_last_hidden_state + + if self.input_modality == "text": + seq_length = self.seq_length + else: + # if speech, expected length has been subsampled. + seq_length = model._compute_sub_sample_lengths_from_attention_mask(input_mask).max().item() + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, seq_length, self.hidden_size)) + self.parent.assertEqual(decoder_output.size(), (self.batch_size, decoder_input_ids.shape[1], self.vocab_size)) + # There should be `num_layers` key value embeddings stored in decoder_past + self.parent.assertEqual(len(decoder_past), config.decoder_layers) + # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple + self.parent.assertEqual(len(decoder_past[0]), 4) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + decoder_input_ids, + input_mask, + lm_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + model = SeamlessM4Tv2Model(config=config) + model.to(torch_device) + model.eval() + + # make sure no pad token in decoder_input_ids + decoder_input_ids = torch.clamp(decoder_input_ids, config.pad_token_id + 1) + + # first forward pass + outputs = model( + input_ids, decoder_input_ids=decoder_input_ids, decoder_attention_mask=input_mask, use_cache=True + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([decoder_input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + input_ids, + decoder_input_ids=next_input_ids, + decoder_attention_mask=next_attention_mask, + output_hidden_states=True, + ) + output_from_no_past = output_from_no_past["decoder_hidden_states"][0] + output_from_past = model( + input_ids, + decoder_input_ids=next_tokens, + decoder_attention_mask=next_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["decoder_hidden_states"][0] + + # 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)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + decoder_input_ids, + input_mask, + lm_labels, + ) = config_and_inputs + + input_name = "input_ids" if self.input_modality == "text" else "input_features" + + inputs_dict = { + input_name: input_ids, + "attention_mask": input_mask, + "decoder_input_ids": decoder_input_ids, + "labels": lm_labels, + } + return config, inputs_dict + + +@require_torch +class SeamlessM4Tv2ModelWithSpeechInputTest(ModelTesterMixin, unittest.TestCase): + is_encoder_decoder = True + fx_compatible = False + test_missing_keys = False + test_pruning = False + test_model_parallel = False + test_resize_embeddings = False + test_headmasking = False + test_torchscript = False + + all_model_classes = ( + ( + SeamlessM4Tv2Model, + SeamlessM4Tv2ForSpeechToSpeech, + SeamlessM4Tv2ForSpeechToText, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (SeamlessM4Tv2ForSpeechToText,) if is_torch_available() else () + + input_name = "input_features" + + def setUp(self): + self.model_tester = SeamlessM4Tv2ModelTester(self, input_modality="speech") + self.config_tester = ConfigTester(self, config_class=SeamlessM4Tv2Config) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in SEAMLESS_M4T_V2_PRETRAINED_MODEL_ARCHIVE_LIST: + model = SeamlessM4Tv2Model.from_pretrained(model_name) + self.assertIsNotNone(model) + + def _get_input_ids_and_config(self, batch_size=2): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_ids = inputs_dict[self.input_name] + + # cut to half length & take max batch_size 3 + sequence_length = input_ids.shape[-1] // 2 + input_ids = input_ids[:batch_size, :sequence_length] + + # generate max 3 tokens + max_length = input_ids.shape[-1] + 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()` + if isinstance(config.eos_token_id, int): + config.eos_token_id = [config.eos_token_id] + config.pad_token_id = config.eos_token_id[0] + + attention_mask = torch.ones(input_ids.shape[:2], dtype=torch.long)[:batch_size, :sequence_length] + + return config, input_ids.float(), attention_mask, max_length + + @staticmethod + def _get_encoder_outputs( + model, input_ids, attention_mask, output_attentions=None, output_hidden_states=None, num_interleave=1 + ): + 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 = ( + torch.zeros(input_ids.shape[:2], dtype=torch.int64, layout=input_ids.layout, device=input_ids.device) + + model._get_decoder_start_token_id() + ) + attention_mask = None + return encoder_outputs, input_ids, attention_mask + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "pos_bias_v", + "pos_bias_u", + "pointwise_conv1", + "pointwise_conv2", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "objective.weight", + "adapter", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + @unittest.skip(reason="SeamlessM4Tv2SpeechEncoder doesn't have an embedding layer") + def test_inputs_embeds(self): + pass + + @unittest.skip( + reason="Expected missing keys serve when using SeamlessM4Tv2ForXXX.from_pretrained from a checkpoint saved by SeamlessM4Tv2Model.save_pretrained." + ) + def test_model_weights_reload_no_missing_tied_weights(self): + pass + + @unittest.skip( + reason="SeamlessM4Tv2Model is base class but has actually a bigger architecture than seamlessM4T task-specific models." + ) + def test_save_load_fast_init_to_base(self): + pass + + @unittest.skip(reason="SeamlessM4Tv2Model can takes input_ids or input_features") + def test_forward_signature(self): + pass + + @unittest.skip(reason="SeamlessM4Tv2 has no base model") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + def test_attention_outputs(self): + # expected length is subsampled so need to change a bit this test + if not self.has_attentions: + self.skipTest(reason="Model does not output attentions") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + # no more chunk_length test + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + out_len = len(outputs) + + if self.is_encoder_decoder: + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + + sub_sampled_length = ( + model._compute_sub_sample_lengths_from_attention_mask(inputs_dict["attention_mask"]).max().item() + ) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + sub_sampled_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + elif self.is_encoder_decoder: + added_hidden_states = 2 + else: + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + +@require_torch +class SeamlessM4Tv2ModelWithTextInputTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): + is_encoder_decoder = True + fx_compatible = False + test_missing_keys = False + test_pruning = False + test_model_parallel = False + test_resize_embeddings = True + test_headmasking = False + test_torchscript = False + + all_model_classes = ( + ( + SeamlessM4Tv2Model, + SeamlessM4Tv2ForTextToSpeech, + SeamlessM4Tv2ForTextToText, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (SeamlessM4Tv2ForTextToText,) if is_torch_available() else () + + def setUp(self): + self.model_tester = SeamlessM4Tv2ModelTester(self, input_modality="text") + self.config_tester = ConfigTester(self, config_class=SeamlessM4Tv2Config) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in SEAMLESS_M4T_V2_PRETRAINED_MODEL_ARCHIVE_LIST: + model = SeamlessM4Tv2Model.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "pos_bias_v", + "pos_bias_u", + "pointwise_conv1", + "pointwise_conv2", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "objective.weight", + "adapter", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + @unittest.skip( + reason="Expected missing keys serve when using SeamlessM4Tv2ForXXX.from_pretrained from a checkpoint saved by SeamlessM4Tv2Model.save_pretrained." + ) + def test_model_weights_reload_no_missing_tied_weights(self): + pass + + @unittest.skip(reason="SeamlessM4Tv2Model can take input_ids or input_features") + def test_forward_signature(self): + pass + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + @unittest.skip( + reason="SeamlessM4Tv2Model is base class but has actually a bigger architecture than seamlessM4T task-specific models." + ) + def test_save_load_fast_init_to_base(self): + pass + + @unittest.skip(reason="SeamlessM4Tv2 has no base model") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + +@require_torch +class SeamlessM4Tv2GenerationTest(unittest.TestCase): + # test that non-standard generation works + # test generation of: SeamlessM4Tv2Model, SeamlessM4Tv2ForSpeechToSpeech, SeamlessM4Tv2ForSpeechToText, SeamlessM4Tv2ForTextToSpeech + + def setUp(self): + self.speech_model_tester = SeamlessM4Tv2ModelTester(self, input_modality="speech") + self.text_model_tester = SeamlessM4Tv2ModelTester(self, input_modality="text") + self.tmpdirname = tempfile.mkdtemp() + + def update_generation(self, model): + lang_code_to_id = { + "fra": 4, + "eng": 4, + } + + id_to_text = {str(i): "a" for i in range(model.config.vocab_size)} + id_to_text["0"] = "ab" + id_to_text["1"] = "_b" + id_to_text["3"] = "," + id_to_text["4"] = "_cd" + + char_to_id = {char: i for (i, char) in enumerate("abcd")} + + generation_config = copy.deepcopy(model.generation_config) + + generation_config.__setattr__("text_decoder_lang_to_code_id", lang_code_to_id) + generation_config.__setattr__("t2u_lang_code_to_id", lang_code_to_id) + generation_config.__setattr__("vocoder_lang_code_to_id", lang_code_to_id) + generation_config.__setattr__("id_to_text", id_to_text) + generation_config.__setattr__("char_to_id", char_to_id) + generation_config.__setattr__("eos_token_id", 0) + + generation_config._from_model_config = False + + model.generation_config = generation_config + + def prepare_text_input(self): + config, inputs, decoder_input_ids, input_mask, lm_labels = self.text_model_tester.prepare_config_and_inputs() + + input_dict = { + "input_ids": inputs, + "attention_mask": input_mask, + "tgt_lang": "eng", + "num_beams": 2, + "do_sample": True, + } + + return config, input_dict + + def prepare_speech_input(self): + config, inputs, decoder_input_ids, input_mask, lm_labels = self.speech_model_tester.prepare_config_and_inputs() + + input_dict = { + "input_features": inputs, + "attention_mask": input_mask, + "tgt_lang": "fra", + "num_beams": 2, + "do_sample": True, + } + + return config, input_dict + + def prepare_speech_and_text_input(self): + config, inputs, decoder_input_ids, input_mask, lm_labels = self.speech_model_tester.prepare_config_and_inputs() + + input_speech = { + "input_features": inputs, + "attention_mask": input_mask, + "tgt_lang": "fra", + "num_beams": 2, + "do_sample": True, + } + + config, inputs, decoder_input_ids, input_mask, lm_labels = self.text_model_tester.prepare_config_and_inputs() + + input_text = { + "input_ids": inputs, + "attention_mask": input_mask, + "tgt_lang": "eng", + "num_beams": 2, + "do_sample": True, + } + return config, input_speech, input_text + + def factory_generation_speech_test(self, model, inputs): + set_seed(0) + output = model.generate(**inputs) + return output + + def test_speech_generation(self): + config, input_speech, input_text = self.prepare_speech_and_text_input() + + model = SeamlessM4Tv2Model(config=config) + self.update_generation(model) + model.save_pretrained(self.tmpdirname) + model.to(torch_device) + model.eval() + + output_original_text = self.factory_generation_speech_test(model, input_text) + output_original_speech = self.factory_generation_speech_test(model, input_speech) + + state_dict = model.state_dict() + + text_model = SeamlessM4Tv2ForTextToSpeech.from_pretrained(self.tmpdirname) + self.update_generation(text_model) + text_model.to(torch_device) + text_model.eval() + + output_text = self.factory_generation_speech_test(model, input_text) + + speech_model = SeamlessM4Tv2ForSpeechToSpeech.from_pretrained(self.tmpdirname) + self.update_generation(speech_model) + speech_model.to(torch_device) + speech_model.eval() + + for name, tensor in speech_model.state_dict().items(): + right_tensor = state_dict.get(name) + self.assertEqual(tensor.tolist(), right_tensor.tolist(), f"Tensor {name}") + + output_speech = self.factory_generation_speech_test(model, input_speech) + + # test same text output from input text + self.assertListEqual(output_original_text[0].ravel().tolist(), output_text[0].ravel().tolist()) + self.assertListEqual(output_original_text[1].ravel().tolist(), output_text[1].ravel().tolist()) + + # test same speech output from input text + # assertTrue because super long list makes this hang in case of failure + self.assertTrue( + output_original_speech[0].ravel().tolist() == output_speech[0].ravel().tolist(), + "Speech generated was different", + ) + self.assertTrue( + output_original_speech[1].ravel().tolist() == output_speech[1].ravel().tolist(), + "Speech generated was different", + ) + + def test_text_generation(self): + config, input_speech, input_text = self.prepare_speech_and_text_input() + + # to return speech + input_speech["generate_speech"] = False + input_text["generate_speech"] = False + + model = SeamlessM4Tv2Model(config=config) + self.update_generation(model) + model.save_pretrained(self.tmpdirname) + model.to(torch_device) + model.eval() + + output_original_text = self.factory_generation_speech_test(model, input_text) + output_original_speech = self.factory_generation_speech_test(model, input_speech) + + # other models don't need it + input_speech.pop("generate_speech") + input_text.pop("generate_speech") + + state_dict = model.state_dict() + + text_model = SeamlessM4Tv2ForTextToText.from_pretrained(self.tmpdirname) + self.update_generation(text_model) + text_model.to(torch_device) + text_model.eval() + + for name, tensor in text_model.state_dict().items(): + right_tensor = state_dict.get(name) + self.assertEqual(tensor.tolist(), right_tensor.tolist()) + + output_text = self.factory_generation_speech_test(text_model, input_text) + + speech_model = SeamlessM4Tv2ForSpeechToText.from_pretrained(self.tmpdirname) + + for name, tensor in speech_model.state_dict().items(): + right_tensor = state_dict.get(name) + self.assertEqual(tensor.tolist(), right_tensor.tolist(), f"Tensor {name}") + + self.update_generation(speech_model) + speech_model.to(torch_device) + speech_model.eval() + + output_speech = self.factory_generation_speech_test(speech_model, input_speech) + + # test same text output from input text + self.assertListEqual(output_original_text[0].ravel().tolist(), output_text.ravel().tolist()) + + # test same speech output from input text + self.assertListEqual(output_original_speech[0].ravel().tolist(), output_speech.ravel().tolist()) + + def test_generation(self): + config, input_speech, input_text = self.prepare_speech_and_text_input() + + input_speech["num_beams"] = 3 + input_speech["do_sample"] = True + input_speech["temperature"] = 0.5 + input_speech["num_return_sequences"] = 3 + + input_text["num_beams"] = 3 + input_text["do_sample"] = True + input_text["temperature"] = 0.5 + input_text["num_return_sequences"] = 3 + + for model_class in [SeamlessM4Tv2ForSpeechToSpeech, SeamlessM4Tv2ForSpeechToText, SeamlessM4Tv2Model]: + model = model_class(config=config) + self.update_generation(model) + model.to(torch_device) + model.eval() + + output = model.generate(**input_speech) + output = output[0] if isinstance(output, tuple) else output + + self.assertEqual(output.shape[0], 3 * input_speech["input_features"].shape[0]) + + for model_class in [SeamlessM4Tv2ForTextToSpeech, SeamlessM4Tv2ForTextToText, SeamlessM4Tv2Model]: + model = model_class(config=config) + self.update_generation(model) + model.to(torch_device) + model.eval() + + output = model.generate(**input_text) + + output = output[0] if isinstance(output, tuple) else output + + self.assertEqual(output.shape[0], 3 * input_text["input_ids"].shape[0]) + + +@require_torch +class SeamlessM4Tv2ModelIntegrationTest(unittest.TestCase): + repo_id = "facebook/seamless-m4t-v2-large" + + def assertListAlmostEqual(self, list1, list2, tol=1e-4): + self.assertEqual(len(list1), len(list2)) + for a, b in zip(list1, list2): + self.assertAlmostEqual(a, b, delta=tol) + + @cached_property + def processor(self): + return SeamlessM4TProcessor.from_pretrained(self.repo_id) + + @cached_property + def input_text(self): + # corresponds to "C'est un test." with seamlessM4T_medium checkpoint + + input_ids = torch.tensor([[256026, 109, 247729, 171, 128, 6816, 247676, 3]]) # fmt: skip + + input_ids = input_ids.to(torch_device) + + attention_mask = torch.ones_like(input_ids).to(torch_device) + + inputs = { + "attention_mask": attention_mask, + "input_ids": input_ids, + } + + return inputs + + @cached_property + def input_audio(self): + set_seed(0) + seq_len = 20000 + sampling_rate = 16000 + input_features = torch.rand((2, seq_len)) + + return self.processor(audios=[input_features.tolist()], sampling_rate=sampling_rate, return_tensors="pt").to( + torch_device + ) + + def factory_test_task(self, class1, class2, inputs, class1_kwargs, class2_kwargs): + # half-precision loading to limit GPU usage + model1 = class1.from_pretrained(self.repo_id, torch_dtype=torch.float16).to(torch_device) + model2 = class2.from_pretrained(self.repo_id, torch_dtype=torch.float16).to(torch_device) + + set_seed(0) + output_1 = model1.generate(**inputs, **class1_kwargs) + set_seed(0) + output_2 = model2.generate(**inputs, **class2_kwargs) + + for key in output_1: + if isinstance(output_1[key], torch.Tensor): + if len(output_1[key].shape) == 0: + self.assertEqual(output_1[key].item(), output_2[key].item()) + else: + self.assertListAlmostEqual(output_1[key].squeeze().tolist(), output_2[key].squeeze().tolist()) + + @slow + def test_to_eng_text(self): + model = SeamlessM4Tv2Model.from_pretrained(self.repo_id).to(torch_device) + + # test text - tgt lang: eng + + expected_text_tokens = [3, 256022, 3080, 1, 247669, 10, 6816, 247676, 3] # fmt: skip + + # fmt: off + expected_unit_tokens = [ + 4746,7163,8208,8208,1315,1266,4307,1119,989,9594,3007,3007,4341,5205,7631,7631,3202,4061,9092,3191,7509,1715, + 5280,5280,3554,8812,8197,6366,5382,5382,7330,2758,9433,9433,6863,7510,5800,5800,5286,1948,1825,1825,3956,8724, + 8724,5331,8914,9315,9315,5288,2588,8167,8787,8787,8063,6008,2621,2621,2621,5696 + ] + # fmt: on + + expected_wav_slice = [9.485097e-04, 8.320558e-04, 7.178137e-04, 9.349979e-04, 1.121628e-03, 1.091766e-03, 1.279693e-03, 1.387754e-03, 1.296396e-03, 1.143557e-03] # fmt: skip + + set_seed(0) + output = model.generate(**self.input_text, num_beams=1, tgt_lang="eng", return_intermediate_token_ids=True) + + self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) + self.assertListEqual( + expected_unit_tokens, (output.unit_sequences - model.config.vocoder_offset).squeeze().tolist() + ) + + self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) + + # assert mean and std equality + self.assertListAlmostEqual( + [-2.349690e-04, 9.920777e-02], [output.waveform.mean().item(), output.waveform.std().item()] + ) + + @slow + @unittest.skip(reason="Equivalence is broken since a new update") + def test_to_swh_text(self): + model = SeamlessM4Tv2Model.from_pretrained(self.repo_id).to(torch_device) + + # test text - tgt lang: swh + + expected_text_tokens = [3, 256084, 109, 247729, 171, 10, 6816, 247676, 3] # fmt: skip + + # fmt: off + expected_unit_tokens = [ + 5725,7163,7472,7472,6915,3099,3099,9921,2765,6515,6515,1374,1374,1347,8252,9854,9854,5662,2420,6600,2216,4503, + 7208,6107,6107,7298,9123,6472,9663,9663,6366,6366,6445,575,3575,2052,2052,5788,5800,5800,5286,5286,1825,1825,3956, + 3956,8724,8724,5331,8914,8914,9315,9315,2821,8167,8167,8787,8787,8787,8700,8700,8700,2175,2175,3196,3196,2621,1725, + 1725,7507,5696 + ] + # fmt: on + + expected_wav_slice = [3.124037e-04, 2.450471e-04, 2.286572e-04, 2.317214e-04, 2.732605e-04, 2.478790e-04, 2.704144e-04, 2.665847e-04, 2.828784e-04, 2.684390e-04] # fmt: skip + + set_seed(0) + output = model.generate(**self.input_text, num_beams=1, tgt_lang="swh", return_intermediate_token_ids=True) + + self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) + self.assertListEqual( + expected_unit_tokens, (output.unit_sequences - model.config.vocoder_offset).squeeze().tolist() + ) + + self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) + + # assert mean and std equality + self.assertListAlmostEqual( + [-2.001826e-04, 8.580012e-02], [output.waveform.mean().item(), output.waveform.std().item()] + ) + + @slow + def test_to_rus_speech(self): + model = SeamlessM4Tv2Model.from_pretrained(self.repo_id).to(torch_device) + + # test audio - tgt lang: rus + + expected_text_tokens = [3, 256074, 107, 248213, 404, 247792, 247789, 3] # fmt: skip + + # fmt: off + expected_unit_tokens = [ + 8976,7163,6915,2728,2728,5198,3318,3318,3686,1049,9643,1200,2052,2052,8196,8196,7624,7624,7555,7555,7555,7555, + 9717,9717,4869,8167,8167,8167,8053,972,9362,8167,297,297,297,3993,3993,3993,3993,4660,4660,4660,4660,4660,4660, + 7962,7962,225,225,8737,4199 + ] + # fmt: on + + expected_wav_slice = [1.415287e-03, 1.360976e-03, 1.297727e-03, 1.305321e-03, 1.352087e-03, 1.283812e-03, 1.352623e-03, 1.387384e-03, 1.449627e-03, 1.411701e-03] # fmt: skip + + set_seed(0) + output = model.generate(**self.input_audio, num_beams=1, tgt_lang="rus", return_intermediate_token_ids=True) + + self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) + self.assertListEqual( + expected_unit_tokens, (output.unit_sequences - model.config.vocoder_offset).squeeze().tolist() + ) + + self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) + + # assert mean and std equality - higher tolerance for speech + self.assertListAlmostEqual( + [-2.818016e-04, 7.169888e-02], [output.waveform.mean().item(), output.waveform.std().item()], tol=5e-4 + ) + + @slow + def test_text_to_text_model(self): + kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True, "generate_speech": False} + kwargs2 = { + "tgt_lang": "eng", + "output_hidden_states": True, + "return_dict_in_generate": True, + "output_scores": True, + } + self.factory_test_task(SeamlessM4Tv2Model, SeamlessM4Tv2ForTextToText, self.input_text, kwargs1, kwargs2) + + @slow + def test_speech_to_text_model(self): + kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True, "generate_speech": False} + kwargs2 = { + "tgt_lang": "eng", + "output_hidden_states": True, + "return_dict_in_generate": True, + "output_scores": True, + } + self.factory_test_task(SeamlessM4Tv2Model, SeamlessM4Tv2ForSpeechToText, self.input_audio, kwargs1, kwargs2) + + @slow + def test_speech_to_speech_model(self): + kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True} + self.factory_test_task(SeamlessM4Tv2Model, SeamlessM4Tv2ForSpeechToSpeech, self.input_audio, kwargs1, kwargs1) + + @slow + def test_text_to_speech_model(self): + kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True} + + self.factory_test_task(SeamlessM4Tv2Model, SeamlessM4Tv2ForTextToSpeech, self.input_text, kwargs1, kwargs1) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_image_processing_segformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_image_processing_segformer.py new file mode 100644 index 0000000000000000000000000000000000000000..d84afdaa5746a34b063926967e6a7ae08e5642ac --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_image_processing_segformer.py @@ -0,0 +1,258 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 unittest + +from datasets import load_dataset + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + from transformers import SegformerImageProcessor + + +class SegformerImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + min_resolution=30, + max_resolution=400, + do_resize=True, + size=None, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + do_reduce_labels=False, + ): + size = size if size is not None else {"height": 30, "width": 30} + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + self.do_reduce_labels = do_reduce_labels + + def prepare_image_processor_dict(self): + return { + "do_resize": self.do_resize, + "size": self.size, + "do_normalize": self.do_normalize, + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_reduce_labels": self.do_reduce_labels, + } + + def expected_output_image_shape(self, images): + return self.num_channels, self.size["height"], self.size["width"] + + def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_image_inputs( + batch_size=self.batch_size, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +def prepare_semantic_single_inputs(): + dataset = load_dataset("hf-internal-testing/fixtures_ade20k", split="test") + + image = Image.open(dataset[0]["file"]) + map = Image.open(dataset[1]["file"]) + + return image, map + + +def prepare_semantic_batch_inputs(): + dataset = load_dataset("hf-internal-testing/fixtures_ade20k", split="test") + + image1 = Image.open(dataset[0]["file"]) + map1 = Image.open(dataset[1]["file"]) + image2 = Image.open(dataset[2]["file"]) + map2 = Image.open(dataset[3]["file"]) + + return [image1, image2], [map1, map2] + + +@require_torch +@require_vision +class SegformerImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = SegformerImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = SegformerImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "size")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_reduce_labels")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"height": 30, "width": 30}) + self.assertEqual(image_processor.do_reduce_labels, False) + + image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42, reduce_labels=True) + self.assertEqual(image_processor.size, {"height": 42, "width": 42}) + self.assertEqual(image_processor.do_reduce_labels, True) + + def test_call_segmentation_maps(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + maps = [] + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + maps.append(torch.zeros(image.shape[-2:]).long()) + + # Test not batched input + encoding = image_processing(image_inputs[0], maps[0], return_tensors="pt") + self.assertEqual( + encoding["pixel_values"].shape, + ( + 1, + self.image_processor_tester.num_channels, + self.image_processor_tester.size["height"], + self.image_processor_tester.size["width"], + ), + ) + self.assertEqual( + encoding["labels"].shape, + ( + 1, + self.image_processor_tester.size["height"], + self.image_processor_tester.size["width"], + ), + ) + self.assertEqual(encoding["labels"].dtype, torch.long) + self.assertTrue(encoding["labels"].min().item() >= 0) + self.assertTrue(encoding["labels"].max().item() <= 255) + + # Test batched + encoding = image_processing(image_inputs, maps, return_tensors="pt") + self.assertEqual( + encoding["pixel_values"].shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_channels, + self.image_processor_tester.size["height"], + self.image_processor_tester.size["width"], + ), + ) + self.assertEqual( + encoding["labels"].shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.size["height"], + self.image_processor_tester.size["width"], + ), + ) + self.assertEqual(encoding["labels"].dtype, torch.long) + self.assertTrue(encoding["labels"].min().item() >= 0) + self.assertTrue(encoding["labels"].max().item() <= 255) + + # Test not batched input (PIL images) + image, segmentation_map = prepare_semantic_single_inputs() + + encoding = image_processing(image, segmentation_map, return_tensors="pt") + self.assertEqual( + encoding["pixel_values"].shape, + ( + 1, + self.image_processor_tester.num_channels, + self.image_processor_tester.size["height"], + self.image_processor_tester.size["width"], + ), + ) + self.assertEqual( + encoding["labels"].shape, + ( + 1, + self.image_processor_tester.size["height"], + self.image_processor_tester.size["width"], + ), + ) + self.assertEqual(encoding["labels"].dtype, torch.long) + self.assertTrue(encoding["labels"].min().item() >= 0) + self.assertTrue(encoding["labels"].max().item() <= 255) + + # Test batched input (PIL images) + images, segmentation_maps = prepare_semantic_batch_inputs() + + encoding = image_processing(images, segmentation_maps, return_tensors="pt") + self.assertEqual( + encoding["pixel_values"].shape, + ( + 2, + self.image_processor_tester.num_channels, + self.image_processor_tester.size["height"], + self.image_processor_tester.size["width"], + ), + ) + self.assertEqual( + encoding["labels"].shape, + ( + 2, + self.image_processor_tester.size["height"], + self.image_processor_tester.size["width"], + ), + ) + self.assertEqual(encoding["labels"].dtype, torch.long) + self.assertTrue(encoding["labels"].min().item() >= 0) + self.assertTrue(encoding["labels"].max().item() <= 255) + + def test_reduce_labels(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + + # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 + image, map = prepare_semantic_single_inputs() + encoding = image_processing(image, map, return_tensors="pt") + self.assertTrue(encoding["labels"].min().item() >= 0) + self.assertTrue(encoding["labels"].max().item() <= 150) + + image_processing.do_reduce_labels = True + encoding = image_processing(image, map, return_tensors="pt") + self.assertTrue(encoding["labels"].min().item() >= 0) + self.assertTrue(encoding["labels"].max().item() <= 255) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_modeling_segformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_modeling_segformer.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a4dce9ffeb3cd981095afcd4b50e791393258d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_modeling_segformer.py @@ -0,0 +1,435 @@ +# coding=utf-8 +# 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 SegFormer model. """ + + +import unittest + +from transformers import SegformerConfig, is_torch_available, is_vision_available +from transformers.models.auto import get_values +from transformers.testing_utils import require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + MODEL_MAPPING, + SegformerForImageClassification, + SegformerForSemanticSegmentation, + SegformerModel, + ) + from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import SegformerImageProcessor + + +class SegformerConfigTester(ConfigTester): + def create_and_test_config_common_properties(self): + config = self.config_class(**self.inputs_dict) + self.parent.assertTrue(hasattr(config, "hidden_sizes")) + self.parent.assertTrue(hasattr(config, "num_attention_heads")) + self.parent.assertTrue(hasattr(config, "num_encoder_blocks")) + + +class SegformerModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=64, + num_channels=3, + num_encoder_blocks=4, + depths=[1, 1, 1, 1], + sr_ratios=[8, 4, 2, 1], + hidden_sizes=[8, 8, 16, 16], + downsampling_rates=[1, 4, 8, 16], + num_attention_heads=[1, 1, 2, 2], + is_training=True, + use_labels=True, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + initializer_range=0.02, + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.num_encoder_blocks = num_encoder_blocks + self.sr_ratios = sr_ratios + self.depths = depths + self.hidden_sizes = hidden_sizes + self.downsampling_rates = downsampling_rates + self.num_attention_heads = num_attention_heads + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.num_labels = num_labels + self.scope = scope + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels) + + config = self.get_config() + return config, pixel_values, labels + + def get_config(self): + return SegformerConfig( + image_size=self.image_size, + num_channels=self.num_channels, + num_encoder_blocks=self.num_encoder_blocks, + depths=self.depths, + hidden_sizes=self.hidden_sizes, + num_attention_heads=self.num_attention_heads, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = SegformerModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + expected_height = expected_width = self.image_size // (self.downsampling_rates[-1] * 2) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) + ) + + def create_and_check_for_image_segmentation(self, config, pixel_values, labels): + config.num_labels = self.num_labels + model = SegformerForSemanticSegmentation(config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) + ) + result = model(pixel_values, labels=labels) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) + ) + self.parent.assertGreater(result.loss, 0.0) + + def create_and_check_for_binary_image_segmentation(self, config, pixel_values, labels): + config.num_labels = 1 + model = SegformerForSemanticSegmentation(config=config) + model.to(torch_device) + model.eval() + labels = torch.randint(0, 1, (self.batch_size, self.image_size, self.image_size)).to(torch_device) + result = model(pixel_values, labels=labels) + self.parent.assertGreater(result.loss, 0.0) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class SegformerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + SegformerModel, + SegformerForSemanticSegmentation, + SegformerForImageClassification, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + { + "feature-extraction": SegformerModel, + "image-classification": SegformerForImageClassification, + "image-segmentation": SegformerForSemanticSegmentation, + } + if is_torch_available() + else {} + ) + + fx_compatible = True + test_head_masking = False + test_pruning = False + test_resize_embeddings = False + + def setUp(self): + self.model_tester = SegformerModelTester(self) + self.config_tester = SegformerConfigTester(self, config_class=SegformerConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_binary_image_segmentation(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_binary_image_segmentation(*config_and_inputs) + + def test_for_image_segmentation(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_segmentation(*config_and_inputs) + + @unittest.skip("SegFormer does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods") + def test_model_common_attributes(self): + pass + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + + expected_num_attentions = sum(self.model_tester.depths) + self.assertEqual(len(attentions), expected_num_attentions) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + + self.assertEqual(len(attentions), expected_num_attentions) + + # verify the first attentions (first block, first layer) + expected_seq_len = (self.model_tester.image_size // 4) ** 2 + expected_reduced_seq_len = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len], + ) + + # verify the last attentions (last block, last layer) + expected_seq_len = (self.model_tester.image_size // 32) ** 2 + expected_reduced_seq_len = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 + self.assertListEqual( + list(attentions[-1].shape[-3:]), + [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), expected_num_attentions) + # verify the first attentions (first block, first layer) + expected_seq_len = (self.model_tester.image_size // 4) ** 2 + expected_reduced_seq_len = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_layers = self.model_tester.num_encoder_blocks + self.assertEqual(len(hidden_states), expected_num_layers) + + # verify the first hidden states (first block) + self.assertListEqual( + list(hidden_states[0].shape[-3:]), + [ + self.model_tester.hidden_sizes[0], + self.model_tester.image_size // 4, + self.model_tester.image_size // 4, + ], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_training(self): + if not self.model_tester.is_training: + return + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + if model_class in get_values(MODEL_MAPPING): + continue + + model = model_class(config) + model.to(torch_device) + model.train() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + loss = model(**inputs).loss + loss.backward() + + @slow + def test_model_from_pretrained(self): + for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SegformerModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +class SegformerModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_image_segmentation_ade(self): + # only resize + normalize + image_processor = SegformerImageProcessor( + image_scale=(512, 512), keep_ratio=False, align=False, do_random_crop=False + ) + model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512").to( + torch_device + ) + + image = prepare_img() + encoded_inputs = image_processor(images=image, return_tensors="pt") + pixel_values = encoded_inputs.pixel_values.to(torch_device) + + with torch.no_grad(): + outputs = model(pixel_values) + + expected_shape = torch.Size((1, model.config.num_labels, 128, 128)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor( + [ + [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], + [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], + [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], + ] + ).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_image_segmentation_city(self): + # only resize + normalize + image_processor = SegformerImageProcessor( + image_scale=(512, 512), keep_ratio=False, align=False, do_random_crop=False + ) + model = SegformerForSemanticSegmentation.from_pretrained( + "nvidia/segformer-b1-finetuned-cityscapes-1024-1024" + ).to(torch_device) + + image = prepare_img() + encoded_inputs = image_processor(images=image, return_tensors="pt") + pixel_values = encoded_inputs.pixel_values.to(torch_device) + + with torch.no_grad(): + outputs = model(pixel_values) + + expected_shape = torch.Size((1, model.config.num_labels, 128, 128)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor( + [ + [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], + [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], + [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], + ] + ).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3], expected_slice, atol=1e-1)) + + @slow + def test_post_processing_semantic_segmentation(self): + # only resize + normalize + image_processor = SegformerImageProcessor( + image_scale=(512, 512), keep_ratio=False, align=False, do_random_crop=False + ) + model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512").to( + torch_device + ) + + image = prepare_img() + encoded_inputs = image_processor(images=image, return_tensors="pt") + pixel_values = encoded_inputs.pixel_values.to(torch_device) + + with torch.no_grad(): + outputs = model(pixel_values) + + outputs.logits = outputs.logits.detach().cpu() + + segmentation = image_processor.post_process_semantic_segmentation(outputs=outputs, target_sizes=[(500, 300)]) + expected_shape = torch.Size((500, 300)) + self.assertEqual(segmentation[0].shape, expected_shape) + + segmentation = image_processor.post_process_semantic_segmentation(outputs=outputs) + expected_shape = torch.Size((128, 128)) + self.assertEqual(segmentation[0].shape, expected_shape) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_modeling_tf_segformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_modeling_tf_segformer.py new file mode 100644 index 0000000000000000000000000000000000000000..aca621f5097dd0948b6c2ab088aafa7ac856b15b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/segformer/test_modeling_tf_segformer.py @@ -0,0 +1,506 @@ +# coding=utf-8 +# Copyright 2022 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 TensorFlow SegFormer model. """ + +from __future__ import annotations + +import inspect +import unittest +from typing import List, Tuple + +from transformers import SegformerConfig +from transformers.file_utils import is_tf_available, is_vision_available +from transformers.testing_utils import require_tf, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import numpy as np + import tensorflow as tf + + from transformers import TFSegformerForImageClassification, TFSegformerForSemanticSegmentation, TFSegformerModel + from transformers.models.segformer.modeling_tf_segformer import TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST + +if is_vision_available(): + from PIL import Image + + from transformers import SegformerImageProcessor + + +class TFSegformerConfigTester(ConfigTester): + def create_and_test_config_common_properties(self): + config = self.config_class(**self.inputs_dict) + self.parent.assertTrue(hasattr(config, "hidden_sizes")) + self.parent.assertTrue(hasattr(config, "num_attention_heads")) + self.parent.assertTrue(hasattr(config, "num_encoder_blocks")) + + +class TFSegformerModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=64, + num_channels=3, + num_encoder_blocks=4, + depths=[1, 1, 1, 1], + sr_ratios=[8, 4, 2, 1], + hidden_sizes=[8, 8, 16, 16], + downsampling_rates=[1, 4, 8, 16], + num_attention_heads=[1, 1, 2, 2], + is_training=True, + use_labels=True, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + initializer_range=0.02, + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.num_encoder_blocks = num_encoder_blocks + self.sr_ratios = sr_ratios + self.depths = depths + self.hidden_sizes = hidden_sizes + self.downsampling_rates = downsampling_rates + self.num_attention_heads = num_attention_heads + self.is_training = is_training + self.use_labels = use_labels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.initializer_range = initializer_range + self.num_labels = num_labels + self.scope = scope + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels) + + config = self.get_config() + return config, pixel_values, labels + + def get_config(self): + return SegformerConfig( + image_size=self.image_size, + num_channels=self.num_channels, + num_encoder_blocks=self.num_encoder_blocks, + depths=self.depths, + hidden_sizes=self.hidden_sizes, + num_attention_heads=self.num_attention_heads, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + num_labels=self.num_labels, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = TFSegformerModel(config=config) + result = model(pixel_values, training=False) + expected_height = expected_width = self.image_size // (self.downsampling_rates[-1] * 2) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) + ) + + def create_and_check_for_image_segmentation(self, config, pixel_values, labels): + config.num_labels = self.num_labels + model = TFSegformerForSemanticSegmentation(config) + result = model(pixel_values, training=False) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) + ) + result = model(pixel_values, labels=labels, training=False) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + def prepare_config_and_inputs_for_keras_fit(self, for_segmentation: bool = False): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, seg_labels = config_and_inputs + if for_segmentation: + inputs_dict = {"pixel_values": pixel_values, "labels": seg_labels} + else: + inputs_dict = {"pixel_values": pixel_values, "labels": tf.zeros((self.batch_size))} + return config, inputs_dict + + +@require_tf +class TFSegformerModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (TFSegformerModel, TFSegformerForImageClassification, TFSegformerForSemanticSegmentation) + if is_tf_available() + else () + ) + pipeline_model_mapping = ( + {"feature-extraction": TFSegformerModel, "image-classification": TFSegformerForImageClassification} + if is_tf_available() + else {} + ) + + test_head_masking = False + test_onnx = False + test_pruning = False + test_resize_embeddings = False + + def setUp(self): + self.model_tester = TFSegformerModelTester(self) + self.config_tester = TFSegformerConfigTester(self, config_class=SegformerConfig, has_text_modality=False) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @unittest.skip("SegFormer does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods") + def test_model_common_attributes(self): + pass + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + + expected_num_attentions = sum(self.model_tester.depths) + self.assertEqual(len(attentions), expected_num_attentions) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + + self.assertEqual(len(attentions), expected_num_attentions) + + # verify the first attentions (first block, first layer) + expected_seq_len = (self.model_tester.image_size // 4) ** 2 + expected_reduced_seq_len = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len], + ) + + # verify the last attentions (last block, last layer) + expected_seq_len = (self.model_tester.image_size // 32) ** 2 + expected_reduced_seq_len = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 + self.assertListEqual( + list(attentions[-1].shape[-3:]), + [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), expected_num_attentions) + # verify the first attentions (first block, first layer) + expected_seq_len = (self.model_tester.image_size // 4) ** 2 + expected_reduced_seq_len = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_layers = self.model_tester.num_encoder_blocks + self.assertEqual(len(hidden_states), expected_num_layers) + + # verify the first hidden states (first block) + self.assertListEqual( + list(hidden_states[0].shape[-3:]), + [ + self.model_tester.hidden_sizes[0], + self.model_tester.image_size // 4, + self.model_tester.image_size // 4, + ], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_model_outputs_equivalence(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): + tuple_output = model(tuple_inputs, return_dict=False, **additional_kwargs) + dict_output = model(dict_inputs, return_dict=True, **additional_kwargs).to_tuple() + + def recursive_check(tuple_object, dict_object): + if isinstance(tuple_object, (List, Tuple)): + for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif tuple_object is None: + return + else: + self.assertTrue( + all(tf.equal(tuple_object, dict_object)), + msg=( + "Tuple and dict output are not equal. Difference:" + f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}" + ), + ) + + recursive_check(tuple_output, dict_output) + + for model_class in self.all_model_classes: + model = model_class(config) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + if self.has_attentions: + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + # todo: incorporate label support for semantic segmentation in `test_modeling_tf_common.py`. + + @unittest.skipIf( + not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, + reason="TF does not support backprop for grouped convolutions on CPU.", + ) + def test_dataset_conversion(self): + super().test_dataset_conversion() + + def check_keras_fit_results(self, val_loss1, val_loss2, atol=2e-1, rtol=2e-1): + self.assertTrue(np.allclose(val_loss1, val_loss2, atol=atol, rtol=rtol)) + + @unittest.skipIf( + not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, + reason="TF does not support backprop for grouped convolutions on CPU.", + ) + @slow + def test_keras_fit(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + # Since `TFSegformerModel` cannot operate with the default `fit()` method. + if model_class.__name__ != "TFSegformerModel": + model = model_class(config) + if getattr(model, "hf_compute_loss", None): + super().test_keras_fit() + + def test_loss_computation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def apply(model): + for_segmentation = True if model_class.__name__ == "TFSegformerForSemanticSegmentation" else False + # The number of elements in the loss should be the same as the number of elements in the label + _, prepared_for_class = self.model_tester.prepare_config_and_inputs_for_keras_fit( + for_segmentation=for_segmentation + ) + added_label = prepared_for_class[sorted(prepared_for_class.keys() - inputs_dict.keys(), reverse=True)[0]] + loss_size = tf.size(added_label) + + # Test that model correctly compute the loss with kwargs + possible_input_names = {"input_ids", "pixel_values", "input_features"} + input_name = possible_input_names.intersection(set(prepared_for_class)).pop() + model_input = prepared_for_class.pop(input_name) + + loss = model(model_input, **prepared_for_class)[0] + + if model_class.__name__ == "TFSegformerForSemanticSegmentation": + # Semantic segmentation loss is computed similarly as + # https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_tf_utils.py#L210. + self.assertEqual(loss.shape, (1,)) + else: + self.assertEqual(loss.shape, [loss_size]) + + # Test that model correctly compute the loss with a dict + _, prepared_for_class = self.model_tester.prepare_config_and_inputs_for_keras_fit( + for_segmentation=for_segmentation + ) + loss = model(**prepared_for_class)[0] + + if model_class.__name__ == "TFSegformerForSemanticSegmentation": + self.assertEqual(loss.shape, (1,)) + else: + self.assertEqual(loss.shape, [loss_size]) + + # Test that model correctly compute the loss with a tuple + label_keys = prepared_for_class.keys() - inputs_dict.keys() + signature = inspect.signature(model.call).parameters + signature_names = list(signature.keys()) + + # Create a dictionary holding the location of the tensors in the tuple + tuple_index_mapping = {0: input_name} + for label_key in label_keys: + label_key_index = signature_names.index(label_key) + tuple_index_mapping[label_key_index] = label_key + sorted_tuple_index_mapping = sorted(tuple_index_mapping.items()) + # Initialize a list with their default values, update the values and convert to a tuple + list_input = [] + + for name in signature_names: + if name != "kwargs": + list_input.append(signature[name].default) + + for index, value in sorted_tuple_index_mapping: + list_input[index] = prepared_for_class[value] + + tuple_input = tuple(list_input) + + # Send to model + loss = model(tuple_input[:-1])[0] + if model_class.__name__ == "TFSegformerForSemanticSegmentation": + self.assertEqual(loss.shape, (1,)) + else: + self.assertEqual(loss.shape, [loss_size]) + + for model_class in self.all_model_classes: + # Since `TFSegformerModel` won't have labels against which we + # could compute loss. + if model_class.__name__ != "TFSegformerModel": + model = model_class(config) + apply(model) + + def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=2e-4, name="outputs", attributes=None): + # We override with a slightly higher tol value, as semseg models tend to diverge a bit more + super().check_pt_tf_outputs(tf_outputs, pt_outputs, model_class, tol, name, attributes) + + @slow + def test_model_from_pretrained(self): + for model_name in TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFSegformerModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_tf +class TFSegformerModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_image_segmentation_ade(self): + # only resize + normalize + image_processor = SegformerImageProcessor( + image_scale=(512, 512), keep_ratio=False, align=False, do_random_crop=False + ) + model = TFSegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512") + + image = prepare_img() + encoded_inputs = image_processor(images=image, return_tensors="tf") + pixel_values = encoded_inputs.pixel_values + + outputs = model(pixel_values, training=False) + + expected_shape = tf.TensorShape((1, model.config.num_labels, 128, 128)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = tf.constant( + [ + [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], + [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], + [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], + ] + ) + tf.debugging.assert_near(outputs.logits[0, :3, :3, :3], expected_slice, atol=1e-4) + + @slow + def test_inference_image_segmentation_city(self): + # only resize + normalize + image_processor = SegformerImageProcessor( + image_scale=(512, 512), keep_ratio=False, align=False, do_random_crop=False + ) + model = TFSegformerForSemanticSegmentation.from_pretrained( + "nvidia/segformer-b1-finetuned-cityscapes-1024-1024" + ) + + image = prepare_img() + encoded_inputs = image_processor(images=image, return_tensors="tf") + pixel_values = encoded_inputs.pixel_values + + outputs = model(pixel_values, training=False) + + expected_shape = tf.TensorShape((1, model.config.num_labels, 128, 128)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = tf.constant( + [ + [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], + [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], + [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], + ] + ) + tf.debugging.assert_near(outputs.logits[0, :3, :3, :3], expected_slice, atol=1e-1) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew/test_modeling_sew.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew/test_modeling_sew.py new file mode 100644 index 0000000000000000000000000000000000000000..528d5f84185e6e0301f9fe1203f89f4d43dd77b6 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew/test_modeling_sew.py @@ -0,0 +1,571 @@ +# coding=utf-8 +# 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 Hubert model. """ + + +import math +import unittest + +import pytest + +from transformers import SEWConfig, is_torch_available +from transformers.testing_utils import require_soundfile, require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + SEWForCTC, + SEWForSequenceClassification, + SEWModel, + Wav2Vec2FeatureExtractor, + Wav2Vec2Processor, + ) + from transformers.models.hubert.modeling_hubert import _compute_mask_indices + + +class SEWModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=1024, # speech is longer + is_training=False, + hidden_size=32, + feat_extract_norm="group", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(64, 32, 32), + conv_stride=(5, 2, 1), + conv_kernel=(10, 3, 1), + conv_bias=False, + num_conv_pos_embeddings=31, + num_conv_pos_embedding_groups=2, + squeeze_factor=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout=0.1, + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + vocab_size=32, + do_stable_layer_norm=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.squeeze_factor = squeeze_factor + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout = hidden_dropout + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.scope = scope + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length // self.squeeze_factor + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + + return config, input_values, attention_mask + + def get_config(self): + return SEWConfig( + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + squeeze_factor=self.squeeze_factor, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout=self.hidden_dropout, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + ) + + def create_and_check_model(self, config, input_values, attention_mask): + model = SEWModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_batch_inference(self, config, input_values, *args): + # test does not pass for models making use of `group_norm` + # check: https://github.com/pytorch/fairseq/issues/3227 + model = SEWModel(config=config) + model.to(torch_device) + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0.0 + + batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state + + for i in range(input_values.shape[0]): + input_slice = input_values[i : i + 1, : input_lengths[i]] + output = model(input_slice).last_hidden_state + + batch_output = batch_outputs[i : i + 1, : output.shape[1]] + self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) + + def check_ctc_loss(self, config, input_values, *args): + model = SEWForCTC(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + model.config.ctc_loss_reduction = "sum" + sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + model.config.ctc_loss_reduction = "mean" + mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(sum_loss, float)) + self.parent.assertTrue(isinstance(mean_loss, float)) + + def check_ctc_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = SEWForCTC(config=config) + model.to(torch_device) + model.train() + + # freeze feature encoder + model.freeze_feature_encoder() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + if max_length_labels[i] < labels.shape[-1]: + # it's important that we make sure that target lengths are at least + # one shorter than logit lengths to prevent -inf + labels[i, max_length_labels[i] - 1 :] = -100 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_seq_classifier_loss(self, config, input_values, *args): + model = SEWForSequenceClassification(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + unmasked_loss = model(input_values, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(masked_loss, float)) + self.parent.assertTrue(isinstance(unmasked_loss, float)) + self.parent.assertTrue(masked_loss != unmasked_loss) + + def check_seq_classifier_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = SEWForSequenceClassification(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_labels_out_of_vocab(self, config, input_values, *args): + model = SEWForCTC(config) + model.to(torch_device) + model.train() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) + + with pytest.raises(ValueError): + model(input_values, labels=labels) + + def prepare_config_and_inputs_for_common(self): + config, input_values, attention_mask = self.prepare_config_and_inputs() + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class SEWModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (SEWForCTC, SEWModel, SEWForSequenceClassification) if is_torch_available() else () + pipeline_model_mapping = ( + { + "audio-classification": SEWForSequenceClassification, + "automatic-speech-recognition": SEWForCTC, + "feature-extraction": SEWModel, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_headmasking = False + + def setUp(self): + self.model_tester = SEWModelTester(self) + self.config_tester = ConfigTester(self, config_class=SEWConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # Hubert has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # SEW cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # SEW has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + def test_seq_classifier_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_loss(*config_and_inputs) + + def test_seq_classifier_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_training(*config_and_inputs) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "masked_spec_embed", + "quantizer.weight_proj.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + @unittest.skip(reason="Feed forward chunking is not implemented") + def test_feed_forward_chunking(self): + pass + + @slow + def test_model_from_pretrained(self): + model = SEWModel.from_pretrained("asapp/sew-tiny-100k") + self.assertIsNotNone(model) + + +@require_torch +class SEWUtilsTest(unittest.TestCase): + def test_compute_mask_indices(self): + batch_size = 4 + sequence_length = 60 + mask_prob = 0.5 + mask_length = 1 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + self.assertListEqual(mask.sum(axis=-1).tolist(), [mask_prob * sequence_length for _ in range(batch_size)]) + + def test_compute_mask_indices_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + # because of overlap mask don't have to add up exactly to `mask_prob * sequence_length`, but have to be smaller or equal + for batch_sum in mask.sum(axis=-1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + +@require_torch +@require_soundfile +@slow +class SEWModelIntegrationTest(unittest.TestCase): + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter( + lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] + )[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_inference_pretrained_batched(self): + model = SEWModel.from_pretrained("asapp/sew-tiny-100k").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("asapp/sew-tiny-100k") + + input_speech = self._load_datasamples(2) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + + with torch.no_grad(): + outputs = model(input_values).last_hidden_state + + # expected outputs taken from the original SEW implementation + expected_outputs_first = torch.tensor( + [ + [ + [0.1509, 0.5372, 0.3061, -0.1694], + [-0.1700, 0.5764, 0.2753, -0.1299], + [0.1281, 0.7949, 0.2342, -0.1624], + [-0.1627, 0.6710, 0.2215, -0.1317], + ], + [ + [0.0408, 1.4355, 0.8605, -0.0968], + [0.0393, 1.2368, 0.6826, 0.0364], + [-0.1269, 1.9215, 1.1677, -0.1297], + [-0.1654, 1.6524, 0.6877, -0.0196], + ], + ], + device=torch_device, + ) + expected_outputs_last = torch.tensor( + [ + [ + [1.3379, -0.1450, -0.1500, -0.0515], + [0.8364, -0.1680, -0.1248, -0.0689], + [1.2791, -0.1507, -0.1523, -0.0564], + [0.8208, -0.1690, -0.1199, -0.0751], + ], + [ + [0.6959, -0.0861, -0.1235, -0.0861], + [0.4700, -0.1686, -0.1141, -0.1199], + [1.0776, -0.1137, -0.0124, -0.0472], + [0.5774, -0.1675, -0.0376, -0.0823], + ], + ], + device=torch_device, + ) + expected_output_sum = 62146.7422 + + self.assertTrue(torch.allclose(outputs[:, :4, :4], expected_outputs_first, atol=5e-3)) + self.assertTrue(torch.allclose(outputs[:, -4:, -4:], expected_outputs_last, atol=5e-3)) + self.assertTrue(abs(outputs.sum() - expected_output_sum) < 5) + + def test_inference_ctc_batched(self): + model = SEWForCTC.from_pretrained("asapp/sew-tiny-100k-ft-ls100h").to(torch_device) + processor = Wav2Vec2Processor.from_pretrained("asapp/sew-tiny-100k-ft-ls100h", do_lower_case=True) + + input_speech = self._load_datasamples(2) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + + with torch.no_grad(): + logits = model(input_values).logits + + predicted_ids = torch.argmax(logits, dim=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "swet covered brian's body trickling into the tightloine closs hat was the only garment he wore", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew_d/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew_d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew_d/test_modeling_sew_d.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew_d/test_modeling_sew_d.py new file mode 100644 index 0000000000000000000000000000000000000000..6fda7963a8009c0c1bde670f500853faedfbc125 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/sew_d/test_modeling_sew_d.py @@ -0,0 +1,585 @@ +# coding=utf-8 +# 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 Hubert model. """ + + +import math +import unittest + +import pytest + +from transformers import SEWDConfig, is_torch_available +from transformers.testing_utils import require_soundfile, require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + SEWDForCTC, + SEWDForSequenceClassification, + SEWDModel, + Wav2Vec2FeatureExtractor, + Wav2Vec2Processor, + ) + from transformers.models.hubert.modeling_hubert import _compute_mask_indices + + +class SEWDModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=1024, # speech is longer + is_training=False, + hidden_size=32, + feat_extract_norm="group", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(64, 32, 32), + conv_stride=(5, 2, 1), + conv_kernel=(10, 3, 1), + conv_bias=False, + num_conv_pos_embeddings=31, + num_conv_pos_embedding_groups=2, + squeeze_factor=2, + max_position_embeddings=512, + position_buckets=256, + share_att_key=True, + relative_attention=True, + position_biased_input=False, + pos_att_type=("p2c", "c2p"), + norm_rel_ebd="layer_norm", + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout=0.1, + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + vocab_size=32, + do_stable_layer_norm=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.squeeze_factor = squeeze_factor + self.max_position_embeddings = max_position_embeddings + self.position_buckets = position_buckets + self.share_att_key = share_att_key + self.relative_attention = relative_attention + self.position_biased_input = position_biased_input + self.pos_att_type = pos_att_type + self.norm_rel_ebd = norm_rel_ebd + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout = hidden_dropout + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.scope = scope + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length // self.squeeze_factor + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + + return config, input_values, attention_mask + + def get_config(self): + return SEWDConfig( + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + squeeze_factor=self.squeeze_factor, + max_position_embeddings=self.max_position_embeddings, + position_buckets=self.position_buckets, + share_att_key=self.share_att_key, + relative_attention=self.relative_attention, + position_biased_input=self.position_biased_input, + pos_att_type=self.pos_att_type, + norm_rel_ebd=self.norm_rel_ebd, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout=self.hidden_dropout, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + ) + + def create_and_check_model(self, config, input_values, attention_mask): + model = SEWDModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_batch_inference(self, config, input_values, *args): + # test does not pass for models making use of `group_norm` + # check: https://github.com/pytorch/fairseq/issues/3227 + model = SEWDModel(config=config) + model.to(torch_device) + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0.0 + + batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state + + for i in range(input_values.shape[0]): + input_slice = input_values[i : i + 1, : input_lengths[i]] + output = model(input_slice).last_hidden_state + + batch_output = batch_outputs[i : i + 1, : output.shape[1]] + self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) + + def check_ctc_loss(self, config, input_values, *args): + model = SEWDForCTC(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + model.config.ctc_loss_reduction = "sum" + sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + model.config.ctc_loss_reduction = "mean" + mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(sum_loss, float)) + self.parent.assertTrue(isinstance(mean_loss, float)) + + def check_ctc_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = SEWDForCTC(config=config) + model.to(torch_device) + model.train() + + # freeze feature encoder + model.freeze_feature_encoder() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + if max_length_labels[i] < labels.shape[-1]: + # it's important that we make sure that target lengths are at least + # one shorter than logit lengths to prevent -inf + labels[i, max_length_labels[i] - 1 :] = -100 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_seq_classifier_loss(self, config, input_values, *args): + model = SEWDForSequenceClassification(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + unmasked_loss = model(input_values, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(masked_loss, float)) + self.parent.assertTrue(isinstance(unmasked_loss, float)) + self.parent.assertTrue(masked_loss != unmasked_loss) + + def check_seq_classifier_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = SEWDForSequenceClassification(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_labels_out_of_vocab(self, config, input_values, *args): + model = SEWDForCTC(config) + model.to(torch_device) + model.train() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) + + with pytest.raises(ValueError): + model(input_values, labels=labels) + + def prepare_config_and_inputs_for_common(self): + config, input_values, attention_mask = self.prepare_config_and_inputs() + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class SEWDModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (SEWDForCTC, SEWDModel, SEWDForSequenceClassification) if is_torch_available() else () + pipeline_model_mapping = ( + { + "audio-classification": SEWDForSequenceClassification, + "automatic-speech-recognition": SEWDForCTC, + "feature-extraction": SEWDModel, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_headmasking = False + test_torchscript = False + + def setUp(self): + self.model_tester = SEWDModelTester(self) + self.config_tester = ConfigTester(self, config_class=SEWDConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # Hubert has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # SEW cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # SEW has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "masked_spec_embed", + "quantizer.weight_proj.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + @unittest.skip(reason="Feed forward chunking is not implemented") + def test_feed_forward_chunking(self): + pass + + @slow + def test_model_from_pretrained(self): + model = SEWDModel.from_pretrained("asapp/sew-d-tiny-100k") + self.assertIsNotNone(model) + + +@require_torch +class SEWDUtilsTest(unittest.TestCase): + def test_compute_mask_indices(self): + batch_size = 4 + sequence_length = 60 + mask_prob = 0.5 + mask_length = 1 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + self.assertListEqual(mask.sum(axis=-1).tolist(), [mask_prob * sequence_length for _ in range(batch_size)]) + + def test_compute_mask_indices_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + # because of overlap mask don't have to add up exactly to `mask_prob * sequence_length`, but have to be smaller or equal + for batch_sum in mask.sum(axis=-1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + +@require_torch +@require_soundfile +@slow +class SEWDModelIntegrationTest(unittest.TestCase): + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter( + lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] + )[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_inference_pretrained_batched(self): + model = SEWDModel.from_pretrained("asapp/sew-d-tiny-100k").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("asapp/sew-d-tiny-100k") + + input_speech = self._load_datasamples(2) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + + with torch.no_grad(): + outputs = model(input_values).last_hidden_state + + # expected outputs taken from the original SEW-D implementation + expected_outputs_first = torch.tensor( + [ + [ + [-0.1619, 0.6995, 0.4062, -0.1014], + [-0.1364, 0.5960, 0.0952, -0.0873], + [-0.1572, 0.5718, 0.4228, -0.0864], + [-0.1325, 0.6823, 0.1387, -0.0871], + ], + [ + [-0.1296, 0.4008, 0.4952, -0.1450], + [-0.1152, 0.3693, 0.3037, -0.1290], + [-0.1194, 0.6074, 0.3531, -0.1466], + [-0.1113, 0.3135, 0.2224, -0.1338], + ], + ], + device=torch_device, + ) + expected_outputs_last = torch.tensor( + [ + [ + [-0.1577, 0.5108, 0.8553, 0.2550], + [-0.1530, 0.3580, 0.6143, 0.2672], + [-0.1535, 0.4954, 0.8503, 0.1387], + [-0.1572, 0.3363, 0.6217, 0.1490], + ], + [ + [-0.1338, 0.5459, 0.9607, -0.1133], + [-0.1502, 0.3738, 0.7313, -0.0986], + [-0.0953, 0.4708, 1.0821, -0.0944], + [-0.1474, 0.3598, 0.7248, -0.0748], + ], + ], + device=torch_device, + ) + expected_output_sum = 54201.0469 + + self.assertTrue(torch.allclose(outputs[:, :4, :4], expected_outputs_first, atol=1e-3)) + self.assertTrue(torch.allclose(outputs[:, -4:, -4:], expected_outputs_last, atol=1e-3)) + self.assertTrue(abs(outputs.sum() - expected_output_sum) < 1) + + def test_inference_ctc_batched(self): + model = SEWDForCTC.from_pretrained("asapp/sew-d-tiny-100k-ft-ls100h").to(torch_device) + processor = Wav2Vec2Processor.from_pretrained("asapp/sew-d-tiny-100k-ft-ls100h", do_lower_case=True) + + input_speech = self._load_datasamples(2) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + + with torch.no_grad(): + logits = model(input_values).logits + + predicted_ids = torch.argmax(logits, dim=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "swet covered breon's body trickling into the titlowing closs that was the only garmened he war", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_encoder_decoder/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_encoder_decoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_encoder_decoder/test_modeling_flax_speech_encoder_decoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_encoder_decoder/test_modeling_flax_speech_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..f2c75e702bf765c1b20977ab883c9cf621d3c20d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_encoder_decoder/test_modeling_flax_speech_encoder_decoder.py @@ -0,0 +1,923 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. team. +# +# 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 tempfile +import unittest + +import numpy as np + +from transformers import is_flax_available, is_torch_available +from transformers.testing_utils import is_pt_flax_cross_test, require_flax, slow, torch_device + +from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask +from ..bart.test_modeling_flax_bart import FlaxBartStandaloneDecoderModelTester +from ..bert.test_modeling_flax_bert import FlaxBertModelTester +from ..gpt2.test_modeling_flax_gpt2 import FlaxGPT2ModelTester +from ..wav2vec2.test_modeling_flax_wav2vec2 import FlaxWav2Vec2ModelTester + + +if is_flax_available(): + import jax + import jax.numpy as jnp + from flax.training.common_utils import onehot + from flax.traverse_util import flatten_dict + + from transformers import ( + FlaxBartForCausalLM, + FlaxBertForCausalLM, + FlaxGPT2LMHeadModel, + FlaxSpeechEncoderDecoderModel, + FlaxWav2Vec2Model, + SpeechEncoderDecoderConfig, + ) + from transformers.modeling_flax_outputs import FlaxBaseModelOutput + from transformers.modeling_flax_pytorch_utils import ( + convert_pytorch_state_dict_to_flax, + load_flax_weights_in_pytorch_model, + ) + +if is_torch_available(): + import torch + + from transformers import SpeechEncoderDecoderModel + + +@require_flax +class FlaxEncoderDecoderMixin: + def get_encoder_decoder_model(self, config, decoder_config): + raise NotImplementedError + + def prepare_config_and_inputs(self): + raise NotImplementedError + + def get_pretrained_model(self): + raise NotImplementedError + + def check_encoder_decoder_model_from_pretrained_configs( + self, + config, + inputs, + attention_mask, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + self.assertTrue(encoder_decoder_config.decoder.is_decoder) + + enc_dec_model = FlaxSpeechEncoderDecoderModel(encoder_decoder_config) + + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + self.assertFalse(enc_dec_model.config.tie_word_embeddings) + + outputs_encoder_decoder = enc_dec_model( + inputs=inputs, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_encoder_decoder_model( + self, + config, + inputs, + attention_mask, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + self.assertTrue(enc_dec_model.config.decoder.is_decoder) + self.assertTrue(enc_dec_model.config.decoder.add_cross_attention) + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + + outputs_encoder_decoder = enc_dec_model( + inputs=inputs, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + encoder_outputs = FlaxBaseModelOutput(last_hidden_state=outputs_encoder_decoder.encoder_hidden_states[-1]) + + outputs_encoder_decoder = enc_dec_model( + attention_mask, decoder_input_ids, decoder_attention_mask, encoder_outputs=encoder_outputs + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_encoder_decoder_model_from_pretrained( + self, + config, + inputs, + attention_mask, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + return_dict, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model, "return_dict": return_dict} + enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + outputs_encoder_decoder = enc_dec_model( + inputs=inputs, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_hidden_states=True, + return_dict=True, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_save_and_load( + self, + config, + inputs, + attention_mask, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} + enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + + outputs = enc_dec_model( + inputs=inputs, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + out_2 = np.array(outputs[0]) + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmpdirname: + enc_dec_model.save_pretrained(tmpdirname) + FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname) + + after_outputs = enc_dec_model( + inputs=inputs, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + out_1 = np.array(after_outputs[0]) + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 4e-2) + + def check_encoder_decoder_model_from_encoder_decoder_pretrained( + self, + config, + inputs, + attention_mask, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + # assert that loading encoder and decoder models from configs has been correctly executed + self.assertEqual(config.add_adapter, encoder_model.config.add_adapter) + self.assertEqual(decoder_config.use_cache, decoder_model.config.use_cache) + + with tempfile.TemporaryDirectory() as enc_tmpdir: + with tempfile.TemporaryDirectory() as dec_tmpdir: + encoder_model.save_pretrained(enc_tmpdir) + decoder_model.save_pretrained(dec_tmpdir) + # load a model from pretrained encoder and decoder checkpoints, setting one encoder and one decoder kwarg opposite to that specified in their respective configs + enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( + encoder_pretrained_model_name_or_path=enc_tmpdir, + decoder_pretrained_model_name_or_path=dec_tmpdir, + encoder_add_adapter=not config.add_adapter, + decoder_use_cache=not decoder_config.use_cache, + ) + + # assert that setting encoder and decoder kwargs opposite to those in the configs has correctly been applied + self.assertNotEqual(config.add_adapter, enc_dec_model.config.encoder.add_adapter) + self.assertNotEqual(decoder_config.use_cache, enc_dec_model.config.decoder.use_cache) + + outputs_encoder_decoder = enc_dec_model( + inputs=inputs, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_hidden_states=True, + return_dict=True, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_encoder_decoder_model_output_attentions( + self, + config, + inputs, + attention_mask, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + # make the decoder inputs a different shape from the encoder inputs to harden the test + decoder_input_ids = decoder_input_ids[:, :-1] + decoder_attention_mask = decoder_attention_mask[:, :-1] + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} + enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + outputs_encoder_decoder = enc_dec_model( + inputs=inputs, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_attentions=True, + ) + + encoder_attentions = outputs_encoder_decoder["encoder_attentions"] + self.assertEqual(len(encoder_attentions), config.num_hidden_layers) + + seq_len = enc_dec_model._get_feat_extract_output_lengths(inputs.shape[1]) + self.assertEqual(encoder_attentions[0].shape[-3:], (config.num_attention_heads, seq_len, seq_len)) + + decoder_attentions = outputs_encoder_decoder["decoder_attentions"] + num_decoder_layers = ( + decoder_config.num_decoder_layers + if hasattr(decoder_config, "num_decoder_layers") + else decoder_config.num_hidden_layers + ) + self.assertEqual(len(decoder_attentions), num_decoder_layers) + + self.assertEqual( + decoder_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), + ) + + cross_attentions = outputs_encoder_decoder["cross_attentions"] + self.assertEqual(len(cross_attentions), num_decoder_layers) + + cross_attention_input_seq_len = decoder_input_ids.shape[-1] + + self.assertEqual( + cross_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, cross_attention_input_seq_len, seq_len), + ) + + def check_encoder_decoder_model_generate(self, inputs, config, decoder_config, **kwargs): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} + enc_dec_model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + + pad_token_id = enc_dec_model.config.decoder.pad_token_id + eos_token_id = enc_dec_model.config.decoder.eos_token_id + decoder_start_token_id = enc_dec_model.config.decoder.decoder_start_token_id + + # Copied from generation.utils (GPT2 doesn't have `pad_token_id`) + if pad_token_id is None and eos_token_id is not None: + pad_token_id = eos_token_id + if decoder_start_token_id is None: + decoder_start_token_id = enc_dec_model.config.decoder.bos_token_id + + # Bert does not have a bos token id, so use pad_token_id instead + # Copied from `test_modeling_encoder_decoder.py` + if decoder_start_token_id is None: + decoder_start_token_id = pad_token_id + + generated_output = enc_dec_model.generate( + inputs, + pad_token_id=pad_token_id, + eos_token_id=eos_token_id, + decoder_start_token_id=decoder_start_token_id, + ) + generated_sequences = generated_output.sequences + self.assertEqual(generated_sequences.shape, (inputs.shape[0],) + (decoder_config.max_length,)) + + def check_freeze_feature_encoder( + self, + config, + inputs, + attention_mask, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + enc_dec_model = FlaxSpeechEncoderDecoderModel(encoder_decoder_config) + params = enc_dec_model.params + + def cross_entropy(logits, labels): + return -jnp.sum(labels * jax.nn.log_softmax(logits, axis=-1), axis=-1) + + # define a dummy loss function for computing the loss over a forward pass + def compute_loss( + params, + inputs, + attention_mask, + decoder_input_ids, + freeze_feature_encoder: bool = False, + ): + outputs_enc_dec = enc_dec_model( + inputs=inputs, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + freeze_feature_encoder=freeze_feature_encoder, + params=params, + ) + logits = outputs_enc_dec.logits + vocab_size = logits.shape[-1] + loss = cross_entropy(logits, onehot(labels=decoder_input_ids, num_classes=vocab_size)).sum() + return (loss, logits) + + # transform the loss function to get the gradients + grad_fn = jax.value_and_grad(compute_loss, has_aux=True) + + # compute the loss, logits, and gradients for the unfrozen model + (loss, logits), grads = grad_fn( + params, inputs, attention_mask, decoder_input_ids, freeze_feature_encoder=False + ) + + # compare to the loss, logits and gradients for the frozen model + (loss_frozen, logits_frozen), grads_frozen = grad_fn( + params, inputs, attention_mask, decoder_input_ids, freeze_feature_encoder=True + ) + + # ensure that the logits and losses remain precisely equal + self.assertTrue((logits == logits_frozen).all()) + self.assertEqual(loss, loss_frozen) + + grads = flatten_dict(grads) + grads_frozen = flatten_dict(grads_frozen) + + # ensure that the dicts of gradients contain the same keys + self.assertEqual(grads.keys(), grads_frozen.keys()) + + # ensure that the gradients of the feature extractor layers are precisely zero when frozen and contain non-zero entries when unfrozen + feature_extractor_grads = tuple(grads[k] for k in grads if "feature_extractor" in k) + feature_extractor_grads_frozen = tuple(grads_frozen[k] for k in grads_frozen if "feature_extractor" in k) + + for feature_extractor_grad, feature_extractor_grad_frozen in zip( + feature_extractor_grads, feature_extractor_grads_frozen + ): + self.assertTrue((feature_extractor_grad_frozen == 0.0).all()) + self.assertTrue((feature_extractor_grad > 0.0).any()) + + # ensure that the gradients of all unfrozen layers remain precisely equal, i.e. all layers excluding the frozen 'feature_extractor' + grads = tuple(grads[k] for k in grads if "feature_extractor" not in k) + grads_frozen = tuple(grads_frozen[k] for k in grads_frozen if "feature_extractor" not in k) + + for grad, grad_frozen in zip(grads, grads_frozen): + self.assertTrue((grad == grad_frozen).all()) + + def check_pt_flax_equivalence(self, pt_model, fx_model, inputs_dict): + pt_model.to(torch_device) + pt_model.eval() + + # prepare inputs + flax_inputs = inputs_dict + pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs).to_tuple() + + fx_outputs = fx_model(**inputs_dict).to_tuple() + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output in zip(fx_outputs, pt_outputs): + self.assert_almost_equals(fx_output, pt_output.numpy(), 1e-5) + + # PT -> Flax + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**inputs_dict).to_tuple() + self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output_loaded, pt_output in zip(fx_outputs_loaded, pt_outputs): + self.assert_almost_equals(fx_output_loaded, pt_output.numpy(), 1e-5) + + # Flax -> PT + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) + + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs).to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output_loaded in zip(fx_outputs, pt_outputs_loaded): + self.assert_almost_equals(fx_output, pt_output_loaded.numpy(), 1e-5) + + def check_equivalence_pt_to_flax(self, config, decoder_config, inputs_dict): + encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + + pt_model = SpeechEncoderDecoderModel(encoder_decoder_config) + fx_model = FlaxSpeechEncoderDecoderModel(encoder_decoder_config) + + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + self.check_pt_flax_equivalence(pt_model, fx_model, inputs_dict) + + def check_equivalence_flax_to_pt(self, config, decoder_config, inputs_dict): + encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + + pt_model = SpeechEncoderDecoderModel(encoder_decoder_config) + fx_model = FlaxSpeechEncoderDecoderModel(encoder_decoder_config) + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + + self.check_pt_flax_equivalence(pt_model, fx_model, inputs_dict) + + def test_encoder_decoder_model_from_pretrained_configs(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained_configs(**input_ids_dict) + + def test_encoder_decoder_model_from_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=False) + + def test_encoder_decoder_model_from_pretrained_return_dict(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=True) + + def test_save_and_load_from_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_save_and_load(**input_ids_dict) + + def test_encoder_decoder_model_from_encoder_decoder_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_encoder_decoder_pretrained(**input_ids_dict) + + def test_encoder_decoder_model_output_attentions(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_output_attentions(**input_ids_dict) + + def test_freeze_feature_encoder(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_freeze_feature_encoder(**input_ids_dict) + + def test_encoder_decoder_model_generate(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_generate(**input_ids_dict) + + def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): + diff = np.abs((a - b)).max() + self.assertLessEqual(diff, tol, f"Difference between torch and flax is {diff} (>= {tol}).") + + @is_pt_flax_cross_test + def test_pt_flax_equivalence(self): + config_inputs_dict = self.prepare_config_and_inputs() + config = config_inputs_dict.pop("config") + decoder_config = config_inputs_dict.pop("decoder_config") + + inputs_dict = config_inputs_dict + # `encoder_hidden_states` is not used in model call/forward + del inputs_dict["encoder_hidden_states"] + + # Avoid the case where a sequence has no place to attend (after combined with the causal attention mask) + batch_size = inputs_dict["decoder_attention_mask"].shape[0] + inputs_dict["decoder_attention_mask"] = np.concatenate( + [np.ones(shape=(batch_size, 1)), inputs_dict["decoder_attention_mask"][:, 1:]], axis=1 + ) + + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + decoder_config.use_cache = False + + self.assertTrue(decoder_config.cross_attention_hidden_size is None) + + # check without `enc_to_dec_proj` projection + decoder_config.hidden_size = config.hidden_size + self.assertTrue(config.hidden_size == decoder_config.hidden_size) + self.check_equivalence_pt_to_flax(config, decoder_config, inputs_dict) + self.check_equivalence_flax_to_pt(config, decoder_config, inputs_dict) + + # check `enc_to_dec_proj` work as expected + decoder_config.hidden_size = decoder_config.hidden_size * 2 + self.assertTrue(config.hidden_size != decoder_config.hidden_size) + self.check_equivalence_pt_to_flax(config, decoder_config, inputs_dict) + self.check_equivalence_flax_to_pt(config, decoder_config, inputs_dict) + + # check `add_adapter` works as expected + config.add_adapter = True + self.assertTrue(config.add_adapter) + self.check_equivalence_pt_to_flax(config, decoder_config, inputs_dict) + self.check_equivalence_flax_to_pt(config, decoder_config, inputs_dict) + + @slow + def test_real_model_save_load_from_pretrained(self): + model_2 = self.get_pretrained_model() + inputs = ids_tensor([13, 5], model_2.config.encoder.vocab_size) + decoder_input_ids = ids_tensor([13, 1], model_2.config.decoder.vocab_size) + attention_mask = ids_tensor([13, 5], vocab_size=2) + + outputs = model_2( + inputs=inputs, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + ) + out_2 = np.array(outputs[0]) + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmp_dirname: + model_2.save_pretrained(tmp_dirname) + model_1 = FlaxSpeechEncoderDecoderModel.from_pretrained(tmp_dirname) + + after_outputs = model_1( + inputs=inputs, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + ) + out_1 = np.array(after_outputs[0]) + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 4e-2) + + +@require_flax +class FlaxWav2Vec2GPT2ModelTest(FlaxEncoderDecoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( + "facebook/wav2vec2-large-lv60", "gpt2-medium" + ) + batch_size = 13 + input_values = floats_tensor([batch_size, 512], scale=1.0) + attention_mask = random_attention_mask([batch_size, 512]) + decoder_input_ids = ids_tensor([batch_size, 4], model.config.decoder.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs = { + "inputs": input_values, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + return model, inputs + + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = FlaxWav2Vec2Model(config) + decoder_model = FlaxGPT2LMHeadModel(decoder_config) + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + model_tester_encoder = FlaxWav2Vec2ModelTester(self, batch_size=13) + model_tester_decoder = FlaxGPT2ModelTester(self, batch_size=13) + encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() + decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder() + (config, inputs, attention_mask) = encoder_config_and_inputs + ( + decoder_config, + decoder_input_ids, + decoder_attention_mask, + encoder_hidden_states, + encoder_attention_mask, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + return { + "config": config, + "inputs": inputs, + "attention_mask": attention_mask, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "encoder_hidden_states": encoder_hidden_states, + } + + @slow + def test_flaxwav2vec2gpt2_pt_flax_equivalence(self): + pt_model = SpeechEncoderDecoderModel.from_pretrained("jsnfly/wav2vec2-large-xlsr-53-german-gpt2") + fx_model = FlaxSpeechEncoderDecoderModel.from_pretrained( + "jsnfly/wav2vec2-large-xlsr-53-german-gpt2", from_pt=True + ) + + pt_model.to(torch_device) + pt_model.eval() + + # prepare inputs + batch_size = 13 + input_values = floats_tensor([batch_size, 512], scale=1.0) + attention_mask = random_attention_mask([batch_size, 512]) + decoder_input_ids = ids_tensor([batch_size, 4], fx_model.config.decoder.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs_dict = { + "inputs": input_values, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + flax_inputs = inputs_dict + pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + pt_logits = pt_outputs.logits + pt_outputs = pt_outputs.to_tuple() + + fx_outputs = fx_model(**inputs_dict) + fx_logits = fx_outputs.logits + fx_outputs = fx_outputs.to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits, pt_logits.numpy(), 4e-2) + + # PT -> Flax + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**inputs_dict) + fx_logits_loaded = fx_outputs_loaded.logits + fx_outputs_loaded = fx_outputs_loaded.to_tuple() + self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits_loaded, pt_logits.numpy(), 4e-2) + + # Flax -> PT + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) + + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs) + pt_logits_loaded = pt_outputs_loaded.logits + pt_outputs_loaded = pt_outputs_loaded.to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits, pt_logits_loaded.numpy(), 4e-2) + + +@require_flax +class FlaxWav2Vec2BartModelTest(FlaxEncoderDecoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( + "facebook/wav2vec2-large-lv60", "bart-large" + ) + batch_size = 13 + input_values = floats_tensor([batch_size, 512], scale=1.0) + attention_mask = random_attention_mask([batch_size, 512]) + decoder_input_ids = ids_tensor([batch_size, 4], model.config.decoder.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs = { + "inputs": input_values, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + return model, inputs + + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = FlaxWav2Vec2Model(config) + decoder_model = FlaxBartForCausalLM(decoder_config) + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + model_tester_encoder = FlaxWav2Vec2ModelTester(self, batch_size=13) + model_tester_decoder = FlaxBartStandaloneDecoderModelTester(self, batch_size=13) + encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() + decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder() + (config, inputs, attention_mask) = encoder_config_and_inputs + ( + decoder_config, + decoder_input_ids, + decoder_attention_mask, + encoder_hidden_states, + encoder_attention_mask, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + return { + "config": config, + "inputs": inputs, + "attention_mask": attention_mask, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "encoder_hidden_states": encoder_hidden_states, + } + + @slow + def test_flaxwav2vec2bart_pt_flax_equivalence(self): + pt_model = SpeechEncoderDecoderModel.from_pretrained("patrickvonplaten/wav2vec2-2-bart-large") + fx_model = FlaxSpeechEncoderDecoderModel.from_pretrained( + "patrickvonplaten/wav2vec2-2-bart-large", from_pt=True + ) + + pt_model.to(torch_device) + pt_model.eval() + + # prepare inputs + batch_size = 13 + input_values = floats_tensor([batch_size, 512], scale=1.0) + attention_mask = random_attention_mask([batch_size, 512]) + decoder_input_ids = ids_tensor([batch_size, 4], fx_model.config.decoder.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs_dict = { + "inputs": input_values, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + flax_inputs = inputs_dict + pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + pt_logits = pt_outputs.logits + pt_outputs = pt_outputs.to_tuple() + + fx_outputs = fx_model(**inputs_dict) + fx_logits = fx_outputs.logits + fx_outputs = fx_outputs.to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits, pt_logits.numpy(), 4e-2) + + # PT -> Flax + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**inputs_dict) + fx_logits_loaded = fx_outputs_loaded.logits + fx_outputs_loaded = fx_outputs_loaded.to_tuple() + self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits_loaded, pt_logits.numpy(), 4e-2) + + # Flax -> PT + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) + + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs) + pt_logits_loaded = pt_outputs_loaded.logits + pt_outputs_loaded = pt_outputs_loaded.to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits, pt_logits_loaded.numpy(), 4e-2) + + +@require_flax +class FlaxWav2Vec2BertModelTest(FlaxEncoderDecoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = FlaxSpeechEncoderDecoderModel.from_encoder_decoder_pretrained( + "facebook/wav2vec2-large-lv60", "bert-large-uncased" + ) + batch_size = 13 + input_values = floats_tensor([batch_size, 512], model.config.encoder.vocab_size) + attention_mask = random_attention_mask([batch_size, 512]) + decoder_input_ids = ids_tensor([batch_size, 4], model.config.decoder.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs = { + "inputs": input_values, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + return model, inputs + + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = FlaxWav2Vec2Model(config) + decoder_model = FlaxBertForCausalLM(decoder_config) + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + model_tester_encoder = FlaxWav2Vec2ModelTester(self, batch_size=13) + model_tester_decoder = FlaxBertModelTester(self, batch_size=13) + encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() + decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder() + (config, inputs, attention_mask) = encoder_config_and_inputs + ( + decoder_config, + decoder_input_ids, + decoder_attention_mask, + encoder_hidden_states, + encoder_attention_mask, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + return { + "config": config, + "inputs": inputs, + "attention_mask": attention_mask, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "encoder_hidden_states": encoder_hidden_states, + } + + @slow + def test_flaxwav2vec2bert_pt_flax_equivalence(self): + pt_model = SpeechEncoderDecoderModel.from_pretrained("speech-seq2seq/wav2vec2-2-bert-large") + fx_model = FlaxSpeechEncoderDecoderModel.from_pretrained("speech-seq2seq/wav2vec2-2-bert-large", from_pt=True) + + pt_model.to(torch_device) + pt_model.eval() + + # prepare inputs + batch_size = 13 + input_values = floats_tensor([batch_size, 512], fx_model.config.encoder.vocab_size) + attention_mask = random_attention_mask([batch_size, 512]) + decoder_input_ids = ids_tensor([batch_size, 4], fx_model.config.decoder.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs_dict = { + "inputs": input_values, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + flax_inputs = inputs_dict + pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + pt_logits = pt_outputs.logits + pt_outputs = pt_outputs.to_tuple() + + fx_outputs = fx_model(**inputs_dict) + fx_logits = fx_outputs.logits + fx_outputs = fx_outputs.to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits, pt_logits.numpy(), 4e-2) + + # PT -> Flax + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = FlaxSpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**inputs_dict) + fx_logits_loaded = fx_outputs_loaded.logits + fx_outputs_loaded = fx_outputs_loaded.to_tuple() + self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits_loaded, pt_logits.numpy(), 4e-2) + + # Flax -> PT + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) + + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs) + pt_logits_loaded = pt_outputs_loaded.logits + pt_outputs_loaded = pt_outputs_loaded.to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") + self.assert_almost_equals(fx_logits, pt_logits_loaded.numpy(), 4e-2) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_encoder_decoder/test_modeling_speech_encoder_decoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_encoder_decoder/test_modeling_speech_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..368232331a2ac001642d4f1ba0186966724e69b7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_encoder_decoder/test_modeling_speech_encoder_decoder.py @@ -0,0 +1,621 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. team. +# +# 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 tempfile +import unittest + +from transformers import is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...test_modeling_common import floats_tensor, ids_tensor, random_attention_mask +from ..bert.test_modeling_bert import BertModelTester +from ..speech_to_text.test_modeling_speech_to_text import Speech2TextModelTester +from ..speech_to_text_2.test_modeling_speech_to_text_2 import Speech2Text2StandaloneDecoderModelTester +from ..wav2vec2.test_modeling_wav2vec2 import Wav2Vec2ModelTester + + +if is_torch_available(): + import numpy as np + import torch + + from transformers import ( + BertLMHeadModel, + Speech2Text2ForCausalLM, + SpeechEncoderDecoderConfig, + SpeechEncoderDecoderModel, + Wav2Vec2Model, + ) + from transformers.modeling_outputs import BaseModelOutput + from transformers.models.speech_to_text.modeling_speech_to_text import Speech2TextEncoder + + +@require_torch +class EncoderDecoderMixin: + def get_encoder_decoder_model(self, config, decoder_config): + pass + + def prepare_config_and_inputs(self): + pass + + def get_pretrained_model_and_inputs(self): + pass + + def check_encoder_decoder_model_from_pretrained_configs( + self, + config, + attention_mask, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + input_values=None, + input_features=None, + **kwargs, + ): + encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + self.assertTrue(encoder_decoder_config.decoder.is_decoder) + + enc_dec_model = SpeechEncoderDecoderModel(encoder_decoder_config) + enc_dec_model.to(torch_device) + enc_dec_model.eval() + + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + self.assertFalse(enc_dec_model.config.tie_word_embeddings) + + outputs_encoder_decoder = enc_dec_model( + input_values=input_values, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_encoder_decoder_model( + self, + config, + attention_mask, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + input_values=None, + input_features=None, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + self.assertTrue(enc_dec_model.config.decoder.is_decoder) + self.assertTrue(enc_dec_model.config.decoder.add_cross_attention) + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + enc_dec_model.to(torch_device) + outputs_encoder_decoder = enc_dec_model( + input_values=input_values, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + output_hidden_states=True, + ) + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + encoder_outputs = BaseModelOutput(last_hidden_state=outputs_encoder_decoder.encoder_hidden_states[-1]) + outputs_encoder_decoder = enc_dec_model( + encoder_outputs=encoder_outputs, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_encoder_decoder_model_with_inputs( + self, + config, + attention_mask, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + input_values=None, + input_features=None, + **kwargs, + ): + inputs = input_values if input_features is None else input_features + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + + outputs_encoder_decoder = enc_dec_model( + inputs, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + output_hidden_states=True, + ) + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + outputs_encoder_decoder_kwarg = enc_dec_model( + inputs=inputs, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + output_hidden_states=True, + ) + self.assertEqual( + outputs_encoder_decoder_kwarg["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_encoder_decoder_model_from_pretrained( + self, + config, + attention_mask, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + return_dict, + input_values=None, + input_features=None, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model, "return_dict": return_dict} + enc_dec_model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + enc_dec_model.to(torch_device) + outputs_encoder_decoder = enc_dec_model( + input_values=input_values, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + output_hidden_states=True, + return_dict=True, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_save_and_load( + self, + config, + attention_mask, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + input_values=None, + input_features=None, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + enc_dec_model.eval() + with torch.no_grad(): + outputs = enc_dec_model( + input_values=input_values, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + out_2 = outputs[0].cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmpdirname: + enc_dec_model.save_pretrained(tmpdirname) + enc_dec_model = SpeechEncoderDecoderModel.from_pretrained(tmpdirname) + enc_dec_model.to(torch_device) + + after_outputs = enc_dec_model( + input_values=input_values, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + out_1 = after_outputs[0].cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + def check_save_and_load_encoder_decoder_model( + self, + config, + attention_mask, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + input_values=None, + input_features=None, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + enc_dec_model.eval() + with torch.no_grad(): + outputs = enc_dec_model( + input_values=input_values, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + out_2 = outputs[0].cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as encoder_tmp_dirname, tempfile.TemporaryDirectory() as decoder_tmp_dirname: + enc_dec_model.encoder.save_pretrained(encoder_tmp_dirname) + enc_dec_model.decoder.save_pretrained(decoder_tmp_dirname) + SpeechEncoderDecoderModel.from_encoder_decoder_pretrained( + encoder_pretrained_model_name_or_path=encoder_tmp_dirname, + decoder_pretrained_model_name_or_path=decoder_tmp_dirname, + ) + + after_outputs = enc_dec_model( + input_values=input_values, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + out_1 = after_outputs[0].cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + def check_encoder_decoder_model_output_attentions( + self, + config, + attention_mask, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + labels=None, + input_values=None, + input_features=None, + **kwargs, + ): + # make the decoder inputs a different shape from the encoder inputs to harden the test + decoder_input_ids = decoder_input_ids[:, :-1] + decoder_attention_mask = decoder_attention_mask[:, :-1] + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + outputs_encoder_decoder = enc_dec_model( + input_values=input_values, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + output_attentions=True, + ) + + inputs = input_values if input_features is None else input_features + + encoder_attentions = outputs_encoder_decoder["encoder_attentions"] + self.assertEqual(len(encoder_attentions), config.num_hidden_layers) + + seq_len = enc_dec_model.encoder._get_feat_extract_output_lengths(inputs.shape[1]) + self.assertEqual(encoder_attentions[0].shape[-3:], (config.num_attention_heads, seq_len, seq_len)) + + decoder_attentions = outputs_encoder_decoder["decoder_attentions"] + num_decoder_layers = ( + decoder_config.num_decoder_layers + if hasattr(decoder_config, "num_decoder_layers") + else decoder_config.num_hidden_layers + ) + self.assertEqual(len(decoder_attentions), num_decoder_layers) + + self.assertEqual( + decoder_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), + ) + + cross_attentions = outputs_encoder_decoder["cross_attentions"] + self.assertEqual(len(cross_attentions), num_decoder_layers) + + cross_attention_input_seq_len = decoder_input_ids.shape[-1] + self.assertEqual( + cross_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, cross_attention_input_seq_len, seq_len), + ) + + def check_encoder_decoder_model_generate( + self, config, decoder_config, input_values=None, input_features=None, **kwargs + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + + # make sure EOS token is set to None to prevent early stopping of generation + if hasattr(enc_dec_model.config, "eos_token_id"): + enc_dec_model.config.eos_token_id = None + if hasattr(enc_dec_model.config, "decoder") and hasattr(enc_dec_model.config.decoder, "eos_token_id"): + enc_dec_model.config.decoder.eos_token_id = None + + inputs = input_values if input_features is None else input_features + + # Bert does not have a bos token id, so use pad_token_id instead + generated_output = enc_dec_model.generate( + inputs, decoder_start_token_id=enc_dec_model.config.decoder.pad_token_id + ) + self.assertEqual(generated_output.shape, (inputs.shape[0],) + (decoder_config.max_length,)) + + def test_encoder_decoder_model(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model(**input_ids_dict) + + def test_encoder_decoder_model_with_inputs(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_with_inputs(**input_ids_dict) + + def test_encoder_decoder_model_from_pretrained_configs(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained_configs(**input_ids_dict) + + def test_encoder_decoder_model_from_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=False) + + def test_encoder_decoder_model_from_pretrained_return_dict(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=True) + + def test_save_and_load_from_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_save_and_load(**input_ids_dict) + + def test_save_and_load_from_encoder_decoder_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_save_and_load_encoder_decoder_model(**input_ids_dict) + + def test_encoder_decoder_model_output_attentions(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_output_attentions(**input_ids_dict) + + def test_encoder_decoder_model_generate(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_generate(**input_ids_dict) + + def test_training_gradient_checkpointing(self): + inputs_dict = self.prepare_config_and_inputs() + encoder_model, decoder_model = self.get_encoder_decoder_model( + inputs_dict["config"], inputs_dict["decoder_config"] + ) + + model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + model.to(torch_device) + model.train() + model.gradient_checkpointing_enable() + model.config.decoder_start_token_id = 0 + model.config.pad_token_id = 0 + + model_inputs = { + "attention_mask": inputs_dict["attention_mask"], + "labels": inputs_dict["labels"], + "decoder_input_ids": inputs_dict["decoder_input_ids"], + } + inputs = inputs_dict["input_features"] if "input_features" in inputs_dict else inputs_dict["input_values"] + + loss = model(inputs, **model_inputs).loss + loss.backward() + + @slow + def test_real_model_save_load_from_pretrained(self): + model_2, inputs = self.get_pretrained_model_and_inputs() + model_2.to(torch_device) + + with torch.no_grad(): + outputs = model_2(**inputs) + out_2 = outputs[0].cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmp_dirname: + model_2.save_pretrained(tmp_dirname) + model_1 = SpeechEncoderDecoderModel.from_pretrained(tmp_dirname) + model_1.to(torch_device) + + after_outputs = model_1(**inputs) + out_1 = after_outputs[0].cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + +@require_torch +class Wav2Vec2BertModelTest(EncoderDecoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained( + "facebook/wav2vec2-base-960h", "bert-base-cased" + ) + batch_size = 13 + input_values = floats_tensor([batch_size, 512], scale=1.0) + attention_mask = random_attention_mask([batch_size, 512]) + decoder_input_ids = ids_tensor([batch_size, 4], model.decoder.config.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs = { + "input_values": input_values, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + return model, inputs + + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = Wav2Vec2Model(config).eval() + decoder_model = BertLMHeadModel(decoder_config).eval() + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + bert_model_tester = BertModelTester(self) + wav2vec2_model_tester = Wav2Vec2ModelTester(self) + encoder_config_and_inputs = wav2vec2_model_tester.prepare_config_and_inputs() + decoder_config_and_inputs = bert_model_tester.prepare_config_and_inputs_for_decoder() + ( + config, + input_values, + input_mask, + ) = encoder_config_and_inputs + ( + decoder_config, + decoder_input_ids, + decoder_token_type_ids, + decoder_input_mask, + decoder_sequence_labels, + decoder_token_labels, + decoder_choice_labels, + encoder_attention_mask, + _, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + return { + "config": config, + "input_values": input_values, + "attention_mask": input_mask, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_token_type_ids": decoder_token_type_ids, + "decoder_attention_mask": decoder_input_mask, + "decoder_sequence_labels": decoder_sequence_labels, + "decoder_token_labels": decoder_token_labels, + "decoder_choice_labels": decoder_choice_labels, + "labels": decoder_token_labels, + } + + +@require_torch +class Speech2TextBertModelTest(EncoderDecoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained( + "facebook/s2t-small-librispeech-asr", "bert-base-cased" + ) + batch_size = 13 + input_features = floats_tensor([batch_size, 7, 80], scale=1.0) + attention_mask = random_attention_mask([batch_size, 7]) + decoder_input_ids = ids_tensor([batch_size, 4], model.decoder.config.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs = { + "input_features": input_features, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + return model, inputs + + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = Speech2TextEncoder(config).eval() + decoder_model = BertLMHeadModel(decoder_config).eval() + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + bert_model_tester = BertModelTester(self) + speech2text_model_tester = Speech2TextModelTester(self) + encoder_config_and_inputs = speech2text_model_tester.prepare_config_and_inputs() + decoder_config_and_inputs = bert_model_tester.prepare_config_and_inputs_for_decoder() + + config, inputs = encoder_config_and_inputs + input_features = inputs["input_features"] + input_mask = inputs["attention_mask"] + + ( + decoder_config, + decoder_input_ids, + decoder_token_type_ids, + decoder_input_mask, + decoder_sequence_labels, + decoder_token_labels, + decoder_choice_labels, + encoder_attention_mask, + _, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + return { + "config": config, + "input_features": input_features, + "attention_mask": input_mask, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_token_type_ids": decoder_token_type_ids, + "decoder_attention_mask": decoder_input_mask, + "decoder_sequence_labels": decoder_sequence_labels, + "decoder_token_labels": decoder_token_labels, + "decoder_choice_labels": decoder_choice_labels, + "labels": decoder_token_labels, + } + + # can't save full model for now because Speech2TextModel != Speech2TextEncoder + def test_encoder_decoder_model_from_pretrained_configs(self): + pass + + # can't save full model for now because Speech2TextModel != Speech2TextEncoder + def test_save_and_load_from_pretrained(self): + pass + + # all published pretrained models are Speech2TextModel != Speech2TextEncoder + def test_real_model_save_load_from_pretrained(self): + pass + + +@require_torch +class Wav2Vec2Speech2Text2(EncoderDecoderMixin, unittest.TestCase): + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = Wav2Vec2Model(config).eval() + decoder_model = Speech2Text2ForCausalLM(decoder_config).eval() + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + model_tester_encoder = Wav2Vec2ModelTester(self, batch_size=13) + model_tester_decoder = Speech2Text2StandaloneDecoderModelTester( + self, batch_size=13, d_model=32, max_position_embeddings=512 + ) + encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() + decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs() + ( + config, + input_values, + input_mask, + ) = encoder_config_and_inputs + (decoder_config, decoder_input_ids, decoder_attention_mask, _) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + # disable cache for now + decoder_config.use_cache = False + return { + "config": config, + "input_values": input_values, + "attention_mask": input_mask, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "labels": decoder_input_ids, + } + + # there are no published pretrained Speech2Text2ForCausalLM for now + def test_real_model_save_load_from_pretrained(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_feature_extraction_speech_to_text.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_feature_extraction_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..f652d09ffca5d03eb0f62199a291660ac94efdbe --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_feature_extraction_speech_to_text.py @@ -0,0 +1,323 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 itertools +import os +import random +import tempfile +import unittest + +import numpy as np + +from transformers import Speech2TextFeatureExtractor +from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio + +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +global_rng = random.Random() + + +# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +@require_torch +@require_torchaudio +class Speech2TextFeatureExtractionTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + min_seq_length=400, + max_seq_length=2000, + feature_size=24, + num_mel_bins=24, + padding_value=0.0, + sampling_rate=16_000, + return_attention_mask=True, + do_normalize=True, + ): + self.parent = parent + self.batch_size = batch_size + self.min_seq_length = min_seq_length + self.max_seq_length = max_seq_length + self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) + self.feature_size = feature_size + self.num_mel_bins = num_mel_bins + self.padding_value = padding_value + self.sampling_rate = sampling_rate + self.return_attention_mask = return_attention_mask + self.do_normalize = do_normalize + + def prepare_feat_extract_dict(self): + return { + "feature_size": self.feature_size, + "num_mel_bins": self.num_mel_bins, + "padding_value": self.padding_value, + "sampling_rate": self.sampling_rate, + "return_attention_mask": self.return_attention_mask, + "do_normalize": self.do_normalize, + } + + def prepare_inputs_for_common(self, equal_length=False, numpify=False): + def _flatten(list_of_lists): + return list(itertools.chain(*list_of_lists)) + + if equal_length: + speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] + else: + # make sure that inputs increase in size + speech_inputs = [ + floats_list((x, self.feature_size)) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + return speech_inputs + + +@require_torch +@require_torchaudio +class Speech2TextFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = Speech2TextFeatureExtractor + + def setUp(self): + self.feat_extract_tester = Speech2TextFeatureExtractionTester(self) + + def _check_zero_mean_unit_variance(self, input_vector): + self.assertTrue(np.all(np.mean(input_vector, axis=0) < 1e-3)) + self.assertTrue(np.all(np.abs(np.var(input_vector, axis=0) - 1) < 1e-3)) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test feature size + input_features = feature_extractor(np_speech_inputs, padding=True, return_tensors="np").input_features + self.assertTrue(input_features.ndim == 3) + self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size) + + # Test not batched input + encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_features + self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) + + # Test batched + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test 2-D numpy arrays are batched. + speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] + np_speech_inputs = np.asarray(speech_inputs) + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + def test_cepstral_mean_and_variance_normalization(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + paddings = ["longest", "max_length", "do_not_pad"] + max_lengths = [None, 16, None] + for max_length, padding in zip(max_lengths, paddings): + inputs = feature_extractor( + speech_inputs, padding=padding, max_length=max_length, return_attention_mask=True + ) + input_features = inputs.input_features + attention_mask = inputs.attention_mask + fbank_feat_lengths = [np.sum(x) for x in attention_mask] + + self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]) + self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]) + self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]) + + def test_cepstral_mean_and_variance_normalization_np(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + paddings = ["longest", "max_length", "do_not_pad"] + max_lengths = [None, 16, None] + for max_length, padding in zip(max_lengths, paddings): + inputs = feature_extractor( + speech_inputs, max_length=max_length, padding=padding, return_tensors="np", return_attention_mask=True + ) + input_features = inputs.input_features + attention_mask = inputs.attention_mask + fbank_feat_lengths = [np.sum(x) for x in attention_mask] + + self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]) + self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6) + self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]) + self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6) + self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]) + + def test_cepstral_mean_and_variance_normalization_trunc_max_length(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + inputs = feature_extractor( + speech_inputs, + padding="max_length", + max_length=4, + truncation=True, + return_tensors="np", + return_attention_mask=True, + ) + input_features = inputs.input_features + attention_mask = inputs.attention_mask + fbank_feat_lengths = np.sum(attention_mask == 1, axis=1) + + self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) + self._check_zero_mean_unit_variance(input_features[1]) + self._check_zero_mean_unit_variance(input_features[2]) + + def test_cepstral_mean_and_variance_normalization_trunc_longest(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + inputs = feature_extractor( + speech_inputs, + padding="longest", + max_length=4, + truncation=True, + return_tensors="np", + return_attention_mask=True, + ) + input_features = inputs.input_features + attention_mask = inputs.attention_mask + fbank_feat_lengths = np.sum(attention_mask == 1, axis=1) + + self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) + self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]) + self._check_zero_mean_unit_variance(input_features[2]) + + # make sure that if max_length < longest -> then pad to max_length + self.assertEqual(input_features.shape, (3, 4, 24)) + + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + inputs = feature_extractor( + speech_inputs, + padding="longest", + max_length=16, + truncation=True, + return_tensors="np", + return_attention_mask=True, + ) + input_features = inputs.input_features + attention_mask = inputs.attention_mask + fbank_feat_lengths = np.sum(attention_mask == 1, axis=1) + + self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) + self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]) + self._check_zero_mean_unit_variance(input_features[2]) + + # make sure that if max_length < longest -> then pad to max_length + self.assertEqual(input_features.shape, (3, 6, 24)) + + def test_double_precision_pad(self): + import torch + + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + np_speech_inputs = np.random.rand(100, 32).astype(np.float64) + py_speech_inputs = np_speech_inputs.tolist() + + for inputs in [py_speech_inputs, np_speech_inputs]: + np_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="np") + self.assertTrue(np_processed.input_features.dtype == np.float32) + pt_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="pt") + self.assertTrue(pt_processed.input_features.dtype == torch.float32) + + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_integration(self): + # fmt: off + expected = np.array([ + -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, + -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, + -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, + ]) + # fmt: on + + input_speech = self._load_datasamples(1) + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + input_features = feature_extractor(input_speech, return_tensors="pt").input_features + self.assertEquals(input_features.shape, (1, 584, 24)) + self.assertTrue(np.allclose(input_features[0, 0, :30], expected, atol=1e-4)) + + def test_feat_extract_from_and_save_pretrained(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = feat_extract_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + self.assertDictEqual(dict_first, dict_second) + + def test_feat_extract_to_json_file(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "feat_extract.json") + feat_extract_first.to_json_file(json_file_path) + feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + self.assertEqual(dict_first, dict_second) + + +# exact same tests than before, except that we simulate that torchaudio is not available +@require_torch +@unittest.mock.patch( + "transformers.models.speech_to_text.feature_extraction_speech_to_text.is_speech_available", lambda: False +) +class Speech2TextFeatureExtractionWithoutTorchaudioTest(Speech2TextFeatureExtractionTest): + def test_using_audio_utils(self): + # Tests that it uses audio_utils instead of torchaudio + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + + self.assertTrue(hasattr(feat_extract, "window")) + self.assertTrue(hasattr(feat_extract, "mel_filters")) + + from transformers.models.speech_to_text.feature_extraction_speech_to_text import is_speech_available + + self.assertFalse(is_speech_available()) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_modeling_speech_to_text.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_modeling_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..602a73bacd78f9ade53e852973132f62f7ab793e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_modeling_speech_to_text.py @@ -0,0 +1,827 @@ +# coding=utf-8 +# 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 Speech2Text model. """ + +import copy +import inspect +import os +import tempfile +import unittest + +from transformers import Speech2TextConfig +from transformers.testing_utils import ( + is_torch_available, + require_sentencepiece, + require_tokenizers, + require_torch, + require_torch_fp16, + require_torchaudio, + slow, + torch_device, +) +from transformers.utils import cached_property + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import Speech2TextForConditionalGeneration, Speech2TextModel, Speech2TextProcessor + from transformers.models.speech_to_text.modeling_speech_to_text import Speech2TextDecoder, Speech2TextEncoder + + +def prepare_speech_to_text_inputs_dict( + config, + input_features, + decoder_input_ids, + 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 = input_features.ne(0) + if decoder_attention_mask is None: + decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) + if head_mask is None: + head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device) + if decoder_head_mask is None: + decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) + if cross_attn_head_mask is None: + cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) + return { + # "input_ids": input_features, + "input_features": input_features, + "decoder_input_ids": decoder_input_ids, + "attention_mask": attention_mask, + "decoder_attention_mask": attention_mask, + "head_mask": head_mask, + "decoder_head_mask": decoder_head_mask, + "cross_attn_head_mask": cross_attn_head_mask, + } + + +@require_torch +class Speech2TextModelTester: + 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, + num_conv_layers=2, + conv_kernel_sizes=(5, 5), + conv_channels=32, + input_feat_per_channel=24, + input_channels=1, + hidden_act="relu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=20, + max_source_positions=20, + max_target_positions=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.num_conv_layers = num_conv_layers + self.conv_kernel_sizes = conv_kernel_sizes + self.conv_channels = conv_channels + self.input_feat_per_channel = input_feat_per_channel + self.input_channels = input_channels + 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.max_source_positions = max_source_positions + self.max_target_positions = max_target_positions + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.bos_token_id = bos_token_id + + def prepare_config_and_inputs(self): + input_features = floats_tensor( + [self.batch_size, self.seq_length, self.input_feat_per_channel], self.vocab_size + ) + attention_mask = torch.ones([self.batch_size, self.seq_length], dtype=torch.long, device=torch_device) + decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(2) + + config = self.get_config() + inputs_dict = prepare_speech_to_text_inputs_dict( + config, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + ) + return config, inputs_dict + + def get_config(self): + return Speech2TextConfig( + 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, + num_conv_layers=self.num_conv_layers, + conv_kernel_sizes=self.conv_kernel_sizes, + conv_channels=self.conv_channels, + input_feat_per_channel=self.input_feat_per_channel, + input_channels=self.input_channels, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + max_source_positions=self.max_source_positions, + max_target_positions=self.max_target_positions, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + ) + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_subsampled_output_lengths(self, input_lengths): + """ + Computes the output length of the convolutional layers + """ + + for i in range(self.num_conv_layers): + input_lengths = (input_lengths - 1) // 2 + 1 + + return input_lengths + + def create_and_check_model_forward(self, config, inputs_dict): + model = Speech2TextModel(config=config).to(torch_device).eval() + + input_features = inputs_dict["input_features"] + decoder_input_ids = inputs_dict["decoder_input_ids"] + + # first forward pass + last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state + + self.parent.assertTrue(last_hidden_state.shape, (13, 7, 16)) + + def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): + model = Speech2TextModel(config=config).get_decoder().to(torch_device).eval() + input_ids = inputs_dict["decoder_input_ids"] + attention_mask = inputs_dict["decoder_attention_mask"] + + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size).clamp(2) + next_attn_mask = ids_tensor((self.batch_size, 3), 2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # 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-2)) + + def check_encoder_decoder_model_standalone(self, config, inputs_dict): + model = Speech2TextModel(config=config).to(torch_device).eval() + outputs = model(**inputs_dict) + + encoder_last_hidden_state = outputs.encoder_last_hidden_state + last_hidden_state = outputs.last_hidden_state + + with tempfile.TemporaryDirectory() as tmpdirname: + encoder = model.get_encoder() + encoder.save_pretrained(tmpdirname) + encoder = Speech2TextEncoder.from_pretrained(tmpdirname).to(torch_device) + + encoder_last_hidden_state_2 = encoder( + inputs_dict["input_features"], attention_mask=inputs_dict["attention_mask"] + )[0] + + self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3) + + with tempfile.TemporaryDirectory() as tmpdirname: + decoder = model.get_decoder() + decoder.save_pretrained(tmpdirname) + decoder = Speech2TextDecoder.from_pretrained(tmpdirname).to(torch_device) + + encoder_attention_mask = encoder._get_feature_vector_attention_mask( + encoder_last_hidden_state.shape[1], inputs_dict["attention_mask"] + ) + + last_hidden_state_2 = decoder( + input_ids=inputs_dict["decoder_input_ids"], + attention_mask=inputs_dict["decoder_attention_mask"], + encoder_hidden_states=encoder_last_hidden_state, + encoder_attention_mask=encoder_attention_mask, + )[0] + + self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3) + + +@require_torch +class Speech2TextModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (Speech2TextModel, Speech2TextForConditionalGeneration) if is_torch_available() else () + all_generative_model_classes = (Speech2TextForConditionalGeneration,) if is_torch_available() else () + pipeline_model_mapping = ( + {"automatic-speech-recognition": Speech2TextForConditionalGeneration, "feature-extraction": Speech2TextModel} + if is_torch_available() + else {} + ) + is_encoder_decoder = True + fx_compatible = True + test_pruning = False + test_missing_keys = False + + input_name = "input_features" + + def setUp(self): + self.model_tester = Speech2TextModelTester(self) + self.config_tester = ConfigTester(self, config_class=Speech2TextConfig) + self.maxDiff = 3000 + + def test_config(self): + self.config_tester.run_common_tests() + + def test_save_load_strict(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) + self.assertEqual(info["missing_keys"], []) + + def test_model_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + 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) + + # not implemented currently + def test_inputs_embeds(self): + pass + + # training is not supported yet + def test_training(self): + pass + + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + @require_torch_fp16 + def test_generate_fp16(self): + config, input_dict = self.model_tester.prepare_config_and_inputs() + input_features = input_dict["input_features"] + attention_mask = input_dict["attention_mask"] + model = Speech2TextForConditionalGeneration(config).eval().to(torch_device) + input_features = input_features.half() + model.half() + model.generate(input_features, attention_mask=attention_mask) + model.generate(input_features, num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_features", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + ] + expected_arg_names.extend( + ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + else: + seq_length = self.model_tester.seq_length + + subsampled_seq_length = model._get_feat_extract_output_lengths(seq_length) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [subsampled_seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + + subsampled_encoder_seq_length = model._get_feat_extract_output_lengths(encoder_seq_length) + subsampled_encoder_key_length = model._get_feat_extract_output_lengths(encoder_key_length) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + out_len = len(outputs) + + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + subsampled_encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + + def test_resize_tokens_embeddings(self): + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + return + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + + if self.model_tester.is_training is False: + model.eval() + + model_vocab_size = config.vocab_size + # Retrieve the embeddings and clone theme + model_embed = model.resize_token_embeddings(model_vocab_size) + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.vocab_size, model_vocab_size + 10) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15) + + # make sure that decoder_input_ids are resized + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that adding and removing tokens has not modified the first part of the embedding matrix. + models_equal = True + for p1, p2 in zip(cloned_embeddings, model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + def test_resize_embeddings_untied(self): + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + return + + original_config.tie_word_embeddings = False + + # if model cannot untied embeddings -> leave test + if original_config.tie_word_embeddings: + return + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config).to(torch_device) + + # if no output embeddings -> leave test + if model.get_output_embeddings() is None: + continue + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_vocab_size = config.vocab_size + model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.vocab_size, model_vocab_size + 10) + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size + 10) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size - 15) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size - 15) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + def test_generate_without_input_ids(self): + pass + + @staticmethod + def _get_encoder_outputs( + model, input_ids, attention_mask, output_attentions=None, output_hidden_states=None, num_interleave=1 + ): + 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 = input_ids[:, :, 0] + input_ids = torch.zeros_like(input_ids[:, :1], dtype=torch.long) + model._get_decoder_start_token_id() + attention_mask = None + return encoder_outputs, input_ids, attention_mask + + def _check_outputs(self, output, input_ids, config, use_cache=False, num_return_sequences=1): + batch_size, seq_length = input_ids.shape[:2] + subsampled_seq_length = self.model_tester.get_subsampled_output_lengths(seq_length) + num_sequences_in_output = batch_size * num_return_sequences + gen_len = ( + output.sequences.shape[-1] - 1 if config.is_encoder_decoder else output.sequences.shape[-1] - seq_length + ) + + # scores + self._check_scores(num_sequences_in_output, output.scores, length=gen_len, config=config) + + # Attentions + # encoder + self._check_encoder_attention_for_generate( + output.encoder_attentions, batch_size, config, subsampled_seq_length + ) + # decoder + self._check_attentions_for_generate( + num_sequences_in_output, + output.decoder_attentions, + min_length=1, + max_length=output.sequences.shape[-1], + config=config, + use_cache=use_cache, + ) + + # Hidden States + # encoder + self._check_encoder_hidden_states_for_generate( + output.encoder_hidden_states, batch_size, config, subsampled_seq_length + ) + + # decoder + self._check_hidden_states_for_generate( + num_sequences_in_output, + output.decoder_hidden_states, + min_length=1, + max_length=output.sequences.shape[-1], + config=config, + use_cache=use_cache, + ) + + def _create_and_check_torchscript(self, config, inputs_dict): + if not self.test_torchscript: + return + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.torchscript = True + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class) + + try: + model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward + input_features = inputs["input_features"] + attention_mask = inputs["attention_mask"] + decoder_input_ids = inputs["decoder_input_ids"] + decoder_attention_mask = inputs["decoder_attention_mask"] + traced_model = torch.jit.trace( + model, (input_features, attention_mask, decoder_input_ids, decoder_attention_mask) + ) + except RuntimeError: + self.fail("Couldn't trace module.") + + with tempfile.TemporaryDirectory() as tmp_dir_name: + pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt") + + try: + torch.jit.save(traced_model, pt_file_name) + except Exception: + self.fail("Couldn't save module.") + + try: + loaded_model = torch.jit.load(pt_file_name) + except Exception: + self.fail("Couldn't load module.") + + model.to(torch_device) + model.eval() + + loaded_model.to(torch_device) + loaded_model.eval() + + model_state_dict = model.state_dict() + loaded_model_state_dict = loaded_model.state_dict() + + non_persistent_buffers = {} + for key in loaded_model_state_dict.keys(): + if key not in model_state_dict.keys(): + non_persistent_buffers[key] = loaded_model_state_dict[key] + + loaded_model_state_dict = { + key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers + } + + self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys())) + + model_buffers = list(model.buffers()) + for non_persistent_buffer in non_persistent_buffers.values(): + found_buffer = False + for i, model_buffer in enumerate(model_buffers): + if torch.equal(non_persistent_buffer, model_buffer): + found_buffer = True + break + + self.assertTrue(found_buffer) + model_buffers.pop(i) + + models_equal = True + for layer_name, p1 in model_state_dict.items(): + p2 = loaded_model_state_dict[layer_name] + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + def test_pt_tf_model_equivalence(self, allow_missing_keys=True): + # Allow missing keys since TF doesn't cache the sinusoidal embeddings in an attribute + super().test_pt_tf_model_equivalence(allow_missing_keys=allow_missing_keys) + + @unittest.skip("Test failing, @RocketNight is looking into it") + def test_tf_from_pt_safetensors(self): + pass + + +@require_torch +@require_torchaudio +@require_sentencepiece +@require_tokenizers +@slow +class Speech2TextModelIntegrationTests(unittest.TestCase): + @cached_property + def default_processor(self): + return Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr") + + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_generation_librispeech(self): + model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr") + model.to(torch_device) + processor = self.default_processor + + input_speech = self._load_datasamples(1) + + input_features = processor(input_speech, return_tensors="pt").input_features.to(torch_device) + + generated_ids = model.generate(input_features) + generated_transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + + EXPECTED_TRANSCRIPTIONS = [ + "mister quilter is the apostle of the middle classes and we are glad to welcome his gospel" + ] + self.assertListEqual(generated_transcript, EXPECTED_TRANSCRIPTIONS) + + def test_generation_librispeech_batched(self): + model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr") + model.to(torch_device) + processor = self.default_processor + + input_speech = self._load_datasamples(4) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_features = inputs.input_features.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + + generated_ids = model.generate(input_features, attention_mask=attention_mask) + generated_transcripts = processor.batch_decode(generated_ids, skip_special_tokens=True) + + EXPECTED_TRANSCRIPTIONS = [ + "mister quilter is the apostle of the middle classes and we are glad to welcome his gospel", + "nor is mister cultar's manner less interesting than his matter", + "he tells us that at this festive season of the year with christmas and roast beef looming before us" + " similes drawn from eating and its results occur most readily to the mind", + "he has grave doubts whether sir frederick leyton's work is really greek after all and can discover in it" + " but little of rocky ithaca", + ] + + self.assertListEqual(generated_transcripts, EXPECTED_TRANSCRIPTIONS) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_modeling_tf_speech_to_text.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_modeling_tf_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..badde2485df1247927b6b701cfbc2f70f440c651 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_modeling_tf_speech_to_text.py @@ -0,0 +1,630 @@ +# coding=utf-8 +# 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 TensorFlow Speech2Text model. """ + +from __future__ import annotations + +import inspect +import unittest + +from transformers import Speech2TextConfig +from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow +from transformers.utils import cached_property, is_tf_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import Speech2TextProcessor, TFSpeech2TextForConditionalGeneration, TFSpeech2TextModel + + +def prepare_speech_to_text_inputs_dict( + config, + input_features, + decoder_input_ids, + 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 = tf.math.not_equal(input_features, 0) + if decoder_attention_mask is None: + decoder_attention_mask = tf.math.not_equal(decoder_input_ids, config.pad_token_id) + if head_mask is None: + head_mask = tf.ones((config.encoder_layers, config.encoder_attention_heads)) + if decoder_head_mask is None: + decoder_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads)) + if cross_attn_head_mask is None: + cross_attn_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads)) + return { + "input_features": input_features, + "decoder_input_ids": decoder_input_ids, + "attention_mask": attention_mask, + "decoder_attention_mask": attention_mask, + "head_mask": head_mask, + "decoder_head_mask": decoder_head_mask, + "cross_attn_head_mask": cross_attn_head_mask, + } + + +@require_tf +class TFSpeech2TextModelTester: + 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, + num_conv_layers=2, + conv_kernel_sizes=(5, 5), + conv_channels=32, + input_feat_per_channel=24, + input_channels=1, + hidden_act="relu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=20, + max_source_positions=20, + max_target_positions=20, + eos_token_id=2, + pad_token_id=1, + bos_token_id=0, + scale_embedding=False, + ): + 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.num_conv_layers = num_conv_layers + self.conv_kernel_sizes = conv_kernel_sizes + self.conv_channels = conv_channels + self.input_feat_per_channel = input_feat_per_channel + self.input_channels = input_channels + 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.max_source_positions = max_source_positions + self.max_target_positions = max_target_positions + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.bos_token_id = bos_token_id + self.scale_embedding = scale_embedding + + def prepare_config_and_inputs(self): + input_features = floats_tensor( + [self.batch_size, self.seq_length, self.input_feat_per_channel], self.vocab_size + ) + attention_mask = tf.ones([self.batch_size, self.seq_length], dtype=tf.int64) + decoder_input_ids = tf.math.maximum(ids_tensor([self.batch_size, self.seq_length], self.vocab_size), 2) + + config = self.get_config() + inputs_dict = prepare_speech_to_text_inputs_dict( + config, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + ) + return config, inputs_dict + + def get_config(self): + return Speech2TextConfig( + 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, + num_conv_layers=self.num_conv_layers, + conv_kernel_sizes=self.conv_kernel_sizes, + conv_channels=self.conv_channels, + input_feat_per_channel=self.input_feat_per_channel, + input_channels=self.input_channels, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + max_source_positions=self.max_source_positions, + max_target_positions=self.max_target_positions, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + scale_embedding=self.scale_embedding, + ) + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_subsampled_output_lengths(self, input_lengths): + """ + Computes the output length of the convolutional layers + """ + + for _ in range(self.num_conv_layers): + input_lengths = (input_lengths - 1) // 2 + 1 + + return input_lengths + + def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): + model = TFSpeech2TextModel(config=config).get_decoder() + input_ids = inputs_dict["decoder_input_ids"] + attention_mask = inputs_dict["decoder_attention_mask"] + + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) + + _, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = tf.math.maximum(ids_tensor((self.batch_size, 3), config.vocab_size), 2) + next_attn_mask = ids_tensor((self.batch_size, 3), 2, dtype=tf.int64) + + # append to next input_ids and + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([attention_mask, next_attn_mask], axis=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, atol=1e-2) + + +@require_tf +class TFSpeech2TextModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (TFSpeech2TextModel, TFSpeech2TextForConditionalGeneration) if is_tf_available() else () + all_generative_model_classes = (TFSpeech2TextForConditionalGeneration,) if is_tf_available() else () + pipeline_model_mapping = {"feature-extraction": TFSpeech2TextModel} if is_tf_available() else {} + is_encoder_decoder = True + test_pruning = False + test_missing_keys = False + test_onnx = False + + input_name = "input_ids" + + def setUp(self): + self.model_tester = TFSpeech2TextModelTester(self) + self.config_tester = ConfigTester(self, config_class=Speech2TextConfig) + self.maxDiff = 3000 + + def test_config(self): + self.config_tester.run_common_tests() + + 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) + + # not implemented currently + def test_inputs_embeds(self): + pass + + # training is not supported yet + def test_training(self): + pass + + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + def test_generate_fp16(self): + pass + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + else: + seq_length = self.model_tester.seq_length + + subsampled_seq_length = model._get_feat_extract_output_lengths(seq_length) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [subsampled_seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + + subsampled_encoder_seq_length = model._get_feat_extract_output_lengths(encoder_seq_length) + subsampled_encoder_key_length = model._get_feat_extract_output_lengths(encoder_key_length) + + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + out_len = len(outputs) + + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + subsampled_encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + + def test_resize_token_embeddings(self): + # Overwritten method from parent; see `test_resize_embeddings_untied` + pass + + def test_resize_tokens_embeddings(self): + # see `test_resize_embeddings_untied` + pass + + def test_resize_embeddings_untied(self): + # TODO: copy test from PT. Not working at the moment because the test relies on `model.resize_token_embeddings`, + # whose TF implementation assumes the use of `TFWrappedEmbeddings`. But with a `TFWrappedEmbeddings` we can't + # load the weights from PT (also, it induces TF1 behavior, so we might want to rework how + # `model.resize_token_embeddings` operates). + pass + + def test_generate_without_input_ids(self): + pass + + @staticmethod + def _get_encoder_outputs( + model, input_ids, attention_mask, output_attentions=None, output_hidden_states=None, num_interleave=1 + ): + 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"] = tf.repeat(encoder_outputs.last_hidden_state, num_interleave, axis=0) + + input_ids = input_ids[:, :, 0] + input_ids = tf.zeros_like(input_ids[:, :1], dtype=tf.int64) + model._get_decoder_start_token_id() + attention_mask = None + return encoder_outputs, input_ids, attention_mask + + def _check_outputs(self, output, input_ids, config, use_cache=False, num_return_sequences=1): + batch_size, seq_length = input_ids.shape[:2] + subsampled_seq_length = self.model_tester.get_subsampled_output_lengths(seq_length) + num_sequences_in_output = batch_size * num_return_sequences + gen_len = ( + output.sequences.shape[-1] - 1 if config.is_encoder_decoder else output.sequences.shape[-1] - seq_length + ) + + # scores + self._check_scores(num_sequences_in_output, output.scores, length=gen_len, config=config) + + # Attentions + # encoder + self._check_encoder_attention_for_generate( + output.encoder_attentions, batch_size, config, subsampled_seq_length + ) + # decoder + self._check_attentions_for_generate( + num_sequences_in_output, + output.decoder_attentions, + min_length=1, + max_length=output.sequences.shape[-1], + config=config, + use_cache=use_cache, + ) + + # Hidden States + # encoder + self._check_encoder_hidden_states_for_generate( + output.encoder_hidden_states, batch_size, config, subsampled_seq_length + ) + + # decoder + self._check_hidden_states_for_generate( + num_sequences_in_output, + output.decoder_hidden_states, + min_length=1, + max_length=output.sequences.shape[-1], + config=config, + use_cache=use_cache, + ) + + # overwritten from parent due to the inability to work when non-text inputs are not passed AND because the input is + # `input_features` + def test_lm_head_model_random_no_beam_search_generate(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_features = inputs_dict.get("input_features", None) + + # iterate over all generative models + for model_class in self.all_generative_model_classes: + model = model_class(config) + + if config.bos_token_id is None: + # if bos token id is not defined model needs input_features + with self.assertRaises(AssertionError): + model.generate(do_sample=True, max_length=5) + # num_return_sequences = 1 + self._check_generated_ids(model.generate(input_features, do_sample=True)) + + with self.assertRaises(ValueError): + # generating multiple sequences when no beam search generation + # is not allowed as it would always generate the same sequences + model.generate(input_features, do_sample=False, num_return_sequences=2) + + # num_return_sequences > 1, sample + self._check_generated_ids(model.generate(input_features, do_sample=True, num_return_sequences=2)) + + # check bad words tokens language generation + # create list of 1-seq bad token and list of 2-seq of bad tokens + bad_words_ids = [self._generate_random_bad_tokens(1, model), self._generate_random_bad_tokens(2, model)] + output_tokens = model.generate( + input_features, do_sample=True, bad_words_ids=bad_words_ids, num_return_sequences=2 + ) + # only count generated tokens + generated_ids = output_tokens[:, input_features.shape[-1] :] + self.assertFalse(self._check_match_tokens(generated_ids.numpy().tolist(), bad_words_ids)) + + # overwritten from parent due to the inability to work when non-text inputs are not passed AND because the input is + # `input_features` + def test_lm_head_model_random_beam_search_generate(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_features = inputs_dict.get("input_features", None) + + for model_class in self.all_generative_model_classes: + model = model_class(config) + + if config.bos_token_id is None: + # if bos token id is not defined model needs input_ids, num_return_sequences = 1 + self._check_generated_ids(model.generate(input_features, do_sample=True, num_beams=2)) + + with self.assertRaises(ValueError): + # generating more sequences than having beams leads is not possible + model.generate(input_features, do_sample=False, num_return_sequences=3, num_beams=2) + + # num_return_sequences > 1, sample + self._check_generated_ids( + model.generate( + input_features, + do_sample=True, + num_beams=2, + num_return_sequences=2, + ) + ) + # num_return_sequences > 1, greedy + self._check_generated_ids( + model.generate(input_features, do_sample=False, num_beams=2, num_return_sequences=2) + ) + + # check bad words tokens language generation + # create list of 1-seq bad token and list of 2-seq of bad tokens + bad_words_ids = [self._generate_random_bad_tokens(1, model), self._generate_random_bad_tokens(2, model)] + output_tokens = model.generate( + input_features, do_sample=False, bad_words_ids=bad_words_ids, num_beams=2, num_return_sequences=2 + ) + # only count generated tokens + generated_ids = output_tokens[:, input_features.shape[-1] :] + self.assertFalse(self._check_match_tokens(generated_ids.numpy().tolist(), bad_words_ids)) + + # overwritten from parent -- the input is `input_features`, not `input_ids` + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_features", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + ] + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_pt_tf_model_equivalence(self, allow_missing_keys=True): + # Allow missing keys since TF doesn't cache the sinusoidal embeddings in an attribute + super().test_pt_tf_model_equivalence(allow_missing_keys=allow_missing_keys) + + +@require_tf +@require_sentencepiece +@require_tokenizers +@slow +class TFSpeech2TextModelIntegrationTests(unittest.TestCase): + @cached_property + def default_processor(self): + return Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr") + + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_generation_librispeech(self): + model = TFSpeech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr") + processor = self.default_processor + + input_speech = self._load_datasamples(1) + + input_features = processor(input_speech, return_tensors="tf").input_features + + generated_ids = model.generate(input_features) + generated_transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + + EXPECTED_TRANSCRIPTIONS = [ + "mister quilter is the apostle of the middle classes and we are glad to welcome his gospel" + ] + self.assertListEqual(generated_transcript, EXPECTED_TRANSCRIPTIONS) + + def test_generation_librispeech_batched(self): + model = TFSpeech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr") + processor = self.default_processor + + input_speech = self._load_datasamples(4) + + inputs = processor(input_speech, return_tensors="tf", padding=True) + generated_ids = model.generate(inputs.input_features, attention_mask=inputs.attention_mask) + generated_transcripts = processor.batch_decode(generated_ids, skip_special_tokens=True) + + EXPECTED_TRANSCRIPTIONS = [ + "mister quilter is the apostle of the middle classes and we are glad to welcome his gospel", + "nor is mister cultar's manner less interesting than his matter", + "he tells us that at this festive season of the year with christmas and roast beef looming before us" + " similes drawn from eating and its results occur most readily to the mind", + "he has grave doubts whether sir frederick leyton's work is really greek after all and can discover in it" + " but little of rocky ithaca", + ] + self.assertListEqual(generated_transcripts, EXPECTED_TRANSCRIPTIONS) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_processor_speech_to_text.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_processor_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..923ba29d1a87776ddb9db3918bea4c4a81d1b421 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_processor_speech_to_text.py @@ -0,0 +1,154 @@ +# Copyright 2021 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 shutil +import tempfile +import unittest +from pathlib import Path +from shutil import copyfile + +from transformers import Speech2TextFeatureExtractor, Speech2TextProcessor, Speech2TextTokenizer +from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, require_torchaudio +from transformers.utils import FEATURE_EXTRACTOR_NAME + +from .test_feature_extraction_speech_to_text import floats_list + + +SAMPLE_SP = get_tests_dir("fixtures/test_sentencepiece.model") + + +@require_torch +@require_torchaudio +@require_sentencepiece +class Speech2TextProcessorTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + vocab = ["", "", "", "", "▁This", "▁is", "▁a", "▁t", "est"] + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + save_dir = Path(self.tmpdirname) + save_json(vocab_tokens, save_dir / VOCAB_FILES_NAMES["vocab_file"]) + if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): + copyfile(SAMPLE_SP, save_dir / VOCAB_FILES_NAMES["spm_file"]) + + tokenizer = Speech2TextTokenizer.from_pretrained(self.tmpdirname) + tokenizer.save_pretrained(self.tmpdirname) + + feature_extractor_map = { + "feature_size": 24, + "num_mel_bins": 24, + "padding_value": 0.0, + "sampling_rate": 16000, + "return_attention_mask": False, + "do_normalize": True, + } + save_json(feature_extractor_map, save_dir / FEATURE_EXTRACTOR_NAME) + + def get_tokenizer(self, **kwargs): + return Speech2TextTokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def get_feature_extractor(self, **kwargs): + return Speech2TextFeatureExtractor.from_pretrained(self.tmpdirname, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_save_load_pretrained_default(self): + tokenizer = self.get_tokenizer() + feature_extractor = self.get_feature_extractor() + + processor = Speech2TextProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + processor.save_pretrained(self.tmpdirname) + processor = Speech2TextProcessor.from_pretrained(self.tmpdirname) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) + self.assertIsInstance(processor.tokenizer, Speech2TextTokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string()) + self.assertIsInstance(processor.feature_extractor, Speech2TextFeatureExtractor) + + def test_save_load_pretrained_additional_features(self): + processor = Speech2TextProcessor( + tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor() + ) + processor.save_pretrained(self.tmpdirname) + + tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)") + feature_extractor_add_kwargs = self.get_feature_extractor(do_normalize=False, padding_value=1.0) + + processor = Speech2TextProcessor.from_pretrained( + self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0 + ) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) + self.assertIsInstance(processor.tokenizer, Speech2TextTokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.feature_extractor, Speech2TextFeatureExtractor) + + def test_feature_extractor(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Speech2TextProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + raw_speech = floats_list((3, 1000)) + + input_feat_extract = feature_extractor(raw_speech, return_tensors="np") + input_processor = processor(raw_speech, return_tensors="np") + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_tokenizer(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Speech2TextProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + input_str = "This is a test string" + + encoded_processor = processor(text=input_str) + + encoded_tok = tokenizer(input_str) + + for key in encoded_tok.keys(): + self.assertListEqual(encoded_tok[key], encoded_processor[key]) + + def test_tokenizer_decode(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Speech2TextProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] + + decoded_processor = processor.batch_decode(predicted_ids) + decoded_tok = tokenizer.batch_decode(predicted_ids) + + self.assertListEqual(decoded_tok, decoded_processor) + + def test_model_input_names(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Speech2TextProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + self.assertListEqual( + processor.model_input_names, + feature_extractor.model_input_names, + msg="`processor` and `feature_extractor` model input names do not match", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_tokenization_speech_to_text.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_tokenization_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..b0cb1acc856356683e543a79cbd67c2cb3206d5e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text/test_tokenization_speech_to_text.py @@ -0,0 +1,151 @@ +# Copyright 2021 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 unittest +from pathlib import Path +from shutil import copyfile + +from transformers import SPIECE_UNDERLINE, is_sentencepiece_available +from transformers.models.speech_to_text import Speech2TextTokenizer +from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + +if is_sentencepiece_available(): + import sentencepiece as sp + + +FR_CODE = 5 +ES_CODE = 10 + + +@require_sentencepiece +@require_tokenizers +class SpeechToTextTokenizerTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = Speech2TextTokenizer + test_rust_tokenizer = False + test_sentencepiece = True + + def setUp(self): + super().setUp() + + spm_model = sp.SentencePieceProcessor() + spm_model.Load(SAMPLE_VOCAB) + vocab = ["", "", "", ""] + + vocab += [spm_model.IdToPiece(id_) for id_ in range(len(spm_model))] + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + + save_dir = Path(self.tmpdirname) + save_json(vocab_tokens, save_dir / VOCAB_FILES_NAMES["vocab_file"]) + if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): + copyfile(SAMPLE_VOCAB, save_dir / VOCAB_FILES_NAMES["spm_file"]) + + tokenizer = Speech2TextTokenizer.from_pretrained(self.tmpdirname) + tokenizer.save_pretrained(self.tmpdirname) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "" + token_id = 1 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + self.assertEqual(vocab_keys[-1], "j") + self.assertEqual(len(vocab_keys), 1_001) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 1_001) + + def test_full_tokenizer(self): + tokenizer = Speech2TextTokenizer.from_pretrained(self.tmpdirname) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [289, 50, 14, 174, 386], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual(tokens,[SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", "."]) # fmt: skip + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual(ids, [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8]) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual(back_tokens,[SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "", "."]) # fmt: skip + + @slow + def test_tokenizer_integration(self): + expected_encoding = {'input_ids': [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: skip + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, + model_name="facebook/s2t-small-mustc-en-de-st", + revision="a14f04cf0776c02f62a8cb800cf7909e15ea23ad", + ) + + +@require_sentencepiece +class SpeechToTextTokenizerMultilinguialTest(unittest.TestCase): + checkpoint_name = "valhalla/s2t_mustc_multilinguial_medium" + + french_text = "C'est trop cool" + spanish_text = "Esto es genial" + + @classmethod + def setUpClass(cls): + cls.tokenizer: Speech2TextTokenizer = Speech2TextTokenizer.from_pretrained(cls.checkpoint_name) + return cls + + def check_language_codes(self): + self.assertEqual(self.tokenizer.lang_code_to_id["pt"], 4) + self.assertEqual(self.tokenizer.lang_code_to_id["ru"], 6) + self.assertEqual(self.tokenizer.lang_code_to_id["it"], 9) + self.assertEqual(self.tokenizer.lang_code_to_id["de"], 11) + + def test_vocab_size(self): + self.assertEqual(self.tokenizer.vocab_size, 10_000) + + def test_tokenizer_decode_ignores_language_codes(self): + self.assertIn(ES_CODE, self.tokenizer.all_special_ids) + generated_ids = [ES_CODE, 4, 1601, 47, 7647, 2] + result = self.tokenizer.decode(generated_ids, skip_special_tokens=True) + expected_spanish = self.tokenizer.decode(generated_ids[1:], skip_special_tokens=True) + self.assertEqual(result, expected_spanish) + self.assertNotIn(self.tokenizer.eos_token, result) + + def test_tokenizer_adds_special_tokens(self): + self.tokenizer.tgt_lang = "fr" + encoded = self.tokenizer(self.french_text).input_ids + self.assertEqual(encoded[0], FR_CODE) + self.assertEqual(encoded[-1], self.tokenizer.eos_token_id) + + def test_tgt_lang_setter(self): + self.tokenizer.tgt_lang = "fr" + self.assertListEqual(self.tokenizer.prefix_tokens, [FR_CODE]) + + self.tokenizer.tgt_lang = "es" + self.assertListEqual(self.tokenizer.prefix_tokens, [ES_CODE]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text_2/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text_2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text_2/test_modeling_speech_to_text_2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text_2/test_modeling_speech_to_text_2.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb449c6e7ae73dc7eb0dd4a8c9d29095a0867ed --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text_2/test_modeling_speech_to_text_2.py @@ -0,0 +1,216 @@ +# coding=utf-8 +# 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 Speech2Text model. """ + +import unittest + +from transformers import Speech2Text2Config +from transformers.testing_utils import is_torch_available, require_torch, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers.models.speech_to_text_2.modeling_speech_to_text_2 import ( + Speech2Text2Decoder, + Speech2Text2ForCausalLM, + ) + + +@require_torch +class Speech2Text2StandaloneDecoderModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + d_model=16, + decoder_seq_length=7, + is_training=True, + is_decoder=True, + use_attention_mask=True, + use_cache=False, + use_labels=True, + decoder_start_token_id=2, + decoder_ffn_dim=32, + decoder_layers=2, + decoder_attention_heads=4, + max_position_embeddings=30, + pad_token_id=0, + bos_token_id=1, + eos_token_id=2, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_labels = use_labels + + self.vocab_size = vocab_size + self.d_model = d_model + self.hidden_size = d_model + self.num_hidden_layers = decoder_layers + self.decoder_layers = decoder_layers + self.decoder_ffn_dim = decoder_ffn_dim + self.decoder_attention_heads = decoder_attention_heads + self.num_attention_heads = decoder_attention_heads + self.eos_token_id = eos_token_id + self.bos_token_id = bos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.use_cache = use_cache + self.max_position_embeddings = max_position_embeddings + + self.scope = None + self.decoder_key_length = decoder_seq_length + self.base_model_out_len = 2 + self.decoder_attention_idx = 1 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2) + + lm_labels = None + if self.use_labels: + lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + config = Speech2Text2Config( + vocab_size=self.vocab_size, + d_model=self.d_model, + decoder_layers=self.decoder_layers, + decoder_ffn_dim=self.decoder_ffn_dim, + decoder_attention_heads=self.decoder_attention_heads, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + use_cache=self.use_cache, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + max_position_embeddings=self.max_position_embeddings, + ) + + return ( + config, + input_ids, + attention_mask, + lm_labels, + ) + + def create_and_check_decoder_model_past( + self, + config, + input_ids, + attention_mask, + lm_labels, + ): + config.use_cache = True + model = Speech2Text2Decoder(config=config).to(torch_device).eval() + input_ids = input_ids[:2] + + input_ids[input_ids == 0] += 1 + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + past_key_values = outputs["past_key_values"] + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((2, 1), config.vocab_size - 1) + 1 + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + print(next_input_ids) + + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + attention_mask, + lm_labels, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + +@require_torch +class Speech2Text2StandaloneDecoderModelTest( + ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase +): + all_model_classes = (Speech2Text2Decoder, Speech2Text2ForCausalLM) if is_torch_available() else () + all_generative_model_classes = (Speech2Text2ForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = {"text-generation": Speech2Text2ForCausalLM} if is_torch_available() else {} + fx_compatible = True + test_pruning = False + + def setUp( + self, + ): + self.model_tester = Speech2Text2StandaloneDecoderModelTester(self, is_training=False) + self.config_tester = ConfigTester(self, config_class=Speech2Text2Config) + + # not implemented currently + def test_inputs_embeds(self): + pass + + # speech2text2 has no base model + def test_save_load_fast_init_from_base(self): + pass + + # speech2text2 has no base model + def test_save_load_fast_init_to_base(self): + pass + + def test_config(self): + self.config_tester.run_common_tests() + + def test_decoder_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_past(*config_and_inputs) + + # decoder cannot keep gradients + def test_retain_grad_hidden_states_attentions(self): + return diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text_2/test_tokenization_speech_to_text_2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text_2/test_tokenization_speech_to_text_2.py new file mode 100644 index 0000000000000000000000000000000000000000..1000cce2898036b61fe637d16b9765e589311ab8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speech_to_text_2/test_tokenization_speech_to_text_2.py @@ -0,0 +1,97 @@ +# Copyright 2021 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 inspect +import json +import os +import tempfile +import unittest + +from transformers.models.speech_to_text_2 import Speech2Text2Tokenizer +from transformers.models.speech_to_text_2.tokenization_speech_to_text_2 import VOCAB_FILES_NAMES + +from ...test_tokenization_common import TokenizerTesterMixin + + +class SpeechToTextTokenizerTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = Speech2Text2Tokenizer + test_rust_tokenizer = False + + def setUp(self): + super().setUp() + + vocab = " here@@ a couple of@@ words for the he@@ re@@ vocab".split(" ") + merges = ["he re 123", "here a 1456"] + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + + self.special_tokens_map = {"pad_token": "", "unk_token": "", "bos_token": "", "eos_token": ""} + + self.tmpdirname = tempfile.mkdtemp() + 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") as fp: + fp.write("\n".join(merges)) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + self.assertEqual(vocab_keys[-1], "vocab") + self.assertEqual(len(vocab_keys), 14) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 14) + + def test_tokenizer_decode(self): + tokenizer = Speech2Text2Tokenizer.from_pretrained(self.tmpdirname) + + # make sure @@ is correctly concatenated + token_ids = [4, 6, 8, 7, 10] # ["here@@", "couple", "words", "of@@", "the"] + output_string = tokenizer.decode(token_ids) + + self.assertTrue(output_string == "herecouple words ofthe") + + def test_load_no_merges_file(self): + tokenizer = Speech2Text2Tokenizer.from_pretrained(self.tmpdirname) + + with tempfile.TemporaryDirectory() as tmp_dirname: + tokenizer.save_pretrained(tmp_dirname) + os.remove(os.path.join(tmp_dirname, "merges.txt")) + + # load tokenizer without merges file should not throw an error + tokenizer = Speech2Text2Tokenizer.from_pretrained(tmp_dirname) + + with tempfile.TemporaryDirectory() as tmp_dirname: + # save tokenizer and load again + tokenizer.save_pretrained(tmp_dirname) + tokenizer = Speech2Text2Tokenizer.from_pretrained(tmp_dirname) + + self.assertIsNotNone(tokenizer) + + # overwrite since merges_file is optional + def test_tokenizer_slow_store_full_signature(self): + if not self.test_slow_tokenizer: + return + + signature = inspect.signature(self.tokenizer_class.__init__) + tokenizer = self.get_tokenizer() + + for parameter_name, parameter in signature.parameters.items(): + if parameter.default != inspect.Parameter.empty and parameter_name != "merges_file": + self.assertIn(parameter_name, tokenizer.init_kwargs) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_feature_extraction_speecht5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_feature_extraction_speecht5.py new file mode 100644 index 0000000000000000000000000000000000000000..22d99a81804764777116fc00719621d3a34c3c49 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_feature_extraction_speecht5.py @@ -0,0 +1,421 @@ +# coding=utf-8 +# Copyright 2021-2023 HuggingFace Inc. +# +# 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. +"""Tests for the SpeechT5 feature extractors.""" + +import itertools +import random +import unittest + +import numpy as np + +from transformers import BatchFeature, SpeechT5FeatureExtractor +from transformers.testing_utils import require_torch +from transformers.utils.import_utils import is_torch_available + +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +if is_torch_available(): + import torch + + +global_rng = random.Random() + + +# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +@require_torch +class SpeechT5FeatureExtractionTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + min_seq_length=400, + max_seq_length=2000, + feature_size=1, + padding_value=0.0, + sampling_rate=16000, + do_normalize=True, + num_mel_bins=80, + hop_length=16, + win_length=64, + win_function="hann_window", + fmin=80, + fmax=7600, + mel_floor=1e-10, + return_attention_mask=True, + ): + self.parent = parent + self.batch_size = batch_size + self.min_seq_length = min_seq_length + self.max_seq_length = max_seq_length + self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) + self.feature_size = feature_size + self.padding_value = padding_value + self.sampling_rate = sampling_rate + self.do_normalize = do_normalize + self.num_mel_bins = num_mel_bins + self.hop_length = hop_length + self.win_length = win_length + self.win_function = win_function + self.fmin = fmin + self.fmax = fmax + self.mel_floor = mel_floor + self.return_attention_mask = return_attention_mask + + def prepare_feat_extract_dict(self): + return { + "feature_size": self.feature_size, + "padding_value": self.padding_value, + "sampling_rate": self.sampling_rate, + "do_normalize": self.do_normalize, + "num_mel_bins": self.num_mel_bins, + "hop_length": self.hop_length, + "win_length": self.win_length, + "win_function": self.win_function, + "fmin": self.fmin, + "fmax": self.fmax, + "mel_floor": self.mel_floor, + "return_attention_mask": self.return_attention_mask, + } + + def prepare_inputs_for_common(self, equal_length=False, numpify=False): + def _flatten(list_of_lists): + return list(itertools.chain(*list_of_lists)) + + if equal_length: + speech_inputs = floats_list((self.batch_size, self.max_seq_length)) + else: + # make sure that inputs increase in size + speech_inputs = [ + _flatten(floats_list((x, self.feature_size))) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + + return speech_inputs + + def prepare_inputs_for_target(self, equal_length=False, numpify=False): + if equal_length: + speech_inputs = [floats_list((self.max_seq_length, self.num_mel_bins)) for _ in range(self.batch_size)] + else: + # make sure that inputs increase in size + speech_inputs = [ + floats_list((x, self.num_mel_bins)) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + + return speech_inputs + + +@require_torch +class SpeechT5FeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = SpeechT5FeatureExtractor + + def setUp(self): + self.feat_extract_tester = SpeechT5FeatureExtractionTester(self) + + def _check_zero_mean_unit_variance(self, input_vector): + self.assertTrue(np.all(np.mean(input_vector, axis=0) < 1e-3)) + self.assertTrue(np.all(np.abs(np.var(input_vector, axis=0) - 1) < 1e-3)) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test not batched input + encoded_sequences_1 = feat_extract(speech_inputs[0], return_tensors="np").input_values + encoded_sequences_2 = feat_extract(np_speech_inputs[0], return_tensors="np").input_values + self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) + + # Test batched + encoded_sequences_1 = feat_extract(speech_inputs, return_tensors="np").input_values + encoded_sequences_2 = feat_extract(np_speech_inputs, return_tensors="np").input_values + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + def test_zero_mean_unit_variance_normalization_np(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + paddings = ["longest", "max_length", "do_not_pad"] + max_lengths = [None, 1600, None] + for max_length, padding in zip(max_lengths, paddings): + processed = feat_extract(speech_inputs, padding=padding, max_length=max_length, return_tensors="np") + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0][:800]) + self.assertTrue(input_values[0][800:].sum() < 1e-6) + self._check_zero_mean_unit_variance(input_values[1][:1000]) + self.assertTrue(input_values[0][1000:].sum() < 1e-6) + self._check_zero_mean_unit_variance(input_values[2][:1200]) + + def test_zero_mean_unit_variance_normalization(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + lengths = range(800, 1400, 200) + speech_inputs = [floats_list((1, x))[0] for x in lengths] + + paddings = ["longest", "max_length", "do_not_pad"] + max_lengths = [None, 1600, None] + + for max_length, padding in zip(max_lengths, paddings): + processed = feat_extract(speech_inputs, max_length=max_length, padding=padding) + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0][:800]) + self._check_zero_mean_unit_variance(input_values[1][:1000]) + self._check_zero_mean_unit_variance(input_values[2][:1200]) + + def test_zero_mean_unit_variance_normalization_trunc_np_max_length(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + processed = feat_extract( + speech_inputs, truncation=True, max_length=1000, padding="max_length", return_tensors="np" + ) + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0, :800]) + self._check_zero_mean_unit_variance(input_values[1]) + self._check_zero_mean_unit_variance(input_values[2]) + + def test_zero_mean_unit_variance_normalization_trunc_np_longest(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + processed = feat_extract( + speech_inputs, truncation=True, max_length=1000, padding="longest", return_tensors="np" + ) + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0, :800]) + self._check_zero_mean_unit_variance(input_values[1, :1000]) + self._check_zero_mean_unit_variance(input_values[2]) + + # make sure that if max_length < longest -> then pad to max_length + self.assertTrue(input_values.shape == (3, 1000)) + + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + processed = feat_extract( + speech_inputs, truncation=True, max_length=2000, padding="longest", return_tensors="np" + ) + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0, :800]) + self._check_zero_mean_unit_variance(input_values[1, :1000]) + self._check_zero_mean_unit_variance(input_values[2]) + + # make sure that if max_length > longest -> then pad to longest + self.assertTrue(input_values.shape == (3, 1200)) + + def test_double_precision_pad(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + np_speech_inputs = np.random.rand(100).astype(np.float64) + py_speech_inputs = np_speech_inputs.tolist() + + for inputs in [py_speech_inputs, np_speech_inputs]: + np_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="np") + self.assertTrue(np_processed.input_values.dtype == np.float32) + pt_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="pt") + self.assertTrue(pt_processed.input_values.dtype == torch.float32) + + def test_call_target(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test feature size + input_values = feature_extractor(audio_target=np_speech_inputs, padding=True, return_tensors="np").input_values + self.assertTrue(input_values.ndim == 3) + self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins) + + # Test not batched input + encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_values + encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_values + self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) + + # Test batched + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_values + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_values + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test 2-D numpy arrays are batched. + speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] + np_speech_inputs = np.asarray(speech_inputs) + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_values + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_values + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + def test_batch_feature_target(self): + speech_inputs = self.feat_extract_tester.prepare_inputs_for_target() + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + self.assertTrue(all(len(x) == len(y) for x, y in zip(speech_inputs, processed_features[input_name]))) + + speech_inputs = self.feat_extract_tester.prepare_inputs_for_target(equal_length=True) + processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="np") + + batch_features_input = processed_features[input_name] + + if len(batch_features_input.shape) < 3: + batch_features_input = batch_features_input[:, :, None] + + self.assertTrue( + batch_features_input.shape + == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.num_mel_bins) + ) + + @require_torch + def test_batch_feature_target_pt(self): + speech_inputs = self.feat_extract_tester.prepare_inputs_for_target(equal_length=True) + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="pt") + + batch_features_input = processed_features[input_name] + + if len(batch_features_input.shape) < 3: + batch_features_input = batch_features_input[:, :, None] + + self.assertTrue( + batch_features_input.shape + == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.num_mel_bins) + ) + + @require_torch + def test_padding_accepts_tensors_target_pt(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_target() + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + feat_extract.feature_size = feat_extract.num_mel_bins # hack! + + input_np = feat_extract.pad(processed_features, padding="longest", return_tensors="np")[input_name] + input_pt = feat_extract.pad(processed_features, padding="longest", return_tensors="pt")[input_name] + + self.assertTrue(abs(input_np.astype(np.float32).sum() - input_pt.numpy().astype(np.float32).sum()) < 1e-2) + + def test_attention_mask_target(self): + feat_dict = self.feat_extract_dict + feat_dict["return_attention_mask"] = True + feat_extract = self.feature_extraction_class(**feat_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_target() + input_lengths = [len(x) for x in speech_inputs] + input_name = feat_extract.model_input_names[0] + + processed = BatchFeature({input_name: speech_inputs}) + + feat_extract.feature_size = feat_extract.num_mel_bins # hack! + + processed = feat_extract.pad(processed, padding="longest", return_tensors="np") + self.assertIn("attention_mask", processed) + self.assertListEqual(list(processed.attention_mask.shape), list(processed[input_name].shape[:2])) + self.assertListEqual(processed.attention_mask.sum(-1).tolist(), input_lengths) + + def test_attention_mask_with_truncation_target(self): + feat_dict = self.feat_extract_dict + feat_dict["return_attention_mask"] = True + feat_extract = self.feature_extraction_class(**feat_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_target() + input_lengths = [len(x) for x in speech_inputs] + input_name = feat_extract.model_input_names[0] + + processed = BatchFeature({input_name: speech_inputs}) + max_length = min(input_lengths) + + feat_extract.feature_size = feat_extract.num_mel_bins # hack! + + processed_pad = feat_extract.pad( + processed, padding="max_length", max_length=max_length, truncation=True, return_tensors="np" + ) + self.assertIn("attention_mask", processed_pad) + self.assertListEqual( + list(processed_pad.attention_mask.shape), [processed_pad[input_name].shape[0], max_length] + ) + self.assertListEqual( + processed_pad.attention_mask[:, :max_length].sum(-1).tolist(), [max_length for x in speech_inputs] + ) + + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_integration(self): + # fmt: off + EXPECTED_INPUT_VALUES = torch.tensor( + [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03, + 3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03, + 2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04, + 4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03, + 7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04, + 4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03] + ) + # fmt: on + + input_speech = self._load_datasamples(1) + feature_extractor = SpeechT5FeatureExtractor() + input_values = feature_extractor(input_speech, return_tensors="pt").input_values + self.assertEquals(input_values.shape, (1, 93680)) + self.assertTrue(torch.allclose(input_values[0, :30], EXPECTED_INPUT_VALUES, atol=1e-6)) + + def test_integration_target(self): + # fmt: off + EXPECTED_INPUT_VALUES = torch.tensor( + [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, + -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, + -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, + -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] + ) + # fmt: on + + input_speech = self._load_datasamples(1) + feature_extractor = SpeechT5FeatureExtractor() + input_values = feature_extractor(audio_target=input_speech, return_tensors="pt").input_values + self.assertEquals(input_values.shape, (1, 366, 80)) + self.assertTrue(torch.allclose(input_values[0, 0, :30], EXPECTED_INPUT_VALUES, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_modeling_speecht5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_modeling_speecht5.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b4b24873a2fe990a1710bbf28ba748097d832e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_modeling_speecht5.py @@ -0,0 +1,1726 @@ +# coding=utf-8 +# Copyright 2022 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 SpeechT5 model. """ + +import copy +import inspect +import tempfile +import unittest + +from transformers import SpeechT5Config, SpeechT5HifiGanConfig +from transformers.testing_utils import ( + is_torch_available, + require_sentencepiece, + require_tokenizers, + require_torch, + slow, + torch_device, +) +from transformers.trainer_utils import set_seed +from transformers.utils import cached_property + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + SpeechT5ForSpeechToSpeech, + SpeechT5ForSpeechToText, + SpeechT5ForTextToSpeech, + SpeechT5HifiGan, + SpeechT5Model, + SpeechT5Processor, + ) + + +def prepare_inputs_dict( + config, + input_ids=None, + input_values=None, + decoder_input_ids=None, + decoder_input_values=None, + attention_mask=None, + decoder_attention_mask=None, + head_mask=None, + decoder_head_mask=None, + cross_attn_head_mask=None, +): + if input_ids is not None: + encoder_dict = {"input_ids": input_ids} + else: + encoder_dict = {"input_values": input_values} + + if decoder_input_ids is not None: + decoder_dict = {"decoder_input_ids": decoder_input_ids} + else: + decoder_dict = {"decoder_input_values": decoder_input_values} + + if head_mask is None: + head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device) + if decoder_head_mask is None: + decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) + if cross_attn_head_mask is None: + cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) + + return { + **encoder_dict, + **decoder_dict, + "attention_mask": attention_mask, + "decoder_attention_mask": decoder_attention_mask, + "head_mask": head_mask, + "decoder_head_mask": decoder_head_mask, + "cross_attn_head_mask": cross_attn_head_mask, + } + + +@require_torch +class SpeechT5ModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=False, + vocab_size=81, + hidden_size=24, + num_hidden_layers=2, + num_attention_heads=2, + intermediate_size=4, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + 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 + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.seq_length, self.hidden_size], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + decoder_input_values = floats_tensor([self.batch_size, self.seq_length, self.hidden_size], scale=1.0) + decoder_attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + inputs_dict = prepare_inputs_dict( + config, + input_values=input_values, + decoder_input_values=decoder_input_values, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_config(self): + return SpeechT5Config( + vocab_size=self.vocab_size, + hidden_size=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, + ) + + def create_and_check_model_forward(self, config, inputs_dict): + model = SpeechT5Model(config=config).to(torch_device).eval() + + input_values = inputs_dict["input_values"] + attention_mask = inputs_dict["attention_mask"] + decoder_input_values = inputs_dict["decoder_input_values"] + + result = model(input_values, attention_mask=attention_mask, decoder_input_values=decoder_input_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + +@require_torch +class SpeechT5ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (SpeechT5Model,) if is_torch_available() else () + pipeline_model_mapping = ( + {"automatic-speech-recognition": SpeechT5ForSpeechToText, "feature-extraction": SpeechT5Model} + if is_torch_available() + else {} + ) + is_encoder_decoder = True + test_pruning = False + test_headmasking = False + test_resize_embeddings = False + + input_name = "input_values" + + def setUp(self): + self.model_tester = SpeechT5ModelTester(self) + self.config_tester = ConfigTester(self, config_class=SpeechT5Config, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_values", + "attention_mask", + "decoder_input_values", + "decoder_attention_mask", + ] + expected_arg_names.extend( + ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + # this model has no inputs_embeds + def test_inputs_embeds(self): + pass + + # this model has no input embeddings + def test_model_common_attributes(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + # decoder cannot keep gradients + pass + + @slow + def test_torchscript_output_attentions(self): + # disabled because this model doesn't have decoder_input_ids + pass + + @slow + def test_torchscript_output_hidden_state(self): + # disabled because this model doesn't have decoder_input_ids + pass + + @slow + def test_torchscript_simple(self): + # disabled because this model doesn't have decoder_input_ids + pass + + +@require_torch +class SpeechT5ForSpeechToTextTester: + def __init__( + self, + parent, + batch_size=13, + encoder_seq_length=1024, # speech is longer + decoder_seq_length=7, + is_training=False, + hidden_size=24, + num_hidden_layers=2, + num_attention_heads=2, + intermediate_size=4, + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + vocab_size=81, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + self.is_training = is_training + 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.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.vocab_size = vocab_size + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.encoder_seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.encoder_seq_length]) + + decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size).clamp(2) + decoder_attention_mask = random_attention_mask([self.batch_size, self.decoder_seq_length]) + + config = self.get_config() + inputs_dict = prepare_inputs_dict( + config, + input_values=input_values, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_config(self): + return SpeechT5Config( + hidden_size=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, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + vocab_size=self.vocab_size, + ) + + def create_and_check_model_forward(self, config, inputs_dict): + model = SpeechT5ForSpeechToText(config=config).to(torch_device).eval() + + input_values = inputs_dict["input_values"] + attention_mask = inputs_dict["attention_mask"] + decoder_input_ids = inputs_dict["decoder_input_ids"] + + result = model(input_values, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.decoder_seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): + model = SpeechT5ForSpeechToText(config=config).get_decoder().to(torch_device).eval() + input_ids = inputs_dict["decoder_input_ids"] + attention_mask = inputs_dict["decoder_attention_mask"] + + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size).clamp(2) + next_attn_mask = ids_tensor((self.batch_size, 3), 2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # 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-2)) + + +@require_torch +class SpeechT5ForSpeechToTextTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (SpeechT5ForSpeechToText,) if is_torch_available() else () + all_generative_model_classes = (SpeechT5ForSpeechToText,) if is_torch_available() else () + is_encoder_decoder = True + test_pruning = False + test_headmasking = False + + input_name = "input_values" + + def setUp(self): + self.model_tester = SpeechT5ForSpeechToTextTester(self) + self.config_tester = ConfigTester(self, config_class=SpeechT5Config, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_save_load_strict(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) + self.assertEqual(info["missing_keys"], []) + + def test_model_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + 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_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + + subsampled_encoder_seq_length = model.speecht5.encoder.prenet._get_feat_extract_output_lengths( + encoder_seq_length + ) + subsampled_encoder_key_length = model.speecht5.encoder.prenet._get_feat_extract_output_lengths( + encoder_key_length + ) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + out_len = len(outputs) + + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + subsampled_encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_values", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + ] + expected_arg_names.extend( + ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + else: + seq_length = self.model_tester.seq_length + + subsampled_seq_length = model.speecht5.encoder.prenet._get_feat_extract_output_lengths(seq_length) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [subsampled_seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # this model has no inputs_embeds + def test_inputs_embeds(self): + pass + + def test_resize_embeddings_untied(self): + original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + return + + original_config.tie_word_embeddings = False + + # if model cannot untied embeddings -> leave test + if original_config.tie_word_embeddings: + return + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config).to(torch_device) + + # if no output embeddings -> leave test + if model.get_output_embeddings() is None: + continue + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_vocab_size = config.vocab_size + model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.vocab_size, model_vocab_size + 10) + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size + 10) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size - 15) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size - 15) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + def test_resize_tokens_embeddings(self): + original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + return + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + + if self.model_tester.is_training is False: + model.eval() + + model_vocab_size = config.vocab_size + # Retrieve the embeddings and clone theme + model_embed = model.resize_token_embeddings(model_vocab_size) + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.vocab_size, model_vocab_size + 10) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15) + + # make sure that decoder_input_ids are resized + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that adding and removing tokens has not modified the first part of the embedding matrix. + models_equal = True + for p1, p2 in zip(cloned_embeddings, model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + def test_retain_grad_hidden_states_attentions(self): + # decoder cannot keep gradients + pass + + # training is not supported yet + def test_training(self): + pass + + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + +@require_torch +@require_sentencepiece +@require_tokenizers +@slow +class SpeechT5ForSpeechToTextIntegrationTests(unittest.TestCase): + @cached_property + def default_processor(self): + return SpeechT5Processor.from_pretrained("microsoft/speecht5_asr") + + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_generation_librispeech(self): + model = SpeechT5ForSpeechToText.from_pretrained("microsoft/speecht5_asr") + model.to(torch_device) + processor = self.default_processor + + input_speech = self._load_datasamples(1) + + input_values = processor(audio=input_speech, return_tensors="pt").input_values.to(torch_device) + + generated_ids = model.generate(input_values) + generated_transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + + EXPECTED_TRANSCRIPTIONS = [ + "mister quilter is the apostle of the middle classes and we are glad to welcome his gospel" + ] + self.assertListEqual(generated_transcript, EXPECTED_TRANSCRIPTIONS) + + def test_generation_librispeech_batched(self): + model = SpeechT5ForSpeechToText.from_pretrained("microsoft/speecht5_asr") + model.to(torch_device) + processor = self.default_processor + + input_speech = self._load_datasamples(4) + + inputs = processor(audio=input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + + generated_ids = model.generate(input_values, attention_mask=attention_mask) + generated_transcripts = processor.batch_decode(generated_ids, skip_special_tokens=True) + + EXPECTED_TRANSCRIPTIONS = [ + "mister quilter is the apostle of the middle classes and we are glad to welcome his gospel", + "nor is mister quilter's manner less interesting than his matter", + "he tells us that at this festive season of the year with christmas and rosebeaf looming before us" + " similars drawn from eating and its results occur most readily to the mind", + "he has grave doubts whether sir frederick latin's work is really greek after all and can discover in it" + " but little of rocky ithica", + ] + self.assertListEqual(generated_transcripts, EXPECTED_TRANSCRIPTIONS) + + +@require_torch +class SpeechT5ForTextToSpeechTester: + def __init__( + self, + parent, + batch_size=13, + encoder_seq_length=7, + decoder_seq_length=1024, # speech is longer + is_training=False, + hidden_size=24, + num_hidden_layers=2, + num_attention_heads=2, + intermediate_size=4, + vocab_size=81, + num_mel_bins=20, + reduction_factor=2, + speech_decoder_postnet_layers=2, + speech_decoder_postnet_units=32, + speech_decoder_prenet_units=32, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + self.is_training = is_training + 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.vocab_size = vocab_size + self.num_mel_bins = num_mel_bins + self.reduction_factor = reduction_factor + self.speech_decoder_postnet_layers = speech_decoder_postnet_layers + self.speech_decoder_postnet_units = speech_decoder_postnet_units + self.speech_decoder_prenet_units = speech_decoder_prenet_units + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size).clamp(2) + attention_mask = random_attention_mask([self.batch_size, self.encoder_seq_length]) + + decoder_input_values = floats_tensor([self.batch_size, self.decoder_seq_length, self.num_mel_bins], scale=1.0) + decoder_attention_mask = random_attention_mask([self.batch_size, self.decoder_seq_length]) + + config = self.get_config() + inputs_dict = prepare_inputs_dict( + config, + input_ids=input_ids, + decoder_input_values=decoder_input_values, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_config(self): + return SpeechT5Config( + hidden_size=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, + vocab_size=self.vocab_size, + num_mel_bins=self.num_mel_bins, + reduction_factor=self.reduction_factor, + speech_decoder_postnet_layers=self.speech_decoder_postnet_layers, + speech_decoder_postnet_units=self.speech_decoder_postnet_units, + speech_decoder_prenet_units=self.speech_decoder_prenet_units, + ) + + def create_and_check_model_forward(self, config, inputs_dict): + model = SpeechT5ForTextToSpeech(config=config).to(torch_device).eval() + + input_ids = inputs_dict["input_ids"] + attention_mask = inputs_dict["attention_mask"] + decoder_input_values = inputs_dict["decoder_input_values"] + + result = model(input_ids, attention_mask=attention_mask, decoder_input_values=decoder_input_values) + self.parent.assertEqual( + result.spectrogram.shape, + (self.batch_size, self.decoder_seq_length * self.reduction_factor, self.num_mel_bins), + ) + + +@require_torch +class SpeechT5ForTextToSpeechTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (SpeechT5ForTextToSpeech,) if is_torch_available() else () + all_generative_model_classes = (SpeechT5ForTextToSpeech,) if is_torch_available() else () + is_encoder_decoder = True + test_pruning = False + test_headmasking = False + + input_name = "input_ids" + + def setUp(self): + self.model_tester = SpeechT5ForTextToSpeechTester(self) + self.config_tester = ConfigTester(self, config_class=SpeechT5Config, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_save_load_strict(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) + self.assertEqual(info["missing_keys"], []) + + def test_model_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + # skipped because there is always dropout in SpeechT5SpeechDecoderPrenet + def test_decoder_model_past_with_large_inputs(self): + pass + + # skipped because there is always dropout in SpeechT5SpeechDecoderPrenet + def test_determinism(self): + pass + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_ids", + "attention_mask", + "decoder_input_values", + "decoder_attention_mask", + ] + expected_arg_names.extend( + ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # this model has no inputs_embeds + def test_inputs_embeds(self): + pass + + # skipped because there is always dropout in SpeechT5SpeechDecoderPrenet + def test_model_outputs_equivalence(self): + pass + + # skipped because there is always dropout in SpeechT5SpeechDecoderPrenet + def test_save_load(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + # decoder cannot keep gradients + pass + + @slow + def test_torchscript_output_attentions(self): + # disabled because this model doesn't have decoder_input_ids + pass + + @slow + def test_torchscript_output_hidden_state(self): + # disabled because this model doesn't have decoder_input_ids + pass + + @slow + def test_torchscript_simple(self): + # disabled because this model doesn't have decoder_input_ids + pass + + # training is not supported yet + def test_training(self): + pass + + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + + +@require_torch +@require_sentencepiece +@require_tokenizers +class SpeechT5ForTextToSpeechIntegrationTests(unittest.TestCase): + @cached_property + def default_model(self): + return SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts") + + @cached_property + def default_processor(self): + return SpeechT5Processor.from_pretrained("microsoft/speecht5_tts") + + @cached_property + def default_vocoder(self): + return SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan") + + def test_generation(self): + model = self.default_model + model.to(torch_device) + processor = self.default_processor + + set_seed(555) # make deterministic + + speaker_embeddings = torch.zeros((1, 512)).to(torch_device) + + input_text = "mister quilter is the apostle of the middle classes and we are glad to welcome his gospel" + input_ids = processor(text=input_text, return_tensors="pt").input_ids.to(torch_device) + + generated_speech = model.generate_speech(input_ids, speaker_embeddings=speaker_embeddings) + self.assertEqual(generated_speech.shape, (230, model.config.num_mel_bins)) + + set_seed(555) # make deterministic + + # test model.generate, same method than generate_speech but with additional kwargs to absorb kwargs such as attention_mask + generated_speech_with_generate = model.generate( + input_ids, attention_mask=None, speaker_embeddings=speaker_embeddings + ) + self.assertEqual(generated_speech_with_generate.shape, (230, model.config.num_mel_bins)) + + def test_batch_generation(self): + model = self.default_model + model.to(torch_device) + processor = self.default_processor + vocoder = self.default_vocoder + set_seed(555) # make deterministic + + input_text = [ + "mister quilter is the apostle of the middle classes and we are glad to welcome his gospel", + "nor is mister quilter's manner less interesting than his matter", + "he tells us that at this festive season of the year with christmas and rosebeaf looming before us", + ] + inputs = processor(text=input_text, padding="max_length", max_length=128, return_tensors="pt").to(torch_device) + + speaker_embeddings = torch.zeros((1, 512), device=torch_device) + spectrograms, spectrogram_lengths = model.generate_speech( + input_ids=inputs["input_ids"], + speaker_embeddings=speaker_embeddings, + attention_mask=inputs["attention_mask"], + return_output_lengths=True, + ) + self.assertEqual(spectrograms.shape, (3, 262, model.config.num_mel_bins)) + waveforms = vocoder(spectrograms) + waveform_lengths = [int(waveforms.size(1) / max(spectrogram_lengths)) * i for i in spectrogram_lengths] + + # Check waveform results are the same with or without using vocder + set_seed(555) + waveforms_with_vocoder, waveform_lengths_with_vocoder = model.generate_speech( + input_ids=inputs["input_ids"], + speaker_embeddings=speaker_embeddings, + attention_mask=inputs["attention_mask"], + vocoder=vocoder, + return_output_lengths=True, + ) + self.assertTrue(torch.allclose(waveforms, waveforms_with_vocoder, atol=1e-8)) + self.assertEqual(waveform_lengths, waveform_lengths_with_vocoder) + + # Check waveform results are the same with return_concrete_lengths=True/False + set_seed(555) + waveforms_with_vocoder_no_lengths = model.generate_speech( + input_ids=inputs["input_ids"], + speaker_embeddings=speaker_embeddings, + attention_mask=inputs["attention_mask"], + vocoder=vocoder, + return_output_lengths=False, + ) + self.assertTrue(torch.allclose(waveforms_with_vocoder_no_lengths, waveforms_with_vocoder, atol=1e-8)) + + # Check results when batching are consistent with results without batching + for i, text in enumerate(input_text): + set_seed(555) # make deterministic + inputs = processor(text=text, padding="max_length", max_length=128, return_tensors="pt").to(torch_device) + spectrogram = model.generate_speech( + input_ids=inputs["input_ids"], + speaker_embeddings=speaker_embeddings, + ) + self.assertEqual(spectrogram.shape, spectrograms[i][: spectrogram_lengths[i]].shape) + self.assertTrue(torch.allclose(spectrogram, spectrograms[i][: spectrogram_lengths[i]], atol=5e-3)) + waveform = vocoder(spectrogram) + self.assertEqual(waveform.shape, waveforms[i][: waveform_lengths[i]].shape) + # Check whether waveforms are the same with/without passing vocoder + set_seed(555) + waveform_with_vocoder = model.generate_speech( + input_ids=inputs["input_ids"], + speaker_embeddings=speaker_embeddings, + vocoder=vocoder, + ) + self.assertTrue(torch.allclose(waveform, waveform_with_vocoder, atol=1e-8)) + + +@require_torch +class SpeechT5ForSpeechToSpeechTester: + def __init__( + self, + parent, + batch_size=13, + encoder_seq_length=1024, # speech is longer + decoder_seq_length=1024, + is_training=False, + hidden_size=24, + num_hidden_layers=2, + num_attention_heads=2, + intermediate_size=4, + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + vocab_size=81, + num_mel_bins=20, + reduction_factor=2, + speech_decoder_postnet_layers=2, + speech_decoder_postnet_units=32, + speech_decoder_prenet_units=32, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + self.is_training = is_training + 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.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.vocab_size = vocab_size + self.num_mel_bins = num_mel_bins + self.reduction_factor = reduction_factor + self.speech_decoder_postnet_layers = speech_decoder_postnet_layers + self.speech_decoder_postnet_units = speech_decoder_postnet_units + self.speech_decoder_prenet_units = speech_decoder_prenet_units + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.encoder_seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.encoder_seq_length]) + + decoder_input_values = floats_tensor([self.batch_size, self.decoder_seq_length, self.num_mel_bins], scale=1.0) + decoder_attention_mask = random_attention_mask([self.batch_size, self.decoder_seq_length]) + + config = self.get_config() + inputs_dict = prepare_inputs_dict( + config, + input_values=input_values, + decoder_input_values=decoder_input_values, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_config(self): + return SpeechT5Config( + hidden_size=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, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + vocab_size=self.vocab_size, + num_mel_bins=self.num_mel_bins, + reduction_factor=self.reduction_factor, + speech_decoder_postnet_layers=self.speech_decoder_postnet_layers, + speech_decoder_postnet_units=self.speech_decoder_postnet_units, + speech_decoder_prenet_units=self.speech_decoder_prenet_units, + ) + + def create_and_check_model_forward(self, config, inputs_dict): + model = SpeechT5ForSpeechToSpeech(config=config).to(torch_device).eval() + + input_values = inputs_dict["input_values"] + attention_mask = inputs_dict["attention_mask"] + decoder_input_values = inputs_dict["decoder_input_values"] + + result = model(input_values, attention_mask=attention_mask, decoder_input_values=decoder_input_values) + self.parent.assertEqual( + result.spectrogram.shape, + (self.batch_size, self.decoder_seq_length * self.reduction_factor, self.num_mel_bins), + ) + + +@require_torch +class SpeechT5ForSpeechToSpeechTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (SpeechT5ForSpeechToSpeech,) if is_torch_available() else () + all_generative_model_classes = (SpeechT5ForSpeechToSpeech,) if is_torch_available() else () + is_encoder_decoder = True + test_pruning = False + test_headmasking = False + test_resize_embeddings = False + + input_name = "input_values" + + def setUp(self): + self.model_tester = SpeechT5ForSpeechToSpeechTester(self) + self.config_tester = ConfigTester(self, config_class=SpeechT5Config, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_save_load_strict(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) + self.assertEqual(info["missing_keys"], []) + + def test_model_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + # skipped because there is always dropout in SpeechT5SpeechDecoderPrenet + def test_decoder_model_past_with_large_inputs(self): + pass + + # skipped because there is always dropout in SpeechT5SpeechDecoderPrenet + def test_determinism(self): + pass + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + + subsampled_encoder_seq_length = model.speecht5.encoder.prenet._get_feat_extract_output_lengths( + encoder_seq_length + ) + subsampled_encoder_key_length = model.speecht5.encoder.prenet._get_feat_extract_output_lengths( + encoder_key_length + ) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + out_len = len(outputs) + + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + subsampled_encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_values", + "attention_mask", + "decoder_input_values", + "decoder_attention_mask", + ] + expected_arg_names.extend( + ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + else: + seq_length = self.model_tester.seq_length + + subsampled_seq_length = model.speecht5.encoder.prenet._get_feat_extract_output_lengths(seq_length) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [subsampled_seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # this model has no inputs_embeds + def test_inputs_embeds(self): + pass + + # this model has no input embeddings + def test_model_common_attributes(self): + pass + + # skipped because there is always dropout in SpeechT5SpeechDecoderPrenet + def test_model_outputs_equivalence(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + # decoder cannot keep gradients + pass + + # skipped because there is always dropout in SpeechT5SpeechDecoderPrenet + def test_save_load(self): + pass + + @slow + def test_torchscript_output_attentions(self): + # disabled because this model doesn't have decoder_input_ids + pass + + @slow + def test_torchscript_output_hidden_state(self): + # disabled because this model doesn't have decoder_input_ids + pass + + @slow + def test_torchscript_simple(self): + # disabled because this model doesn't have decoder_input_ids + pass + + # training is not supported yet + def test_training(self): + pass + + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + +@require_torch +@require_sentencepiece +@require_tokenizers +@slow +class SpeechT5ForSpeechToSpeechIntegrationTests(unittest.TestCase): + @cached_property + def default_processor(self): + return SpeechT5Processor.from_pretrained("microsoft/speecht5_vc") + + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_generation_librispeech(self): + model = SpeechT5ForSpeechToSpeech.from_pretrained("microsoft/speecht5_vc") + model.to(torch_device) + processor = self.default_processor + + input_speech = self._load_datasamples(1) + input_values = processor(audio=input_speech, return_tensors="pt").input_values.to(torch_device) + + speaker_embeddings = torch.zeros((1, 512), device=torch_device) + generated_speech = model.generate_speech(input_values, speaker_embeddings=speaker_embeddings) + + self.assertEqual(generated_speech.shape[1], model.config.num_mel_bins) + self.assertGreaterEqual(generated_speech.shape[0], 300) + self.assertLessEqual(generated_speech.shape[0], 310) + + +class SpeechT5HifiGanTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=False, + num_mel_bins=20, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.num_mel_bins = num_mel_bins + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.seq_length, self.num_mel_bins], scale=1.0) + config = self.get_config() + return config, input_values + + def get_config(self): + return SpeechT5HifiGanConfig( + model_in_dim=self.num_mel_bins, + upsample_initial_channel=32, + ) + + def create_and_check_model(self, config, input_values): + model = SpeechT5HifiGan(config=config).to(torch_device).eval() + result = model(input_values) + self.parent.assertEqual(result.shape, (self.seq_length * 256,)) + + def prepare_config_and_inputs_for_common(self): + config, input_values = self.prepare_config_and_inputs() + inputs_dict = {"spectrogram": input_values} + return config, inputs_dict + + +@require_torch +class SpeechT5HifiGanTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (SpeechT5HifiGan,) if is_torch_available() else () + test_torchscript = False + test_pruning = False + test_resize_embeddings = False + test_resize_position_embeddings = False + test_head_masking = False + test_mismatched_shapes = False + test_missing_keys = False + test_model_parallel = False + is_encoder_decoder = False + has_attentions = False + + input_name = "spectrogram" + + def setUp(self): + self.model_tester = SpeechT5HifiGanTester(self) + self.config_tester = ConfigTester(self, config_class=SpeechT5HifiGanConfig) + + def test_config(self): + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_from_and_save_pretrained_subfolder() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "spectrogram", + ] + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + # this model does not output hidden states + def test_hidden_states_output(self): + pass + + # skip + def test_initialization(self): + pass + + # this model has no inputs_embeds + def test_inputs_embeds(self): + pass + + # this model has no input embeddings + def test_model_common_attributes(self): + pass + + # skip as this model doesn't support all arguments tested + def test_model_outputs_equivalence(self): + pass + + # this model does not output hidden states + def test_retain_grad_hidden_states_attentions(self): + pass + + # skip because it fails on automapping of SpeechT5HifiGanConfig + def test_save_load_fast_init_from_base(self): + pass + + # skip because it fails on automapping of SpeechT5HifiGanConfig + def test_save_load_fast_init_to_base(self): + pass + + def test_batched_inputs_outputs(self): + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + batched_inputs = inputs["spectrogram"].unsqueeze(0).repeat(2, 1, 1) + with torch.no_grad(): + batched_outputs = model(batched_inputs.to(torch_device)) + + self.assertEqual( + batched_inputs.shape[0], batched_outputs.shape[0], msg="Got different batch dims for input and output" + ) + + def test_unbatched_inputs_outputs(self): + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(inputs["spectrogram"].to(torch_device)) + self.assertTrue(outputs.dim() == 1, msg="Got un-batched inputs but batched output") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_processor_speecht5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_processor_speecht5.py new file mode 100644 index 0000000000000000000000000000000000000000..97d3842f105ad638de5263b6a13b6831ef4320e2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_processor_speecht5.py @@ -0,0 +1,185 @@ +# Copyright 2022 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. +"""Tests for the SpeechT5 processors.""" + +import json +import os +import shutil +import tempfile +import unittest + +from transformers import is_speech_available, is_torch_available +from transformers.models.speecht5 import SpeechT5Tokenizer +from transformers.testing_utils import get_tests_dir, require_torch +from transformers.utils import FEATURE_EXTRACTOR_NAME + + +if is_speech_available() and is_torch_available(): + from transformers import SpeechT5FeatureExtractor, SpeechT5Processor + + from .test_feature_extraction_speecht5 import floats_list + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") + + +@require_torch +class SpeechT5ProcessorTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + tokenizer = SpeechT5Tokenizer(SAMPLE_VOCAB) + tokenizer.save_pretrained(self.tmpdirname) + + feature_extractor_map = { + "feature_size": 1, + "padding_value": 0.0, + "sampling_rate": 16000, + "do_normalize": False, + "num_mel_bins": 80, + "hop_length": 16, + "win_length": 64, + "win_function": "hann_window", + "fmin": 80, + "fmax": 7600, + "mel_floor": 1e-10, + "reduction_factor": 2, + "return_attention_mask": True, + } + + self.feature_extraction_file = os.path.join(self.tmpdirname, FEATURE_EXTRACTOR_NAME) + with open(self.feature_extraction_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(feature_extractor_map) + "\n") + + def get_tokenizer(self, **kwargs): + return SpeechT5Tokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def get_feature_extractor(self, **kwargs): + return SpeechT5FeatureExtractor.from_pretrained(self.tmpdirname, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_save_load_pretrained_default(self): + tokenizer = self.get_tokenizer() + feature_extractor = self.get_feature_extractor() + + processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + processor.save_pretrained(self.tmpdirname) + processor = SpeechT5Processor.from_pretrained(self.tmpdirname) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) + self.assertIsInstance(processor.tokenizer, SpeechT5Tokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string()) + self.assertIsInstance(processor.feature_extractor, SpeechT5FeatureExtractor) + + def test_save_load_pretrained_additional_features(self): + processor = SpeechT5Processor(tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor()) + processor.save_pretrained(self.tmpdirname) + + tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)") + feature_extractor_add_kwargs = self.get_feature_extractor(do_normalize=False, padding_value=1.0) + + processor = SpeechT5Processor.from_pretrained( + self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0 + ) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) + self.assertIsInstance(processor.tokenizer, SpeechT5Tokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.feature_extractor, SpeechT5FeatureExtractor) + + def test_feature_extractor(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + raw_speech = floats_list((3, 1000)) + + input_feat_extract = feature_extractor(audio=raw_speech, return_tensors="np") + input_processor = processor(audio=raw_speech, return_tensors="np") + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_feature_extractor_target(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + raw_speech = floats_list((3, 1000)) + + input_feat_extract = feature_extractor(audio_target=raw_speech, return_tensors="np") + input_processor = processor(audio_target=raw_speech, return_tensors="np") + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_tokenizer(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + input_str = "This is a test string" + + encoded_processor = processor(text=input_str) + encoded_tok = tokenizer(input_str) + + for key in encoded_tok.keys(): + self.assertListEqual(encoded_tok[key], encoded_processor[key]) + + def test_tokenizer_target(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + input_str = "This is a test string" + + encoded_processor = processor(text_target=input_str) + encoded_tok = tokenizer(input_str) + + for key in encoded_tok.keys(): + self.assertListEqual(encoded_tok[key], encoded_processor[key]) + + def test_tokenizer_decode(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] + + decoded_processor = processor.batch_decode(predicted_ids) + decoded_tok = tokenizer.batch_decode(predicted_ids) + + self.assertListEqual(decoded_tok, decoded_processor) + + def test_model_input_names(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + self.assertListEqual( + processor.model_input_names, + feature_extractor.model_input_names, + msg="`processor` and `feature_extractor` model input names do not match", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_tokenization_speecht5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_tokenization_speecht5.py new file mode 100644 index 0000000000000000000000000000000000000000..f078402d505a6983bdda4fda28c51d53bd7a1bbd --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/speecht5/test_tokenization_speecht5.py @@ -0,0 +1,204 @@ +# coding=utf-8 +# Copyright 2022 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. +"""Tests for the SpeechT5 tokenizers.""" + +import unittest + +from transformers import SPIECE_UNDERLINE +from transformers.models.speecht5 import SpeechT5Tokenizer +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow +from transformers.tokenization_utils import AddedToken + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") + + +@require_sentencepiece +@require_tokenizers +class SpeechT5TokenizerTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = SpeechT5Tokenizer + test_rust_tokenizer = False + test_sentencepiece = True + + def setUp(self): + super().setUp() + + # We have a SentencePiece fixture for testing + tokenizer = SpeechT5Tokenizer(SAMPLE_VOCAB) + + mask_token = AddedToken("", lstrip=True, rstrip=False) + tokenizer.mask_token = mask_token + tokenizer.add_special_tokens({"mask_token": mask_token}) + tokenizer.add_tokens([""]) + + tokenizer.save_pretrained(self.tmpdirname) + + def get_input_output_texts(self, tokenizer): + input_text = "this is a test" + output_text = "this is a test" + return input_text, output_text + + def get_numeric_input_output_texts(self): + input_text = "I have $123.45 and owe €59.78. My balance is -₴876.90 and have 73% stocks in my company which equals to ₦72649201" + output_text = "I have one hundred and twenty three point four five dollars and owe fifty nine point seven eight euros. My balance is minus eight hundred and seventy six point nine zero ukrainian hryvnia and have seventy three percent stocks in my company which equals to seventy two million six hundred and forty nine thousand two hundred and one nigerian naira" + return input_text, output_text + + def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5): + input_text, output_text = self.get_input_output_texts(tokenizer) + ids = tokenizer.encode(output_text, add_special_tokens=False) + text = tokenizer.decode(ids, clean_up_tokenization_spaces=False) + return text, ids + + def test_tokenizer_normalization(self): + tokenizer = self.get_tokenizer(normalize=True) + input_text, expected_text = self.get_numeric_input_output_texts() + input_ids = tokenizer.encode(input_text) + output_text = tokenizer.decode(input_ids, skip_special_tokens=True) + self.assertEqual(output_text, expected_text) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "" + token_id = 1 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + self.assertEqual(vocab_keys[-4], "œ") + self.assertEqual(vocab_keys[-2], "") + self.assertEqual(vocab_keys[-1], "") + self.assertEqual(len(vocab_keys), 81) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 79) + + def test_add_tokens_tokenizer(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + vocab_size = tokenizer.vocab_size + all_size = len(tokenizer) + + self.assertNotEqual(vocab_size, 0) + + # We usually have added tokens from the start in tests because our vocab fixtures are + # smaller than the original vocabs - let's not assert this + # self.assertEqual(vocab_size, all_size) + + new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd"] + added_toks = tokenizer.add_tokens(new_toks) + vocab_size_2 = tokenizer.vocab_size + all_size_2 = len(tokenizer) + + self.assertNotEqual(vocab_size_2, 0) + self.assertEqual(vocab_size, vocab_size_2) + self.assertEqual(added_toks, len(new_toks)) + self.assertEqual(all_size_2, all_size + len(new_toks)) + + tokens = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False) + + self.assertGreaterEqual(len(tokens), 4) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-3], tokenizer.vocab_size - 1) + + new_toks_2 = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} + added_toks_2 = tokenizer.add_special_tokens(new_toks_2) + vocab_size_3 = tokenizer.vocab_size + all_size_3 = len(tokenizer) + + self.assertNotEqual(vocab_size_3, 0) + self.assertEqual(vocab_size, vocab_size_3) + self.assertEqual(added_toks_2, len(new_toks_2)) + self.assertEqual(all_size_3, all_size_2 + len(new_toks_2)) + + tokens = tokenizer.encode( + ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", add_special_tokens=False + ) + + self.assertGreaterEqual(len(tokens), 6) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[0], tokens[1]) + self.assertGreater(tokens[-3], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-3], tokens[-4]) + self.assertEqual(tokens[0], tokenizer.eos_token_id) + self.assertEqual(tokens[-3], tokenizer.pad_token_id) + + def test_pickle_subword_regularization_tokenizer(self): + pass + + def test_subword_regularization_tokenizer(self): + pass + + def test_full_tokenizer(self): + tokenizer = self.get_tokenizer(normalize=True) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, [SPIECE_UNDERLINE, 'T', 'h', 'i', 's', SPIECE_UNDERLINE, 'i', 's', SPIECE_UNDERLINE, 'a', SPIECE_UNDERLINE, 't', 'e', 's', 't']) # fmt: skip + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual(tokens,[SPIECE_UNDERLINE, 'I', SPIECE_UNDERLINE, 'w', 'a', 's', SPIECE_UNDERLINE, 'b', 'o', 'r', 'n', SPIECE_UNDERLINE, 'i', 'n', SPIECE_UNDERLINE, 'n', 'i', 'n', 'e', 't', 'y', SPIECE_UNDERLINE, 't', 'w', 'o', SPIECE_UNDERLINE, 't', 'h', 'o', 'u', 's', 'a', 'n', 'd', ',', SPIECE_UNDERLINE, 'a', 'n', 'd', SPIECE_UNDERLINE, 't', 'h', 'i', 's', SPIECE_UNDERLINE, 'i', 's', SPIECE_UNDERLINE, 'f', 'a', 'l', 's', 'é', '.']) # fmt: skip + + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual(ids, [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 9, 10, 9, 5, 6, 22, 4, 6, 20, 8, 4, 6, 11, 8, 16, 12, 7, 9, 14, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26]) # fmt: skip + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual(back_tokens,[SPIECE_UNDERLINE, 'I', SPIECE_UNDERLINE, 'w', 'a', 's', SPIECE_UNDERLINE, 'b', 'o', 'r', 'n', SPIECE_UNDERLINE, 'i', 'n', SPIECE_UNDERLINE, 'n', 'i', 'n', 'e', 't', 'y', SPIECE_UNDERLINE, 't', 'w', 'o', SPIECE_UNDERLINE, 't', 'h', 'o', 'u', 's', 'a', 'n', 'd', ',', SPIECE_UNDERLINE, 'a', 'n', 'd', SPIECE_UNDERLINE, 't', 'h', 'i', 's', SPIECE_UNDERLINE, 'i', 's', SPIECE_UNDERLINE, 'f', 'a', 'l', 's', 'é', '.']) # fmt: skip + + @slow + def test_tokenizer_integration(self): + # Use custom sequence because this tokenizer does not handle numbers. + sequences = [ + "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " + "general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural " + "Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained " + "models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.", + "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " + "conditioning on both left and right context in all layers.", + "The quick brown fox jumps over the lazy dog.", + ] + + # fmt: off + expected_encoding = { + 'input_ids': [ + [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], + [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + ], + 'attention_mask': [ + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + } + # fmt: on + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, + model_name="microsoft/speecht5_asr", + revision="c5ef64c71905caeccde0e4462ef3f9077224c524", + sequences=sequences, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/splinter/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/splinter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/splinter/test_modeling_splinter.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/splinter/test_modeling_splinter.py new file mode 100644 index 0000000000000000000000000000000000000000..90ee07c354588b0681824e4af2f9100507067c70 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/splinter/test_modeling_splinter.py @@ -0,0 +1,508 @@ +# coding=utf-8 +# 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 Splinter model. """ + +import copy +import unittest + +from transformers import is_torch_available +from transformers.testing_utils import require_torch, require_torch_multi_gpu, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import SplinterConfig, SplinterForPreTraining, SplinterForQuestionAnswering, SplinterModel + from transformers.models.splinter.modeling_splinter import SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST + + +class SplinterModelTester: + def __init__( + self, + parent, + batch_size=13, + num_questions=3, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + question_token_id=1, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.num_questions = num_questions + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + self.use_labels = use_labels + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.question_token_id = question_token_id + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + input_ids[:, 1] = self.question_token_id + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + start_positions = None + end_positions = None + question_positions = None + if self.use_labels: + start_positions = ids_tensor([self.batch_size, self.num_questions], self.type_sequence_label_size) + end_positions = ids_tensor([self.batch_size, self.num_questions], self.type_sequence_label_size) + question_positions = ids_tensor([self.batch_size, self.num_questions], self.num_labels) + + config = SplinterConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + question_token_id=self.question_token_id, + ) + + return (config, input_ids, token_type_ids, input_mask, start_positions, end_positions, question_positions) + + def create_and_check_model( + self, + config, + input_ids, + token_type_ids, + input_mask, + start_positions, + end_positions, + question_positions, + ): + model = SplinterModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_question_answering( + self, + config, + input_ids, + token_type_ids, + input_mask, + start_positions, + end_positions, + question_positions, + ): + model = SplinterForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=start_positions[:, 0], + end_positions=end_positions[:, 0], + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_for_pretraining( + self, + config, + input_ids, + token_type_ids, + input_mask, + start_positions, + end_positions, + question_positions, + ): + model = SplinterForPreTraining(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=start_positions, + end_positions=end_positions, + question_positions=question_positions, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.num_questions, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.num_questions, self.seq_length)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + start_positions, + end_positions, + question_positions, + ) = config_and_inputs + inputs_dict = { + "input_ids": input_ids, + "token_type_ids": token_type_ids, + "attention_mask": input_mask, + } + return config, inputs_dict + + +@require_torch +class SplinterModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + SplinterModel, + SplinterForQuestionAnswering, + SplinterForPreTraining, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + {"feature-extraction": SplinterModel, "question-answering": SplinterForQuestionAnswering} + if is_torch_available() + else {} + ) + + # TODO: Fix the failed tests when this model gets more usage + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "QAPipelineTests": + return True + elif pipeline_test_casse_name == "FeatureExtractionPipelineTests" and tokenizer_name.endswith("Fast"): + return True + + return False + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = copy.deepcopy(inputs_dict) + if return_labels: + if issubclass(model_class, SplinterForPreTraining): + inputs_dict["start_positions"] = torch.zeros( + self.model_tester.batch_size, + self.model_tester.num_questions, + dtype=torch.long, + device=torch_device, + ) + inputs_dict["end_positions"] = torch.zeros( + self.model_tester.batch_size, + self.model_tester.num_questions, + dtype=torch.long, + device=torch_device, + ) + inputs_dict["question_positions"] = torch.zeros( + self.model_tester.batch_size, + self.model_tester.num_questions, + dtype=torch.long, + device=torch_device, + ) + elif issubclass(model_class, SplinterForQuestionAnswering): + inputs_dict["start_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + inputs_dict["end_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + + return inputs_dict + + def setUp(self): + self.model_tester = SplinterModelTester(self) + self.config_tester = ConfigTester(self, config_class=SplinterConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_pretraining(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_pretraining(*config_and_inputs) + + def test_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + del inputs["input_ids"] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + + wte = model.get_input_embeddings() + if not self.is_encoder_decoder: + inputs["inputs_embeds"] = wte(input_ids) + else: + inputs["inputs_embeds"] = wte(encoder_input_ids) + inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) + + with torch.no_grad(): + if isinstance(model, SplinterForPreTraining): + with self.assertRaises(TypeError): + # question_positions must not be None. + model(**inputs)[0] + else: + model(**inputs)[0] + + @slow + def test_model_from_pretrained(self): + for model_name in SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SplinterModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + # overwrite from common since `SplinterForPreTraining` could contain different number of question tokens in inputs. + # When the batch is distributed to multiple devices, each replica could get different values for the maximal number + # of question tokens (see `SplinterForPreTraining._prepare_question_positions()`), and the model returns different + # shape along dimension 1 (i.e. `num_questions`) that could not be combined into a single tensor as an output. + @require_torch_multi_gpu + def test_multi_gpu_data_parallel_forward(self): + from torch import nn + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # some params shouldn't be scattered by nn.DataParallel + # so just remove them if they are present. + blacklist_non_batched_params = ["head_mask", "decoder_head_mask", "cross_attn_head_mask"] + for k in blacklist_non_batched_params: + inputs_dict.pop(k, None) + + # move input tensors to cuda:O + for k, v in inputs_dict.items(): + if torch.is_tensor(v): + inputs_dict[k] = v.to(0) + + for model_class in self.all_model_classes: + # Skip this case since it will fail sometimes, as described above. + if model_class == SplinterForPreTraining: + continue + + model = model_class(config=config) + model.to(0) + model.eval() + + # Wrap model in nn.DataParallel + model = nn.DataParallel(model) + with torch.no_grad(): + _ = model(**self._prepare_for_class(inputs_dict, model_class)) + + +@require_torch +class SplinterModelIntegrationTest(unittest.TestCase): + @slow + def test_splinter_question_answering(self): + model = SplinterForQuestionAnswering.from_pretrained("tau/splinter-base-qass") + + # Input: "[CLS] Brad was born in [QUESTION] . He returned to the United Kingdom later . [SEP]" + # Output should be the span "the United Kingdom" + input_ids = torch.tensor( + [[101, 7796, 1108, 1255, 1107, 104, 119, 1124, 1608, 1106, 1103, 1244, 2325, 1224, 119, 102]] + ) + output = model(input_ids) + + expected_shape = torch.Size((1, 16)) + self.assertEqual(output.start_logits.shape, expected_shape) + self.assertEqual(output.end_logits.shape, expected_shape) + + self.assertEqual(torch.argmax(output.start_logits), 10) + self.assertEqual(torch.argmax(output.end_logits), 12) + + @slow + def test_splinter_pretraining(self): + model = SplinterForPreTraining.from_pretrained("tau/splinter-base-qass") + + # Input: "[CLS] [QUESTION] was born in [QUESTION] . Brad returned to the United Kingdom later . [SEP]" + # Output should be the spans "Brad" and "the United Kingdom" + input_ids = torch.tensor( + [[101, 104, 1108, 1255, 1107, 104, 119, 7796, 1608, 1106, 1103, 1244, 2325, 1224, 119, 102]] + ) + question_positions = torch.tensor([[1, 5]], dtype=torch.long) + output = model(input_ids, question_positions=question_positions) + + expected_shape = torch.Size((1, 2, 16)) + self.assertEqual(output.start_logits.shape, expected_shape) + self.assertEqual(output.end_logits.shape, expected_shape) + + self.assertEqual(torch.argmax(output.start_logits[0, 0]), 7) + self.assertEqual(torch.argmax(output.end_logits[0, 0]), 7) + self.assertEqual(torch.argmax(output.start_logits[0, 1]), 10) + self.assertEqual(torch.argmax(output.end_logits[0, 1]), 12) + + @slow + def test_splinter_pretraining_loss_requires_question_positions(self): + model = SplinterForPreTraining.from_pretrained("tau/splinter-base-qass") + + # Input: "[CLS] [QUESTION] was born in [QUESTION] . Brad returned to the United Kingdom later . [SEP]" + # Output should be the spans "Brad" and "the United Kingdom" + input_ids = torch.tensor( + [[101, 104, 1108, 1255, 1107, 104, 119, 7796, 1608, 1106, 1103, 1244, 2325, 1224, 119, 102]] + ) + start_positions = torch.tensor([[7, 10]], dtype=torch.long) + end_positions = torch.tensor([7, 12], dtype=torch.long) + with self.assertRaises(TypeError): + model( + input_ids, + start_positions=start_positions, + end_positions=end_positions, + ) + + @slow + def test_splinter_pretraining_loss(self): + model = SplinterForPreTraining.from_pretrained("tau/splinter-base-qass") + + # Input: "[CLS] [QUESTION] was born in [QUESTION] . Brad returned to the United Kingdom later . [SEP]" + # Output should be the spans "Brad" and "the United Kingdom" + input_ids = torch.tensor( + [ + [101, 104, 1108, 1255, 1107, 104, 119, 7796, 1608, 1106, 1103, 1244, 2325, 1224, 119, 102], + [101, 104, 1108, 1255, 1107, 104, 119, 7796, 1608, 1106, 1103, 1244, 2325, 1224, 119, 102], + ] + ) + start_positions = torch.tensor([[7, 10], [7, 10]], dtype=torch.long) + end_positions = torch.tensor([[7, 12], [7, 12]], dtype=torch.long) + question_positions = torch.tensor([[1, 5], [1, 5]], dtype=torch.long) + output = model( + input_ids, + start_positions=start_positions, + end_positions=end_positions, + question_positions=question_positions, + ) + self.assertAlmostEqual(output.loss.item(), 0.0024, 4) + + @slow + def test_splinter_pretraining_loss_with_padding(self): + model = SplinterForPreTraining.from_pretrained("tau/splinter-base-qass") + + # Input: "[CLS] [QUESTION] was born in [QUESTION] . Brad returned to the United Kingdom later . [SEP]" + # Output should be the spans "Brad" and "the United Kingdom" + input_ids = torch.tensor( + [ + [101, 104, 1108, 1255, 1107, 104, 119, 7796, 1608, 1106, 1103, 1244, 2325, 1224, 119, 102], + ] + ) + start_positions = torch.tensor([[7, 10]], dtype=torch.long) + end_positions = torch.tensor([7, 12], dtype=torch.long) + question_positions = torch.tensor([[1, 5]], dtype=torch.long) + start_positions_with_padding = torch.tensor([[7, 10, 0]], dtype=torch.long) + end_positions_with_padding = torch.tensor([7, 12, 0], dtype=torch.long) + question_positions_with_padding = torch.tensor([[1, 5, 0]], dtype=torch.long) + output = model( + input_ids, + start_positions=start_positions, + end_positions=end_positions, + question_positions=question_positions, + ) + output_with_padding = model( + input_ids, + start_positions=start_positions_with_padding, + end_positions=end_positions_with_padding, + question_positions=question_positions_with_padding, + ) + + self.assertAlmostEqual(output.loss.item(), output_with_padding.loss.item(), 4) + + # Note that the original code uses 0 to denote padded question tokens + # and their start and end positions. As the pad_token_id of the model's + # config is used for the losse's ignore_index in SplinterForPreTraining, + # we add this test to ensure anybody making changes to the default + # value of the config, will be aware of the implication. + self.assertEqual(model.config.pad_token_id, 0) + + @slow + def test_splinter_pretraining_prepare_question_positions(self): + model = SplinterForPreTraining.from_pretrained("tau/splinter-base-qass") + + input_ids = torch.tensor( + [ + [101, 104, 1, 2, 104, 3, 4, 102], + [101, 1, 104, 2, 104, 3, 104, 102], + [101, 1, 2, 104, 104, 3, 4, 102], + [101, 1, 2, 3, 4, 5, 104, 102], + ] + ) + question_positions = torch.tensor([[1, 4, 0], [2, 4, 6], [3, 4, 0], [6, 0, 0]], dtype=torch.long) + output_without_positions = model(input_ids) + output_with_positions = model(input_ids, question_positions=question_positions) + self.assertTrue((output_without_positions.start_logits == output_with_positions.start_logits).all()) + self.assertTrue((output_without_positions.end_logits == output_with_positions.end_logits).all()) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/squeezebert/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/squeezebert/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/squeezebert/test_modeling_squeezebert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/squeezebert/test_modeling_squeezebert.py new file mode 100644 index 0000000000000000000000000000000000000000..bf86792f57f1ef75dc9fa63a9c106f55d5dea7b8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/squeezebert/test_modeling_squeezebert.py @@ -0,0 +1,298 @@ +# coding=utf-8 +# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team. +# +# 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 unittest + +from transformers import SqueezeBertConfig, is_torch_available +from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, + SqueezeBertForMaskedLM, + SqueezeBertForMultipleChoice, + SqueezeBertForQuestionAnswering, + SqueezeBertForSequenceClassification, + SqueezeBertForTokenClassification, + SqueezeBertModel, + ) + + +class SqueezeBertModelTester(object): + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=False, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=64, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + q_groups=2, + k_groups=2, + v_groups=2, + post_attention_groups=2, + intermediate_groups=4, + output_groups=1, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + self.q_groups = q_groups + self.k_groups = k_groups + self.v_groups = v_groups + self.post_attention_groups = post_attention_groups + self.intermediate_groups = intermediate_groups + self.output_groups = output_groups + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels + + def get_config(self): + return SqueezeBertConfig( + embedding_size=self.hidden_size, + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + attention_probs_dropout_prob=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + initializer_range=self.initializer_range, + q_groups=self.q_groups, + k_groups=self.k_groups, + v_groups=self.v_groups, + post_attention_groups=self.post_attention_groups, + intermediate_groups=self.intermediate_groups, + output_groups=self.output_groups, + ) + + def create_and_check_squeezebert_model( + self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = SqueezeBertModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, input_mask) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_squeezebert_for_masked_lm( + self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = SqueezeBertForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_squeezebert_for_question_answering( + self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = SqueezeBertForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, attention_mask=input_mask, start_positions=sequence_labels, end_positions=sequence_labels + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_squeezebert_for_sequence_classification( + self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = SqueezeBertForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, labels=sequence_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_squeezebert_for_token_classification( + self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = SqueezeBertForTokenClassification(config=config) + model.to(torch_device) + model.eval() + + result = model(input_ids, attention_mask=input_mask, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_squeezebert_for_multiple_choice( + self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = SqueezeBertForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + (config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class SqueezeBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + SqueezeBertModel, + SqueezeBertForMaskedLM, + SqueezeBertForMultipleChoice, + SqueezeBertForQuestionAnswering, + SqueezeBertForSequenceClassification, + SqueezeBertForTokenClassification, + ) + if is_torch_available() + else None + ) + pipeline_model_mapping = ( + { + "feature-extraction": SqueezeBertModel, + "fill-mask": SqueezeBertForMaskedLM, + "question-answering": SqueezeBertForQuestionAnswering, + "text-classification": SqueezeBertForSequenceClassification, + "token-classification": SqueezeBertForTokenClassification, + "zero-shot": SqueezeBertForSequenceClassification, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_resize_embeddings = True + test_head_masking = False + + def setUp(self): + self.model_tester = SqueezeBertModelTester(self) + self.config_tester = ConfigTester(self, config_class=SqueezeBertConfig, dim=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_squeezebert_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_squeezebert_model(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_squeezebert_for_masked_lm(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_squeezebert_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_squeezebert_for_sequence_classification(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_squeezebert_for_token_classification(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_squeezebert_for_multiple_choice(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SqueezeBertModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_sentencepiece +@require_tokenizers +@require_torch +class SqueezeBertModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_classification_head(self): + model = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli") + + input_ids = torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]]) + output = model(input_ids)[0] + expected_shape = torch.Size((1, 3)) + self.assertEqual(output.shape, expected_shape) + expected_tensor = torch.tensor([[0.6401, -0.0349, -0.6041]]) + self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/squeezebert/test_tokenization_squeezebert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/squeezebert/test_tokenization_squeezebert.py new file mode 100644 index 0000000000000000000000000000000000000000..a65862556405e8d3cdb319658ec637369ae2178a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/squeezebert/test_tokenization_squeezebert.py @@ -0,0 +1,45 @@ +# coding=utf-8 +# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team. +# +# 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. + + +from transformers import SqueezeBertTokenizer, SqueezeBertTokenizerFast +from transformers.testing_utils import require_tokenizers, slow + +from ..bert.test_tokenization_bert import BertTokenizationTest + + +@require_tokenizers +class SqueezeBertTokenizationTest(BertTokenizationTest): + tokenizer_class = SqueezeBertTokenizer + rust_tokenizer_class = SqueezeBertTokenizerFast + test_rust_tokenizer = True + + def get_rust_tokenizer(self, **kwargs): + return SqueezeBertTokenizerFast.from_pretrained(self.tmpdirname, **kwargs) + + @slow + def test_sequence_builders(self): + tokenizer = SqueezeBertTokenizer.from_pretrained("squeezebert/squeezebert-mnli-headless") + + text = tokenizer.encode("sequence builders", add_special_tokens=False) + text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False) + + encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [ + tokenizer.sep_token_id + ] diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swiftformer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swiftformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swiftformer/test_modeling_swiftformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swiftformer/test_modeling_swiftformer.py new file mode 100644 index 0000000000000000000000000000000000000000..83b6aa3510d925500569b528143163d525790a35 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swiftformer/test_modeling_swiftformer.py @@ -0,0 +1,293 @@ +# coding=utf-8 +# Copyright 2023 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 SwiftFormer model. """ + + +import copy +import unittest + +from transformers import PretrainedConfig, SwiftFormerConfig +from transformers.testing_utils import ( + require_torch, + require_vision, + slow, + torch_device, +) +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import SwiftFormerForImageClassification, SwiftFormerModel + from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import ViTImageProcessor + + +class SwiftFormerModelTester: + def __init__( + self, + parent, + batch_size=13, + num_channels=3, + is_training=True, + use_labels=True, + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + image_size=224, + num_labels=3, + layer_depths=[1, 1, 1, 1], + embed_dims=[16, 16, 32, 32], + ): + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.num_labels = num_labels + self.image_size = image_size + self.layer_depths = layer_depths + self.embed_dims = embed_dims + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.num_labels) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return SwiftFormerConfig( + depths=self.layer_depths, + embed_dims=self.embed_dims, + mlp_ratio=4, + downsamples=[True, True, True, True], + hidden_act="gelu", + num_labels=self.num_labels, + down_patch_size=3, + down_stride=2, + down_pad=1, + drop_rate=0.0, + drop_path_rate=0.0, + use_layer_scale=True, + layer_scale_init_value=1e-5, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = SwiftFormerModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.embed_dims[-1], 7, 7)) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.num_labels + model = SwiftFormerForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + model = SwiftFormerForImageClassification(config) + model.to(torch_device) + model.eval() + + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + (config, pixel_values, labels) = self.prepare_config_and_inputs() + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class SwiftFormerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as SwiftFormer does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification} + if is_torch_available() + else {} + ) + + fx_compatible = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + has_attentions = False + + def setUp(self): + self.model_tester = SwiftFormerModelTester(self) + self.config_tester = ConfigTester( + self, + config_class=SwiftFormerConfig, + has_text_modality=False, + hidden_size=37, + num_attention_heads=12, + num_hidden_layers=12, + ) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="SwiftFormer does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SwiftFormerModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip(reason="SwiftFormer does not output attentions") + def test_attention_outputs(self): + pass + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_stages = 8 + self.assertEqual(len(hidden_states), expected_num_stages) # TODO + + # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) + # with the width and height being successively divided by 2, after every 2 blocks + for i in range(len(hidden_states)): + self.assertEqual( + hidden_states[i].shape, + torch.Size( + [ + self.model_tester.batch_size, + self.model_tester.embed_dims[i // 2], + (self.model_tester.image_size // 4) // 2 ** (i // 2), + (self.model_tester.image_size // 4) // 2 ** (i // 2), + ] + ), + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_initialization(self): + def _config_zero_init(config): + configs_no_init = copy.deepcopy(config) + for key in configs_no_init.__dict__.keys(): + if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: + setattr(configs_no_init, key, 1e-10) + if isinstance(getattr(configs_no_init, key, None), PretrainedConfig): + no_init_subconfig = _config_zero_init(getattr(configs_no_init, key)) + setattr(configs_no_init, key, no_init_subconfig) + return configs_no_init + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if param.requires_grad: + self.assertIn( + ((param.data.mean() * 1e9) / 1e9).round().item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class SwiftFormerModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ViTImageProcessor.from_pretrained("MBZUAI/swiftformer-xs") if is_vision_available() else None + + @slow + def test_inference_image_classification_head(self): + model = SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs").to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([[-2.1703e00, 2.1107e00, -2.0811e00]]).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin/test_modeling_swin.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin/test_modeling_swin.py new file mode 100644 index 0000000000000000000000000000000000000000..e82c13f8db2744445de956c2b97694e3a2fa6e71 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin/test_modeling_swin.py @@ -0,0 +1,504 @@ +# coding=utf-8 +# Copyright 2022 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 Swin model. """ + +import collections +import unittest + +from transformers import SwinConfig +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_backbone_common import BackboneTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel + from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class SwinModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=32, + patch_size=2, + num_channels=3, + embed_dim=16, + depths=[1, 2, 1], + num_heads=[2, 2, 4], + window_size=2, + mlp_ratio=2.0, + qkv_bias=True, + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + drop_path_rate=0.1, + hidden_act="gelu", + use_absolute_embeddings=False, + patch_norm=True, + initializer_range=0.02, + layer_norm_eps=1e-5, + is_training=True, + scope=None, + use_labels=True, + type_sequence_label_size=10, + encoder_stride=8, + out_features=["stage1", "stage2"], + out_indices=[1, 2], + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.embed_dim = embed_dim + self.depths = depths + self.num_heads = num_heads + self.window_size = window_size + self.mlp_ratio = mlp_ratio + self.qkv_bias = qkv_bias + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.drop_path_rate = drop_path_rate + self.hidden_act = hidden_act + self.use_absolute_embeddings = use_absolute_embeddings + self.patch_norm = patch_norm + self.layer_norm_eps = layer_norm_eps + self.initializer_range = initializer_range + self.is_training = is_training + self.scope = scope + self.use_labels = use_labels + self.type_sequence_label_size = type_sequence_label_size + self.encoder_stride = encoder_stride + self.out_features = out_features + self.out_indices = out_indices + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return SwinConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + embed_dim=self.embed_dim, + depths=self.depths, + num_heads=self.num_heads, + window_size=self.window_size, + mlp_ratio=self.mlp_ratio, + qkv_bias=self.qkv_bias, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + drop_path_rate=self.drop_path_rate, + hidden_act=self.hidden_act, + use_absolute_embeddings=self.use_absolute_embeddings, + path_norm=self.patch_norm, + layer_norm_eps=self.layer_norm_eps, + initializer_range=self.initializer_range, + encoder_stride=self.encoder_stride, + out_features=self.out_features, + out_indices=self.out_indices, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = SwinModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + expected_seq_len = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) + expected_dim = int(config.embed_dim * 2 ** (len(config.depths) - 1)) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim)) + + def create_and_check_backbone(self, config, pixel_values, labels): + model = SwinBackbone(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + # verify hidden states + self.parent.assertEqual(len(result.feature_maps), len(config.out_features)) + self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, model.channels[0], 16, 16]) + + # verify channels + self.parent.assertEqual(len(model.channels), len(config.out_features)) + + # verify backbone works with out_features=None + config.out_features = None + model = SwinBackbone(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + # verify feature maps + self.parent.assertEqual(len(result.feature_maps), 1) + self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, model.channels[-1], 4, 4]) + + # verify channels + self.parent.assertEqual(len(model.channels), 1) + + def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels): + model = SwinForMaskedImageModeling(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) + ) + + # test greyscale images + config.num_channels = 1 + model = SwinForMaskedImageModeling(config) + model.to(torch_device) + model.eval() + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size)) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.type_sequence_label_size + model = SwinForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + # test greyscale images + config.num_channels = 1 + model = SwinForImageClassification(config) + model.to(torch_device) + model.eval() + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + pixel_values, + labels, + ) = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class SwinModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + SwinModel, + SwinBackbone, + SwinForImageClassification, + SwinForMaskedImageModeling, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + {"feature-extraction": SwinModel, "image-classification": SwinForImageClassification} + if is_torch_available() + else {} + ) + fx_compatible = True + + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = SwinModelTester(self) + self.config_tester = ConfigTester(self, config_class=SwinConfig, embed_dim=37) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + # TODO: check if this works again for PyTorch 2.x.y + @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0.") + def test_multi_gpu_data_parallel_forward(self): + pass + + def test_training_gradient_checkpointing(self): + super().test_training_gradient_checkpointing() + + def test_backbone(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_backbone(*config_and_inputs) + + def test_for_masked_image_modeling(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @unittest.skip(reason="Swin does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="Swin Transformer does not use feedforward chunking") + def test_feed_forward_chunking(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + expected_num_attentions = len(self.model_tester.depths) + self.assertEqual(len(attentions), expected_num_attentions) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + window_size_squared = config.window_size**2 + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), expected_num_attentions) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_heads[0], window_size_squared, window_size_squared], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + # also another +1 for reshaped_hidden_states + added_hidden_states = 1 if model_class.__name__ == "SwinBackbone" else 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), expected_num_attentions) + + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_heads[0], window_size_squared, window_size_squared], + ) + + def check_hidden_states_output(self, inputs_dict, config, model_class, image_size): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths) + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + # Swin has a different seq_length + patch_size = ( + config.patch_size + if isinstance(config.patch_size, collections.abc.Iterable) + else (config.patch_size, config.patch_size) + ) + + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [num_patches, self.model_tester.embed_dim], + ) + + if not model_class.__name__ == "SwinBackbone": + reshaped_hidden_states = outputs.reshaped_hidden_states + self.assertEqual(len(reshaped_hidden_states), expected_num_layers) + + batch_size, num_channels, height, width = reshaped_hidden_states[0].shape + reshaped_hidden_states = ( + reshaped_hidden_states[0].view(batch_size, num_channels, height * width).permute(0, 2, 1) + ) + self.assertListEqual( + list(reshaped_hidden_states.shape[-2:]), + [num_patches, self.model_tester.embed_dim], + ) + + def test_hidden_states_output(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + image_size = ( + self.model_tester.image_size + if isinstance(self.model_tester.image_size, collections.abc.Iterable) + else (self.model_tester.image_size, self.model_tester.image_size) + ) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + self.check_hidden_states_output(inputs_dict, config, model_class, image_size) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + self.check_hidden_states_output(inputs_dict, config, model_class, image_size) + + def test_hidden_states_output_with_padding(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.patch_size = 3 + + image_size = ( + self.model_tester.image_size + if isinstance(self.model_tester.image_size, collections.abc.Iterable) + else (self.model_tester.image_size, self.model_tester.image_size) + ) + patch_size = ( + config.patch_size + if isinstance(config.patch_size, collections.abc.Iterable) + else (config.patch_size, config.patch_size) + ) + + padded_height = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) + padded_width = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) + + @slow + def test_model_from_pretrained(self): + for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SwinModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if "embeddings" not in name and param.requires_grad: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + +@require_vision +@require_torch +class SwinModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ( + AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224") + if is_vision_available() + else None + ) + + @slow + def test_inference_image_classification_head(self): + model = SwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224").to(torch_device) + image_processor = self.default_image_processor + + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + expected_slice = torch.tensor([-0.0948, -0.6454, -0.0921]).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) + + +@require_torch +class SwinBackboneTest(unittest.TestCase, BackboneTesterMixin): + all_model_classes = (SwinBackbone,) if is_torch_available() else () + config_class = SwinConfig + + def setUp(self): + self.model_tester = SwinModelTester(self) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin/test_modeling_tf_swin.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin/test_modeling_tf_swin.py new file mode 100644 index 0000000000000000000000000000000000000000..597643936f95c13a2217e5839eeefd811601f74e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin/test_modeling_tf_swin.py @@ -0,0 +1,407 @@ +# coding=utf-8 +# Copyright 2022 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 TF 2.0 Swin model. """ + + +from __future__ import annotations + +import inspect +import unittest + +import numpy as np + +from transformers import SwinConfig +from transformers.testing_utils import require_tf, require_vision, slow, to_2tuple +from transformers.utils import cached_property, is_tf_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers.models.swin.modeling_tf_swin import ( + TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, + TFSwinForImageClassification, + TFSwinForMaskedImageModeling, + TFSwinModel, + ) + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class TFSwinModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=32, + patch_size=2, + num_channels=3, + embed_dim=16, + depths=[1, 2, 1], + num_heads=[2, 2, 4], + window_size=2, + mlp_ratio=2.0, + qkv_bias=True, + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + drop_path_rate=0.1, + hidden_act="gelu", + use_absolute_embeddings=False, + patch_norm=True, + initializer_range=0.02, + layer_norm_eps=1e-5, + is_training=True, + scope=None, + use_labels=True, + type_sequence_label_size=10, + encoder_stride=8, + ) -> None: + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.embed_dim = embed_dim + self.depths = depths + self.num_heads = num_heads + self.window_size = window_size + self.mlp_ratio = mlp_ratio + self.qkv_bias = qkv_bias + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.drop_path_rate = drop_path_rate + self.hidden_act = hidden_act + self.use_absolute_embeddings = use_absolute_embeddings + self.patch_norm = patch_norm + self.layer_norm_eps = layer_norm_eps + self.initializer_range = initializer_range + self.is_training = is_training + self.scope = scope + self.use_labels = use_labels + self.type_sequence_label_size = type_sequence_label_size + self.encoder_stride = encoder_stride + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return SwinConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + embed_dim=self.embed_dim, + depths=self.depths, + num_heads=self.num_heads, + window_size=self.window_size, + mlp_ratio=self.mlp_ratio, + qkv_bias=self.qkv_bias, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + drop_path_rate=self.drop_path_rate, + hidden_act=self.hidden_act, + use_absolute_embeddings=self.use_absolute_embeddings, + path_norm=self.patch_norm, + layer_norm_eps=self.layer_norm_eps, + initializer_range=self.initializer_range, + encoder_stride=self.encoder_stride, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = TFSwinModel(config=config) + result = model(pixel_values) + + expected_seq_len = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) + expected_dim = int(config.embed_dim * 2 ** (len(config.depths) - 1)) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim)) + + def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels): + model = TFSwinForMaskedImageModeling(config=config) + result = model(pixel_values) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) + ) + + # test greyscale images + config.num_channels = 1 + model = TFSwinForMaskedImageModeling(config) + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size)) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.type_sequence_label_size + model = TFSwinForImageClassification(config) + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + # test greyscale images + config.num_channels = 1 + model = TFSwinForImageClassification(config) + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_tf +class TFSwinModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TFSwinModel, + TFSwinForImageClassification, + TFSwinForMaskedImageModeling, + ) + if is_tf_available() + else () + ) + pipeline_model_mapping = ( + {"feature-extraction": TFSwinModel, "image-classification": TFSwinForImageClassification} + if is_tf_available() + else {} + ) + + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + test_onnx = False + + def setUp(self): + self.model_tester = TFSwinModelTester(self) + self.config_tester = ConfigTester(self, config_class=SwinConfig, embed_dim=37) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_image_modeling(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @unittest.skip(reason="Swin does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), tf.keras.layers.Layer) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, tf.keras.layers.Dense)) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + expected_num_attentions = len(self.model_tester.depths) + self.assertEqual(len(attentions), expected_num_attentions) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + window_size_squared = config.window_size**2 + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), expected_num_attentions) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_heads[0], window_size_squared, window_size_squared], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + else: + # also another +1 for reshaped_hidden_states + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), expected_num_attentions) + + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_heads[0], window_size_squared, window_size_squared], + ) + + def check_hidden_states_output(self, inputs_dict, config, model_class, image_size): + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + hidden_states = outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths) + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + # Swin has a different seq_length + patch_size = to_2tuple(config.patch_size) + + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [num_patches, self.model_tester.embed_dim], + ) + + reshaped_hidden_states = outputs.reshaped_hidden_states + self.assertEqual(len(reshaped_hidden_states), expected_num_layers) + + batch_size, num_channels, height, width = reshaped_hidden_states[0].shape + + reshaped_hidden_states = tf.reshape(reshaped_hidden_states[0], (batch_size, num_channels, height * width)) + reshaped_hidden_states = tf.transpose(reshaped_hidden_states, (0, 2, 1)) + + self.assertListEqual( + list(reshaped_hidden_states.shape[-2:]), + [num_patches, self.model_tester.embed_dim], + ) + + def test_hidden_states_output(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + image_size = to_2tuple(self.model_tester.image_size) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + self.check_hidden_states_output(inputs_dict, config, model_class, image_size) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + self.check_hidden_states_output(inputs_dict, config, model_class, image_size) + + def test_inputs_requiring_padding(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.patch_size = 3 + + image_size = to_2tuple(self.model_tester.image_size) + patch_size = to_2tuple(config.patch_size) + + padded_height = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) + padded_width = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) + + @slow + def test_model_from_pretrained(self): + for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFSwinModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_vision +@require_tf +class TFSwinModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ( + AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224") + if is_vision_available() + else None + ) + + @slow + def test_inference_image_classification_head(self): + model = TFSwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224") + image_processor = self.default_image_processor + + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + inputs = image_processor(images=image, return_tensors="tf") + + # forward pass + outputs = model(inputs) + + # verify the logits + expected_shape = tf.TensorShape((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + expected_slice = tf.constant([-0.0948, -0.6454, -0.0921]) + self.assertTrue(np.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin2sr/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin2sr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin2sr/test_image_processing_swin2sr.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin2sr/test_image_processing_swin2sr.py new file mode 100644 index 0000000000000000000000000000000000000000..719ac79d09db239c0b8f3ae58be818380648f724 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin2sr/test_image_processing_swin2sr.py @@ -0,0 +1,181 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. +# +# 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 unittest + +import numpy as np + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + from transformers import Swin2SRImageProcessor + from transformers.image_transforms import get_image_size + + +class Swin2SRImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + image_size=18, + min_resolution=30, + max_resolution=400, + do_rescale=True, + rescale_factor=1 / 255, + do_pad=True, + pad_size=8, + ): + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.image_size = image_size + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_rescale = do_rescale + self.rescale_factor = rescale_factor + self.do_pad = do_pad + self.pad_size = pad_size + + def prepare_image_processor_dict(self): + return { + "do_rescale": self.do_rescale, + "rescale_factor": self.rescale_factor, + "do_pad": self.do_pad, + "pad_size": self.pad_size, + } + + def expected_output_image_shape(self, images): + img = images[0] + + if isinstance(img, Image.Image): + input_width, input_height = img.size + else: + input_height, input_width = img.shape[-2:] + + pad_height = (input_height // self.pad_size + 1) * self.pad_size - input_height + pad_width = (input_width // self.pad_size + 1) * self.pad_size - input_width + + return self.num_channels, input_height + pad_height, input_width + pad_width + + def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_image_inputs( + batch_size=self.batch_size, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class Swin2SRImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = Swin2SRImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = Swin2SRImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processor = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processor, "do_rescale")) + self.assertTrue(hasattr(image_processor, "rescale_factor")) + self.assertTrue(hasattr(image_processor, "do_pad")) + self.assertTrue(hasattr(image_processor, "pad_size")) + + def calculate_expected_size(self, image): + old_height, old_width = get_image_size(image) + size = self.image_processor_tester.pad_size + + pad_height = (old_height // size + 1) * size - old_height + pad_width = (old_width // size + 1) * size - old_width + return old_height + pad_height, old_width + pad_width + + # Swin2SRImageProcessor does not support batched input + def test_call_pil(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PIL images + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) + for image in image_inputs: + self.assertIsInstance(image, Image.Image) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Swin2SRImageProcessor does not support batched input + def test_call_numpy(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) + for image in image_inputs: + self.assertIsInstance(image, np.ndarray) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Swin2SRImageProcessor does not support batched input + def test_call_numpy_4_channels(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + self.image_processor_tester.num_channels = 4 + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) + for image in image_inputs: + self.assertIsInstance(image, np.ndarray) + + # Test not batched input + encoded_images = image_processing( + image_inputs[0], return_tensors="pt", input_data_format="channels_first" + ).pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + self.image_processor_tester.num_channels = 3 + + # Swin2SRImageProcessor does not support batched input + def test_call_pytorch(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin2sr/test_modeling_swin2sr.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin2sr/test_modeling_swin2sr.py new file mode 100644 index 0000000000000000000000000000000000000000..581e8debc7e7d783652b2265956cd01be53dbbbe --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swin2sr/test_modeling_swin2sr.py @@ -0,0 +1,334 @@ +# coding=utf-8 +# Copyright 2022 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 Swin2SR model. """ +import unittest + +from transformers import Swin2SRConfig +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import Swin2SRForImageSuperResolution, Swin2SRModel + from transformers.models.swin2sr.modeling_swin2sr import SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST + +if is_vision_available(): + from PIL import Image + + from transformers import Swin2SRImageProcessor + + +class Swin2SRModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=32, + patch_size=1, + num_channels=3, + num_channels_out=1, + embed_dim=16, + depths=[1, 2, 1], + num_heads=[2, 2, 4], + window_size=2, + mlp_ratio=2.0, + qkv_bias=True, + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + drop_path_rate=0.1, + hidden_act="gelu", + use_absolute_embeddings=False, + patch_norm=True, + initializer_range=0.02, + layer_norm_eps=1e-5, + is_training=True, + scope=None, + use_labels=False, + upscale=2, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.num_channels_out = num_channels_out + self.embed_dim = embed_dim + self.depths = depths + self.num_heads = num_heads + self.window_size = window_size + self.mlp_ratio = mlp_ratio + self.qkv_bias = qkv_bias + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.drop_path_rate = drop_path_rate + self.hidden_act = hidden_act + self.use_absolute_embeddings = use_absolute_embeddings + self.patch_norm = patch_norm + self.layer_norm_eps = layer_norm_eps + self.initializer_range = initializer_range + self.is_training = is_training + self.scope = scope + self.use_labels = use_labels + self.upscale = upscale + + # here we set some attributes to make tests pass + self.num_hidden_layers = len(depths) + self.hidden_size = embed_dim + self.seq_length = (image_size // patch_size) ** 2 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return Swin2SRConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + num_channels_out=self.num_channels_out, + embed_dim=self.embed_dim, + depths=self.depths, + num_heads=self.num_heads, + window_size=self.window_size, + mlp_ratio=self.mlp_ratio, + qkv_bias=self.qkv_bias, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + drop_path_rate=self.drop_path_rate, + hidden_act=self.hidden_act, + use_absolute_embeddings=self.use_absolute_embeddings, + path_norm=self.patch_norm, + layer_norm_eps=self.layer_norm_eps, + initializer_range=self.initializer_range, + upscale=self.upscale, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = Swin2SRModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.embed_dim, self.image_size, self.image_size) + ) + + def create_and_check_for_image_super_resolution(self, config, pixel_values, labels): + model = Swin2SRForImageSuperResolution(config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + expected_image_size = self.image_size * self.upscale + self.parent.assertEqual( + result.reconstruction.shape, + (self.batch_size, self.num_channels_out, expected_image_size, expected_image_size), + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class Swin2SRModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (Swin2SRModel, Swin2SRForImageSuperResolution) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": Swin2SRModel, "image-to-image": Swin2SRForImageSuperResolution} + if is_torch_available() + else {} + ) + + fx_compatible = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + test_torchscript = False + + def setUp(self): + self.model_tester = Swin2SRModelTester(self) + self.config_tester = ConfigTester(self, config_class=Swin2SRConfig, embed_dim=37) + + def test_config(self): + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_for_image_super_resolution(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_super_resolution(*config_and_inputs) + + # TODO: check if this works again for PyTorch 2.x.y + @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0.") + def test_multi_gpu_data_parallel_forward(self): + pass + + @unittest.skip(reason="Swin2SR does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="Swin2SR does not support training yet") + def test_training(self): + pass + + @unittest.skip(reason="Swin2SR does not support training yet") + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + @slow + def test_model_from_pretrained(self): + for model_name in SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = Swin2SRModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + # overwriting because of `logit_scale` parameter + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if "logit_scale" in name: + continue + if param.requires_grad: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + expected_num_attentions = len(self.model_tester.depths) + self.assertEqual(len(attentions), expected_num_attentions) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + window_size_squared = config.window_size**2 + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), expected_num_attentions) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_heads[0], window_size_squared, window_size_squared], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), expected_num_attentions) + + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_heads[0], window_size_squared, window_size_squared], + ) + + +@require_vision +@require_torch +@slow +class Swin2SRModelIntegrationTest(unittest.TestCase): + def test_inference_image_super_resolution_head(self): + processor = Swin2SRImageProcessor() + model = Swin2SRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x2-64").to(torch_device) + + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + inputs = processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size([1, 3, 976, 1296]) + self.assertEqual(outputs.reconstruction.shape, expected_shape) + expected_slice = torch.tensor( + [[0.5458, 0.5546, 0.5638], [0.5526, 0.5565, 0.5651], [0.5396, 0.5426, 0.5621]] + ).to(torch_device) + self.assertTrue(torch.allclose(outputs.reconstruction[0, 0, :3, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swinv2/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swinv2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swinv2/test_modeling_swinv2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swinv2/test_modeling_swinv2.py new file mode 100644 index 0000000000000000000000000000000000000000..9b9d08b39fd1b94e283af12c86192e7bf171a344 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/swinv2/test_modeling_swinv2.py @@ -0,0 +1,427 @@ +# coding=utf-8 +# Copyright 2022 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 Swinv2 model. """ +import collections +import unittest + +from transformers import Swinv2Config +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import Swinv2ForImageClassification, Swinv2ForMaskedImageModeling, Swinv2Model + from transformers.models.swinv2.modeling_swinv2 import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class Swinv2ModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=32, + patch_size=2, + num_channels=3, + embed_dim=16, + depths=[1, 2, 1], + num_heads=[2, 2, 4], + window_size=2, + mlp_ratio=2.0, + qkv_bias=True, + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + drop_path_rate=0.1, + hidden_act="gelu", + use_absolute_embeddings=False, + patch_norm=True, + initializer_range=0.02, + layer_norm_eps=1e-5, + is_training=True, + scope=None, + use_labels=True, + type_sequence_label_size=10, + encoder_stride=8, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.embed_dim = embed_dim + self.depths = depths + self.num_heads = num_heads + self.window_size = window_size + self.mlp_ratio = mlp_ratio + self.qkv_bias = qkv_bias + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.drop_path_rate = drop_path_rate + self.hidden_act = hidden_act + self.use_absolute_embeddings = use_absolute_embeddings + self.patch_norm = patch_norm + self.layer_norm_eps = layer_norm_eps + self.initializer_range = initializer_range + self.is_training = is_training + self.scope = scope + self.use_labels = use_labels + self.type_sequence_label_size = type_sequence_label_size + self.encoder_stride = encoder_stride + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return Swinv2Config( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + embed_dim=self.embed_dim, + depths=self.depths, + num_heads=self.num_heads, + window_size=self.window_size, + mlp_ratio=self.mlp_ratio, + qkv_bias=self.qkv_bias, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + drop_path_rate=self.drop_path_rate, + hidden_act=self.hidden_act, + use_absolute_embeddings=self.use_absolute_embeddings, + path_norm=self.patch_norm, + layer_norm_eps=self.layer_norm_eps, + initializer_range=self.initializer_range, + encoder_stride=self.encoder_stride, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = Swinv2Model(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + expected_seq_len = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) + expected_dim = int(config.embed_dim * 2 ** (len(config.depths) - 1)) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim)) + + def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels): + model = Swinv2ForMaskedImageModeling(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) + ) + + # test greyscale images + config.num_channels = 1 + model = Swinv2ForMaskedImageModeling(config) + model.to(torch_device) + model.eval() + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size)) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.type_sequence_label_size + model = Swinv2ForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class Swinv2ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (Swinv2Model, Swinv2ForImageClassification, Swinv2ForMaskedImageModeling) if is_torch_available() else () + ) + pipeline_model_mapping = ( + {"feature-extraction": Swinv2Model, "image-classification": Swinv2ForImageClassification} + if is_torch_available() + else {} + ) + + fx_compatible = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = Swinv2ModelTester(self) + self.config_tester = ConfigTester(self, config_class=Swinv2Config, embed_dim=37) + + def test_config(self): + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + # TODO: check if this works again for PyTorch 2.x.y + @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0.") + def test_multi_gpu_data_parallel_forward(self): + pass + + @unittest.skip(reason="Swinv2 does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + expected_num_attentions = len(self.model_tester.depths) + self.assertEqual(len(attentions), expected_num_attentions) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + window_size_squared = config.window_size**2 + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), expected_num_attentions) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_heads[0], window_size_squared, window_size_squared], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + else: + # also another +1 for reshaped_hidden_states + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), expected_num_attentions) + + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_heads[0], window_size_squared, window_size_squared], + ) + + def check_hidden_states_output(self, inputs_dict, config, model_class, image_size): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths) + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + # Swinv2 has a different seq_length + patch_size = ( + config.patch_size + if isinstance(config.patch_size, collections.abc.Iterable) + else (config.patch_size, config.patch_size) + ) + + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [num_patches, self.model_tester.embed_dim], + ) + + reshaped_hidden_states = outputs.reshaped_hidden_states + self.assertEqual(len(reshaped_hidden_states), expected_num_layers) + + batch_size, num_channels, height, width = reshaped_hidden_states[0].shape + reshaped_hidden_states = ( + reshaped_hidden_states[0].view(batch_size, num_channels, height * width).permute(0, 2, 1) + ) + self.assertListEqual( + list(reshaped_hidden_states.shape[-2:]), + [num_patches, self.model_tester.embed_dim], + ) + + def test_hidden_states_output(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + image_size = ( + self.model_tester.image_size + if isinstance(self.model_tester.image_size, collections.abc.Iterable) + else (self.model_tester.image_size, self.model_tester.image_size) + ) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + self.check_hidden_states_output(inputs_dict, config, model_class, image_size) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + self.check_hidden_states_output(inputs_dict, config, model_class, image_size) + + def test_hidden_states_output_with_padding(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.patch_size = 3 + + image_size = ( + self.model_tester.image_size + if isinstance(self.model_tester.image_size, collections.abc.Iterable) + else (self.model_tester.image_size, self.model_tester.image_size) + ) + patch_size = ( + config.patch_size + if isinstance(config.patch_size, collections.abc.Iterable) + else (config.patch_size, config.patch_size) + ) + + padded_height = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) + padded_width = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) + + def test_for_masked_image_modeling(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = Swinv2Model.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + +@require_vision +@require_torch +class Swinv2ModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ( + AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256") + if is_vision_available() + else None + ) + + @slow + def test_inference_image_classification_head(self): + model = Swinv2ForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256").to( + torch_device + ) + image_processor = self.default_image_processor + + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + expected_slice = torch.tensor([-0.3947, -0.4306, 0.0026]).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/switch_transformers/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/switch_transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/switch_transformers/test_modeling_switch_transformers.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/switch_transformers/test_modeling_switch_transformers.py new file mode 100644 index 0000000000000000000000000000000000000000..aa226f82ae360669df086936473dc7446b5ab82a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/switch_transformers/test_modeling_switch_transformers.py @@ -0,0 +1,1107 @@ +# coding=utf-8 +# Copyright 2022 Google SwitchTransformers Authors and HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import copy +import tempfile +import unittest + +from transformers import SwitchTransformersConfig, is_torch_available +from transformers.testing_utils import ( + require_tokenizers, + require_torch, + require_torch_accelerator, + require_torch_bf16, + slow, + torch_device, +) + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + AutoTokenizer, + SwitchTransformersEncoderModel, + SwitchTransformersForConditionalGeneration, + SwitchTransformersModel, + SwitchTransformersTop1Router, + ) + from transformers.models.switch_transformers.modeling_switch_transformers import ( + SWITCH_TRANSFORMERS_PRETRAINED_MODEL_ARCHIVE_LIST, + load_balancing_loss_func, + router_z_loss_func, + ) + + +class SwitchTransformersModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + decoder_seq_length=9, + # For common tests + is_training=True, + use_attention_mask=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + dropout_rate=0.1, + initializer_factor=0.002, + eos_token_id=1, + pad_token_id=0, + decoder_start_token_id=0, + decoder_layers=None, + sparse_step=1, + num_sparse_decoder_layers=2, + num_sparse_encoder_layers=2, + expert_capacity=100, + router_jitter_noise=0.0, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.scope = None + self.decoder_layers = decoder_layers + self.sparse_step = sparse_step + self.num_sparse_decoder_layers = num_sparse_decoder_layers + self.num_sparse_encoder_layers = num_sparse_encoder_layers + self.expert_capacity = expert_capacity + self.router_jitter_noise = router_jitter_noise + + def get_large_model_config(self): + return SwitchTransformersConfig.from_pretrained("google/switch-base-8") + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + attention_mask = None + decoder_attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2) + + lm_labels = None + if self.use_labels: + lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + config = self.get_config() + + return ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) + + def get_pipeline_config(self): + return SwitchTransformersConfig( + vocab_size=166, # switch_transformers forces 100 extra tokens + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + expert_capacity=self.expert_capacity, + router_jitter_noise=self.router_jitter_noise, + ) + + def get_config(self): + return SwitchTransformersConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + sparse_step=self.sparse_step, + num_sparse_encoder_layers=self.num_sparse_encoder_layers, + num_sparse_decoder_layers=self.num_sparse_decoder_layers, + ) + + def check_prepare_lm_labels_via_shift_left( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = SwitchTransformersModel(config=config) + model.to(torch_device) + model.eval() + + # make sure that lm_labels are correctly padded from the right + lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id) + + # add casaul pad token mask + triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not() + lm_labels.masked_fill_(triangular_mask, self.pad_token_id) + decoder_input_ids = model._shift_right(lm_labels) + + for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)): + # first item + self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id) + if i < decoder_input_ids_slice.shape[-1]: + if i < decoder_input_ids.shape[-1] - 1: + # items before diagonal + self.parent.assertListEqual( + decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist() + ) + # pad items after diagonal + if i < decoder_input_ids.shape[-1] - 2: + self.parent.assertListEqual( + decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist() + ) + else: + # all items after square + self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist()) + + def create_and_check_model( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = SwitchTransformersModel(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) + decoder_output = result.last_hidden_state + decoder_past = result.past_key_values + encoder_output = result.encoder_last_hidden_state + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size)) + self.parent.assertEqual(decoder_output.size(), (self.batch_size, self.decoder_seq_length, self.hidden_size)) + # There should be `num_layers` key value embeddings stored in decoder_past + self.parent.assertEqual(len(decoder_past), config.num_layers) + # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple + self.parent.assertEqual(len(decoder_past[0]), 4) + + def create_and_check_with_lm_head( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = SwitchTransformersForConditionalGeneration(config=config).to(torch_device).eval() + outputs = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + labels=lm_labels, + ) + self.parent.assertEqual(len(outputs), 10) + self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size)) + self.parent.assertEqual(outputs["loss"].size(), ()) + + def create_and_check_decoder_model_past( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = SwitchTransformersModel(config=config).get_decoder().to(torch_device).eval() + # first forward pass + outputs = model(input_ids, use_cache=True, output_router_logits=False) + outputs_use_cache_conf = model(input_ids, output_router_logits=False) + outputs_no_past = model(input_ids, use_cache=False, output_router_logits=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + output_from_no_past = model(next_input_ids, output_router_logits=False)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values, output_router_logits=False)[ + "last_hidden_state" + ] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_decoder_model_attention_mask_past( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = SwitchTransformersModel(config=config).get_decoder() + model.to(torch_device) + model.eval() + + # create attention mask + attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) + + half_seq_length = input_ids.shape[-1] // 2 + attn_mask[:, half_seq_length:] = 0 + + # first forward pass + output, past_key_values = model( + input_ids, attention_mask=attn_mask, use_cache=True, output_router_logits=False + ).to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1) + input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens + + # append to next input_ids and attn_mask + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + attn_mask = torch.cat( + [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)], + dim=1, + ) + + # get two different outputs + output_from_no_past = model(next_input_ids, attention_mask=attn_mask, output_router_logits=False)[ + "last_hidden_state" + ] + output_from_past = model( + next_tokens, past_key_values=past_key_values, attention_mask=attn_mask, output_router_logits=False + )["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = SwitchTransformersModel(config=config).get_decoder().to(torch_device).eval() + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True, output_router_logits=False) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([attention_mask, next_mask], dim=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask, output_router_logits=False)[ + "last_hidden_state" + ] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + past_key_values=past_key_values, + output_router_logits=False, + )["last_hidden_state"] + + # 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)) + + @slow + def create_and_check_generate_with_past_key_values( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + r""" + This test does not pass for small models due to precision errors. It is therefore only run for slightly larger models. + """ + model = ( + SwitchTransformersForConditionalGeneration.from_pretrained("google/switch-base-8").to(torch_device).eval() + ) + torch.manual_seed(0) + output_without_past_cache = model.generate( + input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False + ) + torch.manual_seed(0) + output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True) + self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache)) + + def create_and_check_model_fp16_forward( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = SwitchTransformersModel(config=config).to(torch_device).half().eval() + output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)["last_hidden_state"] + self.parent.assertFalse(torch.isnan(output).any().item()) + + def create_and_check_encoder_decoder_shared_weights( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + for model_class in [SwitchTransformersModel, SwitchTransformersForConditionalGeneration]: + torch.manual_seed(0) + model = model_class(config=config).to(torch_device).eval() + # load state dict copies weights but does not tie them + model.encoder.load_state_dict(model.decoder.state_dict(), strict=False) + + torch.manual_seed(0) + tied_config = copy.deepcopy(config) + tied_config.tie_encoder_decoder = True + tied_model = model_class(config=tied_config).to(torch_device).eval() + + model_result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + tied_model_result = tied_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + # check that models has less parameters + self.parent.assertLess( + sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters()) + ) + random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item() + + # check that outputs are equal + self.parent.assertTrue( + torch.allclose( + model_result[0][0, :, random_slice_idx], tied_model_result[0][0, :, random_slice_idx], atol=1e-4 + ) + ) + + # check that outputs after saving and loading are equal + with tempfile.TemporaryDirectory() as tmpdirname: + tied_model.save_pretrained(tmpdirname) + tied_model = model_class.from_pretrained(tmpdirname) + tied_model.to(torch_device) + tied_model.eval() + + # check that models has less parameters + self.parent.assertLess( + sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters()) + ) + random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item() + + tied_model_result = tied_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + # check that outputs are equal + self.parent.assertTrue( + torch.allclose( + model_result[0][0, :, random_slice_idx], + tied_model_result[0][0, :, random_slice_idx], + atol=1e-4, + ) + ) + + def check_resize_embeddings_switch_transformers_v1_1( + self, + config, + ): + prev_vocab_size = config.vocab_size + + config.tie_word_embeddings = False + model = SwitchTransformersForConditionalGeneration(config=config).to(torch_device).eval() + model.resize_token_embeddings(prev_vocab_size - 10) + + self.parent.assertEqual(model.get_input_embeddings().weight.shape[0], prev_vocab_size - 10) + self.parent.assertEqual(model.get_output_embeddings().weight.shape[0], prev_vocab_size - 10) + self.parent.assertEqual(model.config.vocab_size, prev_vocab_size - 10) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "use_cache": False, + "output_router_logits": False, + } + return config, inputs_dict + + +@require_torch +class SwitchTransformersModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (SwitchTransformersModel, SwitchTransformersForConditionalGeneration) if is_torch_available() else () + ) + all_generative_model_classes = (SwitchTransformersForConditionalGeneration,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "conversational": SwitchTransformersForConditionalGeneration, + "feature-extraction": SwitchTransformersModel, + "summarization": SwitchTransformersForConditionalGeneration, + "text2text-generation": SwitchTransformersForConditionalGeneration, + "translation": SwitchTransformersForConditionalGeneration, + } + if is_torch_available() + else {} + ) + fx_compatible = False + test_pruning = False + test_resize_embeddings = True + test_model_parallel = False + is_encoder_decoder = True + test_torchscript = False + # The small SWITCH_TRANSFORMERS model needs higher percentages for CPU/MP tests + model_split_percents = [0.8, 0.9] + + def setUp(self): + self.model_tester = SwitchTransformersModelTester(self) + self.config_tester = ConfigTester(self, config_class=SwitchTransformersConfig, d_model=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_shift_right(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_v1_1(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + # check that gated gelu feed forward and different word embeddings work + config = config_and_inputs[0] + config.tie_word_embeddings = False + config.feed_forward_proj = "gated-gelu" + self.model_tester.create_and_check_model(config, *config_and_inputs[1:]) + + def test_config_and_model_silu_gated(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config = config_and_inputs[0] + config.feed_forward_proj = "gated-silu" + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_with_lm_head(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_with_lm_head(*config_and_inputs) + + def test_decoder_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_past(*config_and_inputs) + + def test_decoder_model_past_with_attn_mask(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs) + + def test_decoder_model_past_with_3d_attn_mask(self): + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = self.model_tester.prepare_config_and_inputs() + + attention_mask = ids_tensor( + [self.model_tester.batch_size, self.model_tester.encoder_seq_length, self.model_tester.encoder_seq_length], + vocab_size=2, + ) + decoder_attention_mask = ids_tensor( + [self.model_tester.batch_size, self.model_tester.decoder_seq_length, self.model_tester.decoder_seq_length], + vocab_size=2, + ) + + self.model_tester.create_and_check_decoder_model_attention_mask_past( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) + + 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_generate_with_past_key_values(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_generate_with_past_key_values(*config_and_inputs) + + def test_encoder_decoder_shared_weights(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs) + + @unittest.skipIf(torch_device == "cpu", "Cant do half precision") + def test_model_fp16_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs) + + def test_v1_1_resize_embeddings(self): + config = self.model_tester.prepare_config_and_inputs()[0] + self.model_tester.check_resize_embeddings_switch_transformers_v1_1(config) + + @slow + def test_model_from_pretrained(self): + for model_name in SWITCH_TRANSFORMERS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = SwitchTransformersModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip("Test has a segmentation fault on torch 1.8.0") + def test_export_to_onnx(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + model = SwitchTransformersModel(config_and_inputs[0]).to(torch_device) + with tempfile.TemporaryDirectory() as tmpdirname: + torch.onnx.export( + model, + (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]), + f"{tmpdirname}/switch_transformers_test.onnx", + export_params=True, + opset_version=9, + input_names=["input_ids", "decoder_input_ids"], + ) + + def test_generate_with_head_masking(self): + attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"] + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config = config_and_inputs[0] + max_length = config_and_inputs[1].shape[-1] + 3 + model = SwitchTransformersForConditionalGeneration(config).eval() + model.to(torch_device) + + head_masking = { + "head_mask": torch.zeros(config.num_layers, config.num_heads, device=torch_device), + "decoder_head_mask": torch.zeros(config.num_decoder_layers, config.num_heads, device=torch_device), + "cross_attn_head_mask": torch.zeros(config.num_decoder_layers, config.num_heads, device=torch_device), + } + + for attn_name, (name, mask) in zip(attention_names, head_masking.items()): + head_masks = {name: mask} + # Explicitly pass decoder_head_mask as it is required from SWITCH_TRANSFORMERS model when head_mask specified + if name == "head_mask": + head_masks["decoder_head_mask"] = torch.ones( + config.num_decoder_layers, config.num_heads, device=torch_device + ) + + out = model.generate( + config_and_inputs[1], + num_beams=1, + max_length=max_length, + output_attentions=True, + return_dict_in_generate=True, + **head_masks, + ) + # We check the state of decoder_attentions and cross_attentions just from the last step + attn_weights = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] + self.assertEqual(sum([w.sum().item() for w in attn_weights]), 0.0) + + @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.") + def test_disk_offload(self): + pass + + +class SwitchTransformersEncoderOnlyModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + # For common tests + use_attention_mask=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + is_training=False, + dropout_rate=0.1, + initializer_factor=0.002, + is_encoder_decoder=False, + eos_token_id=1, + pad_token_id=0, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + # For common tests + self.seq_length = self.encoder_seq_length + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.is_encoder_decoder = is_encoder_decoder + self.scope = None + self.is_training = is_training + + def get_large_model_config(self): + return SwitchTransformersConfig.from_pretrained("switch_base_8") + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + + config = SwitchTransformersConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + return config, input_ids, attention_mask + + def create_and_check_model(self, config, input_ids, attention_mask): + model = SwitchTransformersEncoderModel(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + attention_mask=attention_mask, + ) + result = model(input_ids=input_ids) + encoder_output = result.last_hidden_state + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size)) + + def create_and_check_model_fp16_forward(self, config, input_ids, attention_mask): + model = SwitchTransformersEncoderModel(config=config).to(torch_device).half().eval() + output = model(input_ids, attention_mask=attention_mask)["last_hidden_state"] + self.parent.assertFalse(torch.isnan(output).any().item()) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, attention_mask = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + +class SwitchTransformersEncoderOnlyModelTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (SwitchTransformersEncoderModel,) if is_torch_available() else () + test_pruning = False + test_resize_embeddings = False + test_model_parallel = False + test_torchscript = False + + def setUp(self): + self.model_tester = SwitchTransformersEncoderOnlyModelTester(self) + self.config_tester = ConfigTester(self, config_class=SwitchTransformersConfig, d_model=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @unittest.skipIf(torch_device == "cpu", "Cant do half precision") + def test_model_fp16_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs) + + +def use_task_specific_params(model, task): + model.config.update(model.config.task_specific_params[task]) + + +@require_torch +class TestAsymmetricSwitchTransformers(unittest.TestCase): + def build_model_and_check_forward_pass(self, **kwargs): + tester = SwitchTransformersModelTester(self, **kwargs) + config, *inputs = tester.prepare_config_and_inputs() + ( + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = inputs + model = SwitchTransformersForConditionalGeneration(config=config).to(torch_device).eval() + outputs = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + labels=lm_labels, + output_router_logits=False, + ) + # outputs = model(*inputs) + assert len(outputs) == 4 + assert outputs["logits"].size() == (tester.batch_size, tester.decoder_seq_length, tester.vocab_size) + assert outputs["loss"].size() == () + return model + + def test_small_decoder(self): + # num_hidden_layers is passed to SwitchTransformersConfig as num_layers + model = self.build_model_and_check_forward_pass(decoder_layers=1, num_hidden_layers=2) + assert len(model.encoder.block) == 2 + assert len(model.decoder.block) == 1 + + def test_defaulting_to_symmetry(self): + # num_hidden_layers is passed to SwitchTransformersConfig as num_layers + model = self.build_model_and_check_forward_pass(num_hidden_layers=2) + assert len(model.decoder.block) == len(model.encoder.block) == 2 + + +@require_torch +class SwitchTransformerRouterTest(unittest.TestCase): + r""" + Switch Transformers has different blocks from classic transformer based models. + The Swift MLP contains a Router class, that has to be tested to check if it is correctly implemented + + Original implementation of the routers here: + + """ + + config = SwitchTransformersConfig( + num_experts=2, + hidden_size=8, + d_ff=16, + router_jitter_noise=0, + expert_capacity=4, + ) + + def test_equivalency_balancy_loss(self): + r""" + This test checks if the balancy loss is correctly implemented + as in the original implementation of the Switch Transformer . + """ + router_probs = torch.Tensor( + [ + [0.35490513, 0.60419905], + [0.4275843, 0.23061597], + [0.32985854, 0.43953657], + [0.25099766, 0.27730572], + [0.7678207, 0.71474564], + ] + ) + + expert_indices = torch.Tensor([[0], [1], [1], [0], [0]]).to(torch.int32) + + loss = load_balancing_loss_func(router_probs, expert_indices) + self.assertAlmostEqual(loss.item(), 0.8741045, places=5) + + def test_equivalency_router_z_loss(self): + r""" + This test checks if the router z loss is correctly implemented + as in the original implementation of the Switch Transformer . + """ + logits = torch.Tensor( + [ + [ + [-4.2124424, 3.891939, -3.6481273, 1.8849981], + [0.32625437, 2.918651, 0.84758997, -4.556842], + [-3.32062, 4.6977115, -0.15439987, 0.44086337], + [3.4467149, 4.3436565, -4.7224274, -4.264637], + [-2.224406, -2.5318158, -1.3832569, 1.1891162], + [-2.320062, -0.44705987, 4.289819, -0.00662684], + ], + [ + [0.99470854, -0.6992364, 0.25503993, 4.2952085], + [3.5937333, -3.2408535, -4.298278, 4.426601], + [0.7669008, 2.6588762, 2.4505413, 4.6051874], + [0.23330331, -3.0845237, 0.6262374, -2.9865491], + [0.7595146, -2.1099675, -4.155346, -2.8326452], + [2.3771453, 1.004138, -3.1781673, 0.7581556], + ], + ] + ) + + loss = router_z_loss_func(logits) + self.assertAlmostEqual(loss.item(), 13.786719, places=5) + + def test_equivalency_token_chose_masked_router(self): + r""" + This test tests the equivalency between the `SwitchTransformersTop1Router` + originally implemented from here: TODO: provide link + """ + + input_tokens = torch.Tensor( + [ + [ + [0.6433916, 0.18188512, 0.02240455, 0.563781], + [0.5526401, 0.0958724, 0.34253013, 0.03644359], + [0.08744538, 0.7909105, 0.35205448, 0.53364205], + ], + [ + [0.02900076, 0.4168595, 0.5802449, 0.91486526], + [0.27414513, 0.14991808, 0.9383501, 0.5209162], + [0.51207185, 0.90618336, 0.7309413, 0.95533276], + ], + ] + ) + + model = SwitchTransformersTop1Router(self.config) + + model.classifier.weight = torch.nn.Parameter( + torch.Tensor( + [ + [0.02008116, 0.00620062], + [-0.00811031, -0.00031623], + [-0.03542127, 0.02703803], + [0.02335377, -0.02971946], + ], + ).t() + ) + + expert_index, _, router_logits = model(input_tokens) + router_probs = torch.softmax(router_logits, dim=-1) + + router_z_loss = router_z_loss_func(router_logits) + auxiliary_loss = load_balancing_loss_func(router_probs, torch.argmax(expert_index, dim=-1)) + + self.assertAlmostEqual(auxiliary_loss.item(), 1.000308, places=5) + self.assertAlmostEqual(router_z_loss.item(), 0.4789799, places=5) + + # self.assertTrue(torch.allclose(expert_index.bool().unsqueeze(-1), expected_dispatch_mask)) + + def test_max_routing_capacity(self): + model = SwitchTransformersTop1Router(self.config) + seq_len = 128 + batch_size = 4 + hidden_states = torch.stack(batch_size * [torch.rand((seq_len, self.config.hidden_size))]) + + router_probs, router_logits = model._compute_router_probabilities(hidden_states) + expert_index = torch.argmax(router_probs, dim=-1) + expert_index = torch.nn.functional.one_hot(expert_index, num_classes=self.config.num_experts) + + token_priority = torch.cumsum(expert_index, dim=-2) + expert_capacity_mask = token_priority <= self.config.expert_capacity + expert_index = expert_index * expert_capacity_mask + + assert torch.sum(expert_index) <= batch_size * self.config.num_experts * self.config.expert_capacity + + +@slow +@require_torch +@require_tokenizers +class SwitchTransformerModelIntegrationTests(unittest.TestCase): + @require_torch_accelerator + @require_torch_bf16 + def test_small_logits(self): + r""" + Logits testing to check implementation consistency between `t5x` implementation + and `transformers` implementation of Switch-C transformers. We only check the logits + of the first batch. + """ + model = SwitchTransformersModel.from_pretrained("google/switch-base-8", torch_dtype=torch.bfloat16).to( + torch_device + ) + input_ids = torch.ones((32, 64), dtype=torch.long).to(torch_device) + decoder_input_ids = torch.ones((32, 64), dtype=torch.long).to(torch_device) + + # fmt: off + EXPECTED_MEAN_LOGITS = torch.Tensor( + [ + -0.204102, -0.193359, 0.523438, -0.296875, 0.108887, + 0.0211182, 0.605469, -0.100586, -0.0551758, 0.296875, + 0.0090332, 0.174805, 0.139648, -0.170898, -0.0981445, + 0.0245361, 0.0373535, 0.050293, -0.212891, 0.129883, + 0.390625, -0.203125, -0.122559, -0.180664, 0.0437012, + -0.349609, -0.0250244, -0.104004, -0.15918, -0.133789 + ] + ).to(torch.bfloat16) + # fmt: on + hf_logits = model(input_ids, decoder_input_ids=decoder_input_ids).last_hidden_state.cpu() + hf_logits = hf_logits[0, 0, :30] + + torch.testing.assert_allclose(hf_logits, EXPECTED_MEAN_LOGITS, rtol=6e-3, atol=9e-3) + + @unittest.skip( + "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" + ) + def test_small_generate(self): + # Generate test using the smalled switch-C model. + + model = SwitchTransformersForConditionalGeneration.from_pretrained( + "google/switch-base-8", torch_dtype=torch.bfloat16 + ).eval() + tokenizer = AutoTokenizer.from_pretrained("t5-small", use_fast=False, legacy=False) + model = model.to(torch_device) + + input_ids = tokenizer( + "The human walks into a bar and orders a ", return_tensors="pt" + ).input_ids.to(torch_device) + sequences = model.generate(input_ids) + output_str = tokenizer.batch_decode(sequences, skip_special_tokens=True)[0] + self.assertEqual(output_str, "drink.") + + input_ids = tokenizer( + "A walks into a bar and orders a with pinch of .", + return_tensors="pt", + ).input_ids.to(torch_device) + sequences = model.generate(input_ids) + output_str = tokenizer.batch_decode(sequences, skip_special_tokens=False)[0] + + EXPECTED_OUTPUT = " man beer a whiskey." + self.assertEqual(output_str, EXPECTED_OUTPUT) + + @unittest.skip( + "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" + ) + def test_small_batch_generate(self): + BATCH_SIZE = 4 + model = SwitchTransformersForConditionalGeneration.from_pretrained( + "google/switch-base-8", torch_dtype=torch.bfloat16 + ).eval() + tokenizer = AutoTokenizer.from_pretrained("t5-small", use_fast=False, legacy=False) + + inputs = [ + "A walks into a bar and orders a with pinch of ." + ] * BATCH_SIZE + encoded_input = tokenizer.batch_encode_plus(inputs, return_tensors="pt") + + sequences = model.generate(**encoded_input) + batch_output = tokenizer.batch_decode(sequences, skip_special_tokens=False) + + for i in range(0, BATCH_SIZE, 2): + self.assertEqual(batch_output[i], batch_output[i + 1]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_flax_t5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_flax_t5.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d729dac9aff84cd0d6575983002c75c7bef550 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_flax_t5.py @@ -0,0 +1,1111 @@ +# coding=utf-8 +# Copyright 2021 Google T5 Authors and HuggingFace Inc. team. +# +# 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 tempfile +import unittest + +import numpy as np + +import transformers +from transformers import is_flax_available +from transformers.testing_utils import ( + is_pt_flax_cross_test, + require_flax, + require_sentencepiece, + require_tokenizers, + slow, +) + +from ...generation.test_flax_utils import FlaxGenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor + + +if is_flax_available(): + import os + + # The slow tests are often failing with OOM error on GPU + # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed + # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html + os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform" + + import jax + import jax.numpy as jnp + import optax + from flax.core.frozen_dict import unfreeze + from flax.training.common_utils import onehot + from flax.traverse_util import flatten_dict + + from transformers import FLAX_MODEL_MAPPING, ByT5Tokenizer, T5Config, T5Tokenizer + from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model + from transformers.models.t5.modeling_flax_t5 import ( + FlaxT5EncoderModel, + FlaxT5ForConditionalGeneration, + FlaxT5Model, + shift_tokens_right, + ) + + +class FlaxT5ModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + decoder_seq_length=9, + # For common tests + is_training=True, + use_attention_mask=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + dropout_rate=0.1, + initializer_factor=0.002, + eos_token_id=1, + pad_token_id=0, + decoder_start_token_id=0, + scope=None, + decoder_layers=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.scope = None + self.decoder_layers = decoder_layers + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + attention_mask = None + decoder_attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2) + + config = T5Config( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ) + + return ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + ) + + def create_and_check_model( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + ): + model = FlaxT5Model(config=config) + result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) + decoder_output = result.last_hidden_state + encoder_output = result.encoder_last_hidden_state + + self.parent.assertEqual(encoder_output.shape, (self.batch_size, self.encoder_seq_length, self.hidden_size)) + self.parent.assertEqual(decoder_output.shape, (self.batch_size, self.decoder_seq_length, self.hidden_size)) + + def check_use_cache_forward_with_attn_mask( + self, + model_class_name, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + ): + max_decoder_length = 20 + model = model_class_name(config) + + encoder_outputs = model.encode(input_ids) + + # prevent fully zero'd out attention mask + decoder_attention_mask = jnp.ones_like(decoder_attention_mask) + + decoder_attention_mask_cache = jnp.concatenate( + [ + decoder_attention_mask, + jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])), + ], + axis=-1, + ) + + past_key_values = model.init_cache(decoder_input_ids.shape[0], max_decoder_length, encoder_outputs) + + outputs_cache = model.decode( + decoder_input_ids[:, :-1], + encoder_outputs, + decoder_attention_mask=decoder_attention_mask_cache, + past_key_values=past_key_values, + ) + outputs_cache_next = model.decode( + decoder_input_ids[:, -1:], + encoder_outputs, + past_key_values=outputs_cache.past_key_values, + decoder_attention_mask=decoder_attention_mask_cache, + ) + + outputs = model.decode(decoder_input_ids, encoder_outputs, decoder_attention_mask=decoder_attention_mask) + + diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) + self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}") + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + return config, inputs_dict + + +@require_flax +class FlaxT5ModelTest(FlaxModelTesterMixin, FlaxGenerationTesterMixin, unittest.TestCase): + all_model_classes = (FlaxT5Model, FlaxT5ForConditionalGeneration) if is_flax_available() else () + all_generative_model_classes = (FlaxT5ForConditionalGeneration,) if is_flax_available() else () + is_encoder_decoder = True + + def setUp(self): + self.model_tester = FlaxT5ModelTester(self) + self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_v1_1(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + # check that gated gelu feed forward and different word embeddings work + config = config_and_inputs[0] + config.tie_word_embeddings = False + config.feed_forward_proj = "gated-gelu" + self.model_tester.create_and_check_model(config, *config_and_inputs[1:]) + + def test_use_cache_forward_with_attn_mask(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + self.model_tester.check_use_cache_forward_with_attn_mask(model_class, *config_and_inputs) + + def test_encode(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def encode_jitted(input_ids, attention_mask=None, **kwargs): + return model.encode(input_ids=input_ids, attention_mask=attention_mask) + + with self.subTest("JIT Enabled"): + jitted_outputs = encode_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = encode_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + def test_decode(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + model = model_class(config) + encoder_outputs = model.encode(inputs_dict["input_ids"], inputs_dict["attention_mask"]) + + prepared_inputs_dict = { + "decoder_input_ids": inputs_dict["decoder_input_ids"], + "decoder_attention_mask": inputs_dict["decoder_attention_mask"], + "encoder_outputs": encoder_outputs, + } + + @jax.jit + def decode_jitted(decoder_input_ids, decoder_attention_mask, encoder_outputs): + return model.decode( + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + encoder_outputs=encoder_outputs, + ) + + with self.subTest("JIT Enabled"): + jitted_outputs = decode_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = decode_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + def test_shift_right(self): + decoder_start_token_id = 0 + pad_token_id = 1 + labels = np.arange(2, 102).reshape(5, 20) + labels[:2, 15:] = -100 + + decoder_input_ids = shift_tokens_right(labels, pad_token_id, decoder_start_token_id) + np_decoder_input_ids = np.array(decoder_input_ids) + + padded_slice = np_decoder_input_ids[:2, (15 + 1) :] + self.assertTrue((padded_slice == 1).all()) + + not_padded_slice = np_decoder_input_ids[2:, 1:] + rolled_labels = np.roll(labels[2:], 1)[:, 1:] + self.assertTrue((not_padded_slice == rolled_labels).all()) + self.assertTrue((np_decoder_input_ids[:, 0] == 0).all()) + + # overwrite since special base model prefix is used + def test_save_load_from_base(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = base_class(config) + base_params = flatten_dict(unfreeze(model.params)) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + head_model = model_class.from_pretrained(tmpdirname) + + base_param_from_head = flatten_dict(unfreeze(head_model.params)) + + for key in base_param_from_head.keys(): + max_diff = (base_params[key] - base_param_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite since special base model prefix is used + def test_save_load_to_base(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + base_params_from_head = flatten_dict(unfreeze(model.params)) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite since special base model prefix is used + @is_pt_flax_cross_test + def test_save_load_from_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = base_class(config) + base_params = flatten_dict(unfreeze(model.params)) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, base_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + # save pt model + pt_model.save_pretrained(tmpdirname) + head_model = model_class.from_pretrained(tmpdirname, from_pt=True) + + base_param_from_head = flatten_dict(unfreeze(head_model.params)) + + for key in base_param_from_head.keys(): + max_diff = (base_params[key] - base_param_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite since special base model prefix is used + @is_pt_flax_cross_test + def test_save_load_to_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + base_params_from_head = flatten_dict(unfreeze(model.params)) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname, from_pt=True) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite since special base model prefix is used + @is_pt_flax_cross_test + def test_save_load_bf16_to_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + model.params = model.to_bf16(model.params) + base_params_from_head = flatten_dict(unfreeze(model.params)) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname, from_pt=True) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + +class FlaxT5EncoderOnlyModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + # For common tests + is_training=True, + use_attention_mask=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + dropout_rate=0.1, + initializer_factor=0.002, + eos_token_id=1, + pad_token_id=0, + decoder_start_token_id=0, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + # For common tests + self.seq_length = self.encoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.scope = None + self.decoder_layers = 0 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + + config = T5Config( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + is_encoder_decoder=False, + ) + + return ( + config, + input_ids, + attention_mask, + ) + + def create_and_check_model( + self, + config, + input_ids, + attention_mask, + ): + model = FlaxT5EncoderModel(config=config) + result = model( + input_ids=input_ids, + attention_mask=attention_mask, + ) + result = model(input_ids=input_ids) + encoder_output = result.last_hidden_state + + self.parent.assertEqual(encoder_output.shape, (self.batch_size, self.encoder_seq_length, self.hidden_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + attention_mask, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + +@require_flax +class FlaxT5EncoderOnlyModelTest(FlaxModelTesterMixin, unittest.TestCase): + all_model_classes = (FlaxT5EncoderModel,) if is_flax_available() else () + is_encoder_decoder = False + + def setUp(self): + self.model_tester = FlaxT5EncoderOnlyModelTester(self) + self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_v1_1(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + # check that gated gelu feed forward and different word embeddings work + config = config_and_inputs[0] + config.tie_word_embeddings = False + config.feed_forward_proj = "gated-gelu" + self.model_tester.create_and_check_model(config, *config_and_inputs[1:]) + + def test_encode(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def encode_jitted(input_ids, attention_mask=None, **kwargs): + return model(input_ids=input_ids, attention_mask=attention_mask) + + with self.subTest("JIT Enabled"): + jitted_outputs = encode_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = encode_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + # overwrite since special base model prefix is used + def test_save_load_from_base(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = base_class(config) + base_params = flatten_dict(unfreeze(model.params)) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + head_model = model_class.from_pretrained(tmpdirname) + + base_param_from_head = flatten_dict(unfreeze(head_model.params)) + + for key in base_param_from_head.keys(): + max_diff = (base_params[key] - base_param_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite since special base model prefix is used + def test_save_load_to_base(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + base_params_from_head = flatten_dict(unfreeze(model.params)) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite since special base model prefix is used + @is_pt_flax_cross_test + def test_save_load_from_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = base_class(config) + base_params = flatten_dict(unfreeze(model.params)) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, base_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + # save pt model + pt_model.save_pretrained(tmpdirname) + head_model = model_class.from_pretrained(tmpdirname, from_pt=True) + + base_param_from_head = flatten_dict(unfreeze(head_model.params)) + + for key in base_param_from_head.keys(): + max_diff = (base_params[key] - base_param_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite since special base model prefix is used + @is_pt_flax_cross_test + def test_save_load_to_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + base_params_from_head = flatten_dict(unfreeze(model.params)) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname, from_pt=True) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite since special base model prefix is used + @is_pt_flax_cross_test + def test_save_load_bf16_to_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + model.params = model.to_bf16(model.params) + base_params_from_head = flatten_dict(unfreeze(model.params)) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname, from_pt=True) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + +@require_sentencepiece +@require_tokenizers +@require_flax +class FlaxT5ModelIntegrationTests(unittest.TestCase): + @slow + def test_small_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.7.1 + >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary + + >>> path_to_mtf_small_t5_checkpoint = '' + >>> path_to_mtf_small_spm_model_path = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_mtf_small_t5_checkpoint, batch_size=1, tpu=None) + >>> vocab = SentencePieceVocabulary(path_to_mtf_small_spm_model_path, extra_ids=100) + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = FlaxT5ForConditionalGeneration.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + input_ids = tokenizer("Hello there", return_tensors="np").input_ids + labels = tokenizer("Hi I am", return_tensors="np").input_ids + + decoder_input_ids = shift_tokens_right(labels, model.config.pad_token_id, model.config.decoder_start_token_id) + + logits = model(input_ids, decoder_input_ids=decoder_input_ids).logits + + loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean() + mtf_score = -(labels.shape[-1] * loss.item()) + + EXPECTED_SCORE = -19.0845 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_small_v1_1_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.7.1 + >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary + + >>> path_to_mtf_small_t5_v1_1_checkpoint = '' + >>> path_to_mtf_small_spm_model_path = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_mtf_small_t5_v1_1_checkpoint, batch_size=1, tpu=None) + >>> vocab = SentencePieceVocabulary(path_to_mtf_small_spm_model_path, extra_ids=100) + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = FlaxT5ForConditionalGeneration.from_pretrained("google/t5-v1_1-small") + tokenizer = T5Tokenizer.from_pretrained("google/t5-v1_1-small") + + input_ids = tokenizer("Hello there", return_tensors="np").input_ids + labels = tokenizer("Hi I am", return_tensors="np").input_ids + + decoder_input_ids = shift_tokens_right(labels, model.config.pad_token_id, model.config.decoder_start_token_id) + + logits = model(input_ids, decoder_input_ids=decoder_input_ids).logits + loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean() + + mtf_score = -(labels.shape[-1] * loss.item()) + + EXPECTED_SCORE = -59.0293 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_small_byt5_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.9.1 + + >>> path_to_byt5_small_checkpoint = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_tf_checkpoint, batch_size=1, tpu=None) + >>> vocab = t5.data.ByteVocabulary() + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = FlaxT5ForConditionalGeneration.from_pretrained("google/byt5-small") + tokenizer = ByT5Tokenizer.from_pretrained("google/byt5-small") + + input_ids = tokenizer("Hello there", return_tensors="np").input_ids + labels = tokenizer("Hi I am", return_tensors="np").input_ids + + decoder_input_ids = shift_tokens_right(labels, model.config.pad_token_id, model.config.decoder_start_token_id) + + logits = model(input_ids, decoder_input_ids=decoder_input_ids).logits + loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean() + + mtf_score = -(labels.shape[-1] * loss.item()) + + EXPECTED_SCORE = -60.7397 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_small_generation(self): + model = FlaxT5ForConditionalGeneration.from_pretrained("t5-small") + model.config.max_length = 8 + model.config.num_beams = 1 + model.config.do_sample = False + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + input_ids = tokenizer("summarize: Hello there", return_tensors="np").input_ids + + sequences = model.generate(input_ids).sequences + + output_str = tokenizer.batch_decode(sequences, skip_special_tokens=True)[0] + self.assertTrue(output_str == "Hello there!") + + @slow + def test_small_generation_bfloat16(self): + model = FlaxT5ForConditionalGeneration.from_pretrained("t5-small", dtype=jnp.bfloat16) + model.config.max_length = 8 + model.config.num_beams = 1 + model.config.do_sample = False + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + input_ids = tokenizer("summarize: Hello there", return_tensors="np").input_ids + + sequences = model.generate(input_ids).sequences + + output_str = tokenizer.batch_decode(sequences, skip_special_tokens=True)[0] + self.assertTrue(output_str == "Hello there!") + + @slow + def test_summarization(self): + model = FlaxT5ForConditionalGeneration.from_pretrained("t5-base") + tok = T5Tokenizer.from_pretrained("t5-base") + + FRANCE_ARTICLE = ( # @noqa + "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." + ) + 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." + ) + + expected_summaries = [ + 'prosecutor: "so far no videos were used in the crash investigation" two magazines claim to have found a' + " cell phone video of the final seconds . \"one can hear cries of 'My God' in several languages,\" one" + " magazine says . all 150 on board were killed in the crash .", + "the formal accession was marked by a ceremony at The Hague, in the Netherlands . the ICC opened a" + " preliminary examination into the situation in the occupied Palestinian territory . as members of the" + " court, Palestinians may be subject to counter-charges as well .", + "the u.s. and its negotiating partners reached a very strong framework agreement with Iran . aaron miller:" + " the debate that has already begun since the announcement of the new framework will likely result in more" + " heat than light . he says the new framework would reduce Iran's low-enriched uranium stockpile and cut" + " centrifuges . miller: if it had been, there would have been no Iranian team at the table .", + "prosecutors say the marriages were part of an immigration scam . if convicted, barrientos faces two" + ' criminal counts of "offering a false instrument for filing in the first degree" she has been married 10' + " times, with nine of her marriages occurring between 1999 and 2002 .", + ] + + dct = tok( + ["summarize: " + x for x in [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY]], + padding="max_length", + truncation=True, + return_tensors="np", + ) + self.assertEqual(512, dct["input_ids"].shape[1]) + + hypotheses_batch = model.generate( + **dct, + num_beams=4, + length_penalty=2.0, + max_length=142, + min_length=56, + do_sample=False, + early_stopping=True, + ).sequences + + decoded = tok.batch_decode(hypotheses_batch, skip_special_tokens=True, clean_up_tokenization_spaces=False) + self.assertListEqual( + expected_summaries, + decoded, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_t5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_t5.py new file mode 100644 index 0000000000000000000000000000000000000000..68b9f45e155b5320bfd707f401c45eec34bd9cd2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_t5.py @@ -0,0 +1,1599 @@ +# coding=utf-8 +# Copyright 2018 Google T5 Authors and HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import copy +import os +import pickle +import tempfile +import unittest + +from transformers import T5Config, is_torch_available +from transformers.models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES +from transformers.testing_utils import ( + require_accelerate, + require_sentencepiece, + require_tokenizers, + require_torch, + slow, + torch_device, +) +from transformers.utils import cached_property, is_torch_fx_available + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_fx_available(): + from transformers.utils.fx import symbolic_trace + + +if is_torch_available(): + import torch + + from transformers import ( + AutoTokenizer, + ByT5Tokenizer, + T5EncoderModel, + T5ForConditionalGeneration, + T5ForQuestionAnswering, + T5ForSequenceClassification, + T5Model, + T5Tokenizer, + ) + from transformers.models.t5.modeling_t5 import T5_PRETRAINED_MODEL_ARCHIVE_LIST + + +class T5ModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + decoder_seq_length=7, + # For common tests + is_training=True, + use_attention_mask=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + dropout_rate=0.1, + initializer_factor=0.002, + eos_token_id=1, + pad_token_id=0, + decoder_start_token_id=0, + scope=None, + decoder_layers=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.scope = None + self.decoder_layers = decoder_layers + + def get_large_model_config(self): + return T5Config.from_pretrained("t5-base") + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size).clamp(2) + input_ids[:, -1] = self.eos_token_id # Eos Token + decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + attention_mask = None + decoder_attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2) + + lm_labels = None + if self.use_labels: + lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + config = self.get_config() + + return ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) + + def get_pipeline_config(self): + return T5Config( + vocab_size=166, # t5 forces 100 extra tokens + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ) + + def get_config(self): + return T5Config( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ) + + def check_prepare_lm_labels_via_shift_left( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = T5Model(config=config) + model.to(torch_device) + model.eval() + + # make sure that lm_labels are correctly padded from the right + lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id) + + # add casaul pad token mask + triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not() + lm_labels.masked_fill_(triangular_mask, self.pad_token_id) + decoder_input_ids = model._shift_right(lm_labels) + + for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)): + # first item + self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id) + if i < decoder_input_ids_slice.shape[-1]: + if i < decoder_input_ids.shape[-1] - 1: + # items before diagonal + self.parent.assertListEqual( + decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist() + ) + # pad items after diagonal + if i < decoder_input_ids.shape[-1] - 2: + self.parent.assertListEqual( + decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist() + ) + else: + # all items after square + self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist()) + + def create_and_check_model( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = T5Model(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) + decoder_output = result.last_hidden_state + decoder_past = result.past_key_values + encoder_output = result.encoder_last_hidden_state + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size)) + self.parent.assertEqual(decoder_output.size(), (self.batch_size, self.decoder_seq_length, self.hidden_size)) + # There should be `num_layers` key value embeddings stored in decoder_past + self.parent.assertEqual(len(decoder_past), config.num_layers) + # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple + self.parent.assertEqual(len(decoder_past[0]), 4) + + def create_and_check_with_lm_head( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = T5ForConditionalGeneration(config=config).to(torch_device).eval() + outputs = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + labels=lm_labels, + ) + self.parent.assertEqual(len(outputs), 4) + self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size)) + self.parent.assertEqual(outputs["loss"].size(), ()) + + def create_and_check_with_sequence_classification_head( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + labels = torch.tensor([1] * self.batch_size, dtype=torch.long, device=torch_device) + model = T5ForSequenceClassification(config=config).to(torch_device).eval() + outputs = model( + input_ids=input_ids, + decoder_input_ids=input_ids, + labels=labels, + ) + # self.parent.assertEqual(len(outputs), 4) + self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, config.num_labels)) + self.parent.assertEqual(outputs["loss"].size(), ()) + + def create_and_check_decoder_model_past( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = T5Model(config=config).get_decoder().to(torch_device).eval() + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_decoder_model_attention_mask_past( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = T5Model(config=config).get_decoder() + model.to(torch_device) + model.eval() + + # create attention mask + attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) + + half_seq_length = input_ids.shape[-1] // 2 + attn_mask[:, half_seq_length:] = 0 + + # first forward pass + output, past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True).to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1) + input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens + + # append to next input_ids and attn_mask + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + attn_mask = torch.cat( + [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)], + dim=1, + ) + + # get two different outputs + output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values, attention_mask=attn_mask)[ + "last_hidden_state" + ] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = T5Model(config=config).get_decoder().to(torch_device).eval() + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([attention_mask, next_mask], dim=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # 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)) + + def create_and_check_generate_with_past_key_values( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = T5ForConditionalGeneration(config=config).to(torch_device).eval() + torch.manual_seed(0) + output_without_past_cache = model.generate( + input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False + ) + torch.manual_seed(0) + output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True) + self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache)) + + def create_and_check_model_fp16_forward( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = T5Model(config=config).to(torch_device).half().eval() + output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)["last_hidden_state"] + self.parent.assertFalse(torch.isnan(output).any().item()) + + def create_and_check_encoder_decoder_shared_weights( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + for model_class in [T5Model, T5ForConditionalGeneration]: + torch.manual_seed(0) + model = model_class(config=config).to(torch_device).eval() + # load state dict copies weights but does not tie them + model.encoder.load_state_dict(model.decoder.state_dict(), strict=False) + + torch.manual_seed(0) + tied_config = copy.deepcopy(config) + tied_config.tie_encoder_decoder = True + tied_model = model_class(config=tied_config).to(torch_device).eval() + + model_result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + tied_model_result = tied_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + # check that models has less parameters + self.parent.assertLess( + sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters()) + ) + random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item() + + # check that outputs are equal + self.parent.assertTrue( + torch.allclose( + model_result[0][0, :, random_slice_idx], tied_model_result[0][0, :, random_slice_idx], atol=1e-4 + ) + ) + + # check that outputs after saving and loading are equal + with tempfile.TemporaryDirectory() as tmpdirname: + tied_model.save_pretrained(tmpdirname) + tied_model = model_class.from_pretrained(tmpdirname) + tied_model.to(torch_device) + tied_model.eval() + + # check that models has less parameters + self.parent.assertLess( + sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters()) + ) + random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item() + + tied_model_result = tied_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + + # check that outputs are equal + self.parent.assertTrue( + torch.allclose( + model_result[0][0, :, random_slice_idx], + tied_model_result[0][0, :, random_slice_idx], + atol=1e-4, + ) + ) + + def check_resize_embeddings_t5_v1_1( + self, + config, + ): + prev_vocab_size = config.vocab_size + + config.tie_word_embeddings = False + model = T5ForConditionalGeneration(config=config).to(torch_device).eval() + model.resize_token_embeddings(prev_vocab_size - 10) + + self.parent.assertEqual(model.get_input_embeddings().weight.shape[0], prev_vocab_size - 10) + self.parent.assertEqual(model.get_output_embeddings().weight.shape[0], prev_vocab_size - 10) + self.parent.assertEqual(model.config.vocab_size, prev_vocab_size - 10) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "use_cache": False, + } + return config, inputs_dict + + +@require_torch +class T5ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (T5Model, T5ForConditionalGeneration, T5ForSequenceClassification, T5ForQuestionAnswering) + if is_torch_available() + else () + ) + all_generative_model_classes = (T5ForConditionalGeneration,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "conversational": T5ForConditionalGeneration, + "feature-extraction": T5Model, + "question-answering": T5ForQuestionAnswering, + "summarization": T5ForConditionalGeneration, + "text-classification": T5ForSequenceClassification, + "text2text-generation": T5ForConditionalGeneration, + "translation": T5ForConditionalGeneration, + "zero-shot": T5ForSequenceClassification, + } + if is_torch_available() + else {} + ) + all_parallelizable_model_classes = (T5Model, T5ForConditionalGeneration) if is_torch_available() else () + fx_compatible = True + test_pruning = False + test_resize_embeddings = True + test_model_parallel = True + is_encoder_decoder = True + # The small T5 model needs higher percentages for CPU/MP tests + model_split_percents = [0.8, 0.9] + + def setUp(self): + self.model_tester = T5ModelTester(self) + self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37) + + # `QAPipelineTests` is not working well with slow tokenizers (for some models) and we don't want to touch the file + # `src/transformers/data/processors/squad.py` (where this test fails for this model) + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): + return True + + return False + + def _create_and_check_torch_fx_tracing(self, config, inputs_dict, output_loss=False): + if not is_torch_fx_available() or not self.fx_compatible: + return + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.return_dict = False + + for model_class in self.all_model_classes: + if model_class.__name__ == "T5ForSequenceClassification": + continue + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=output_loss) + + try: + if model.config.is_encoder_decoder: + model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward + labels = inputs.get("labels", None) + input_names = [ + "attention_mask", + "decoder_attention_mask", + "decoder_input_ids", + "input_features", + "input_ids", + "input_values", + ] + if labels is not None: + input_names.append("labels") + + filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names} + input_names = list(filtered_inputs.keys()) + + model_output = model(**filtered_inputs) + + traced_model = symbolic_trace(model, input_names) + traced_output = traced_model(**filtered_inputs) + else: + input_names = [ + "attention_mask", + "bbox", + "input_features", + "input_ids", + "input_values", + "pixel_values", + "token_type_ids", + "visual_feats", + "visual_pos", + ] + + labels = inputs.get("labels", None) + start_positions = inputs.get("start_positions", None) + end_positions = inputs.get("end_positions", None) + if labels is not None: + input_names.append("labels") + if start_positions is not None: + input_names.append("start_positions") + if end_positions is not None: + input_names.append("end_positions") + + filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names} + input_names = list(filtered_inputs.keys()) + + if model.__class__.__name__ in set(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values()) and ( + not hasattr(model.config, "problem_type") or model.config.problem_type is None + ): + model.config.problem_type = "single_label_classification" + + traced_model = symbolic_trace(model, input_names) + traced_output = traced_model(**filtered_inputs) + model_output = model(**filtered_inputs) + + except Exception as e: + self.fail(f"Couldn't trace module: {e}") + + def flatten_output(output): + flatten = [] + for x in output: + if isinstance(x, (tuple, list)): + flatten += flatten_output(x) + elif not isinstance(x, torch.Tensor): + continue + else: + flatten.append(x) + return flatten + + model_output = flatten_output(model_output) + traced_output = flatten_output(traced_output) + num_outputs = len(model_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], traced_output[i]), + f"traced {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Test that the model can be serialized and restored properly + with tempfile.TemporaryDirectory() as tmp_dir_name: + pkl_file_name = os.path.join(tmp_dir_name, "model.pkl") + try: + with open(pkl_file_name, "wb") as f: + pickle.dump(traced_model, f) + with open(pkl_file_name, "rb") as f: + loaded = pickle.load(f) + except Exception as e: + self.fail(f"Couldn't serialize / deserialize the traced model: {e}") + + loaded_output = loaded(**filtered_inputs) + loaded_output = flatten_output(loaded_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], loaded_output[i]), + f"serialized model {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Avoid memory leak. Without this, each call increase RAM usage by ~20MB. + # (Even with this call, there are still memory leak by ~0.04MB) + self.clear_torch_jit_class_registry() + + def test_config(self): + self.config_tester.run_common_tests() + + def test_shift_right(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_v1_1(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + # check that gated gelu feed forward and different word embeddings work + config = config_and_inputs[0] + config.tie_word_embeddings = False + config.feed_forward_proj = "gated-gelu" + self.model_tester.create_and_check_model(config, *config_and_inputs[1:]) + + # T5ForSequenceClassification does not support inputs_embeds + def test_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in (T5Model, T5ForConditionalGeneration, T5ForQuestionAnswering): + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + del inputs["input_ids"] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + + wte = model.get_input_embeddings() + if not self.is_encoder_decoder: + inputs["inputs_embeds"] = wte(input_ids) + else: + inputs["inputs_embeds"] = wte(encoder_input_ids) + inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) + + with torch.no_grad(): + model(**inputs)[0] + + def test_config_and_model_silu_gated(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config = config_and_inputs[0] + config.feed_forward_proj = "gated-silu" + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_with_lm_head(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_with_lm_head(*config_and_inputs) + + def test_with_sequence_classification_head(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_with_sequence_classification_head(*config_and_inputs) + + def test_decoder_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_past(*config_and_inputs) + + def test_decoder_model_past_with_attn_mask(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs) + + def test_decoder_model_past_with_3d_attn_mask(self): + ( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = self.model_tester.prepare_config_and_inputs() + + attention_mask = ids_tensor( + [self.model_tester.batch_size, self.model_tester.encoder_seq_length, self.model_tester.encoder_seq_length], + vocab_size=2, + ) + decoder_attention_mask = ids_tensor( + [self.model_tester.batch_size, self.model_tester.decoder_seq_length, self.model_tester.decoder_seq_length], + vocab_size=2, + ) + + self.model_tester.create_and_check_decoder_model_attention_mask_past( + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) + + 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_generate_with_past_key_values(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_generate_with_past_key_values(*config_and_inputs) + + def test_encoder_decoder_shared_weights(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs) + + @unittest.skipIf(torch_device == "cpu", "Cant do half precision") + def test_model_fp16_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs) + + def test_v1_1_resize_embeddings(self): + config = self.model_tester.prepare_config_and_inputs()[0] + self.model_tester.check_resize_embeddings_t5_v1_1(config) + + @slow + def test_model_from_pretrained(self): + for model_name in T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = T5Model.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip("Test has a segmentation fault on torch 1.8.0") + def test_export_to_onnx(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + model = T5Model(config_and_inputs[0]).to(torch_device) + with tempfile.TemporaryDirectory() as tmpdirname: + torch.onnx.export( + model, + (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]), + f"{tmpdirname}/t5_test.onnx", + export_params=True, + opset_version=9, + input_names=["input_ids", "decoder_input_ids"], + ) + + def test_generate_with_head_masking(self): + attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"] + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config = config_and_inputs[0] + max_length = config_and_inputs[1].shape[-1] + 3 + model = T5ForConditionalGeneration(config).eval() + model.to(torch_device) + + head_masking = { + "head_mask": torch.zeros(config.num_layers, config.num_heads, device=torch_device), + "decoder_head_mask": torch.zeros(config.num_decoder_layers, config.num_heads, device=torch_device), + "cross_attn_head_mask": torch.zeros(config.num_decoder_layers, config.num_heads, device=torch_device), + } + + for attn_name, (name, mask) in zip(attention_names, head_masking.items()): + head_masks = {name: mask} + # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified + if name == "head_mask": + head_masks["decoder_head_mask"] = torch.ones( + config.num_decoder_layers, config.num_heads, device=torch_device + ) + + out = model.generate( + config_and_inputs[1], + num_beams=1, + max_length=max_length, + output_attentions=True, + return_dict_in_generate=True, + **head_masks, + ) + # We check the state of decoder_attentions and cross_attentions just from the last step + attn_weights = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] + self.assertEqual(sum([w.sum().item() for w in attn_weights]), 0.0) + + @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.") + def test_disk_offload(self): + pass + + @unittest.skip("Does not support conversations.") + def test_pipeline_conversational(self): + pass + + +class T5EncoderOnlyModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + # For common tests + use_attention_mask=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + is_training=False, + dropout_rate=0.1, + initializer_factor=0.002, + is_encoder_decoder=False, + eos_token_id=1, + pad_token_id=0, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + # For common tests + self.seq_length = self.encoder_seq_length + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.is_encoder_decoder = is_encoder_decoder + self.scope = None + self.is_training = is_training + + def get_large_model_config(self): + return T5Config.from_pretrained("t5-base") + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + + config = T5Config( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + return ( + config, + input_ids, + attention_mask, + ) + + def create_and_check_model( + self, + config, + input_ids, + attention_mask, + ): + model = T5EncoderModel(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + attention_mask=attention_mask, + ) + result = model(input_ids=input_ids) + encoder_output = result.last_hidden_state + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size)) + + def create_and_check_model_fp16_forward( + self, + config, + input_ids, + attention_mask, + ): + model = T5EncoderModel(config=config).to(torch_device).half().eval() + output = model(input_ids, attention_mask=attention_mask)["last_hidden_state"] + self.parent.assertFalse(torch.isnan(output).any().item()) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + attention_mask, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + +class T5EncoderOnlyModelTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (T5EncoderModel,) if is_torch_available() else () + test_pruning = False + test_resize_embeddings = False + test_model_parallel = True + all_parallelizable_model_classes = (T5EncoderModel,) if is_torch_available() else () + + def setUp(self): + self.model_tester = T5EncoderOnlyModelTester(self) + self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @unittest.skipIf(torch_device == "cpu", "Cant do half precision") + def test_model_fp16_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs) + + +def use_task_specific_params(model, task): + model.config.update(model.config.task_specific_params[task]) + + +@require_torch +@require_accelerate +@require_tokenizers +@slow +class T5ModelFp16Tests(unittest.TestCase): + def test_fp16_fp32_conversion(self): + r""" + A test to check whether the argument `keep_in_fp32_modules` correctly does its job + """ + orig_import = __import__ + accelerate_mock = unittest.mock.Mock() + + # mock import of accelerate + def import_accelerate_mock(name, *args, **kwargs): + if name == "accelerate": + if accelerate_available: + return accelerate_mock + else: + raise ImportError + return orig_import(name, *args, **kwargs) + + # Load without using `accelerate` + with unittest.mock.patch("builtins.__import__", side_effect=import_accelerate_mock): + accelerate_available = False + + model = T5ForConditionalGeneration.from_pretrained("t5-small", torch_dtype=torch.float16) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16) + + # Load without in bf16 + model = T5ForConditionalGeneration.from_pretrained("t5-small", torch_dtype=torch.bfloat16) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16) + + # Load using `accelerate` in bf16 + model = T5ForConditionalGeneration.from_pretrained("t5-small", torch_dtype=torch.bfloat16, device_map="auto") + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16) + + # Load using `accelerate` in bf16 + model = T5ForConditionalGeneration.from_pretrained( + "t5-small", torch_dtype=torch.bfloat16, low_cpu_mem_usage=True + ) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16) + + # Load without using `accelerate` + model = T5ForConditionalGeneration.from_pretrained( + "t5-small", torch_dtype=torch.float16, low_cpu_mem_usage=True + ) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16) + + # Load using `accelerate` + model = T5ForConditionalGeneration.from_pretrained("t5-small", torch_dtype=torch.float16, device_map="auto") + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32) + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16) + + +@require_torch +@require_sentencepiece +@require_tokenizers +class T5ModelIntegrationTests(unittest.TestCase): + @cached_property + def model(self): + return T5ForConditionalGeneration.from_pretrained("t5-base").to(torch_device) + + @cached_property + def tokenizer(self): + return T5Tokenizer.from_pretrained("t5-base") + + @slow + def test_torch_quant(self): + r""" + Test that a simple `torch.quantization.quantize_dynamic` call works on a T5 model. + """ + model_name = "google/flan-t5-small" + tokenizer = T5Tokenizer.from_pretrained(model_name) + model = T5ForConditionalGeneration.from_pretrained(model_name) + model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8) + input_text = "Answer the following yes/no question by reasoning step-by-step. Can you write a whole Haiku in a single tweet?" + input_ids = tokenizer(input_text, return_tensors="pt").input_ids + _ = model.generate(input_ids) + + @slow + def test_small_generation(self): + model = T5ForConditionalGeneration.from_pretrained("t5-small").to(torch_device) + model.config.max_length = 8 + model.config.num_beams = 1 + model.config.do_sample = False + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + input_ids = tokenizer("summarize: Hello there", return_tensors="pt").input_ids.to(torch_device) + + sequences = model.generate(input_ids) + + output_str = tokenizer.batch_decode(sequences, skip_special_tokens=True)[0] + self.assertTrue(output_str == "Hello there!") + + @slow + def test_small_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.7.1 + >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary + + >>> path_to_mtf_small_t5_checkpoint = '' + >>> path_to_mtf_small_spm_model_path = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_mtf_small_t5_checkpoint, batch_size=1, tpu=None) + >>> vocab = SentencePieceVocabulary(path_to_mtf_small_spm_model_path, extra_ids=100) + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = T5ForConditionalGeneration.from_pretrained("t5-small").to(torch_device) + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + input_ids = tokenizer("Hello there", return_tensors="pt").input_ids + labels = tokenizer("Hi I am", return_tensors="pt").input_ids + + loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss + mtf_score = -(labels.shape[-1] * loss.item()) + + EXPECTED_SCORE = -19.0845 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_small_v1_1_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.7.1 + >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary + + >>> path_to_mtf_small_t5_v1_1_checkpoint = '' + >>> path_to_mtf_small_spm_model_path = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_mtf_small_t5_v1_1_checkpoint, batch_size=1, tpu=None) + >>> vocab = SentencePieceVocabulary(path_to_mtf_small_spm_model_path, extra_ids=100) + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = T5ForConditionalGeneration.from_pretrained("google/t5-v1_1-small").to(torch_device) + tokenizer = T5Tokenizer.from_pretrained("google/t5-v1_1-small") + + input_ids = tokenizer("Hello there", return_tensors="pt").input_ids + labels = tokenizer("Hi I am", return_tensors="pt").input_ids + + loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss + mtf_score = -(labels.shape[-1] * loss.item()) + + EXPECTED_SCORE = -59.0293 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_small_byt5_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.9.1 + + >>> path_to_byt5_small_checkpoint = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_tf_checkpoint, batch_size=1, tpu=None) + >>> vocab = t5.data.ByteVocabulary() + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = T5ForConditionalGeneration.from_pretrained("google/byt5-small").to(torch_device) + tokenizer = ByT5Tokenizer.from_pretrained("google/byt5-small") + + input_ids = tokenizer("Hello there", return_tensors="pt").input_ids + labels = tokenizer("Hi I am", return_tensors="pt").input_ids + + loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss + mtf_score = -(labels.shape[-1] * loss.item()) + + EXPECTED_SCORE = -60.7397 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_summarization(self): + model = self.model + tok = self.tokenizer + + FRANCE_ARTICLE = ( # @noqa + "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." + ) + 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." + ) + + expected_summaries = [ + 'prosecutor: "so far no videos were used in the crash investigation" two magazines claim to have found a' + " cell phone video of the final seconds . \"one can hear cries of 'My God' in several languages,\" one" + " magazine says .", + "the formal accession was marked by a ceremony at The Hague, in the Netherlands . the ICC opened a" + " preliminary examination into the situation in the occupied Palestinian territory . as members of the" + " court, Palestinians may be subject to counter-charges as well .", + "the u.s. and its negotiating partners reached a very strong framework agreement with Iran . aaron miller:" + " the debate that has already begun since the announcement of the new framework will likely result in more" + " heat than light . the deal would reduce Iran's low-enriched uranium stockpile, cut centrifuges and" + " implement a rigorous inspection regime .", + "prosecutors say the marriages were part of an immigration scam . if convicted, barrientos faces two" + ' criminal counts of "offering a false instrument for filing in the first degree" she has been married 10' + " times, with nine of her marriages occurring between 1999 and 2002 .", + ] + + use_task_specific_params(model, "summarization") + + dct = tok( + [model.config.prefix + x for x in [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY]], + padding="max_length", + truncation=True, + return_tensors="pt", + ).to(torch_device) + self.assertEqual(512, dct["input_ids"].shape[1]) + + hypotheses_batch = model.generate( + **dct, + num_beams=4, + length_penalty=2.0, + max_length=142, + min_length=56, + no_repeat_ngram_size=3, + do_sample=False, + early_stopping=True, + ) + + decoded = tok.batch_decode(hypotheses_batch, skip_special_tokens=True, clean_up_tokenization_spaces=False) + self.assertListEqual( + expected_summaries, + decoded, + ) + + @slow + def test_translation_en_to_de(self): + model = self.model + tok = self.tokenizer + use_task_specific_params(model, "translation_en_to_de") + + en_text = '"Luigi often said to me that he never wanted the brothers to end up in court", she wrote.' + expected_translation = ( + '"Luigi sagte mir oft, dass er nie wollte, dass die Brüder am Gericht sitzen", schrieb sie.' + ) + + input_ids = tok.encode(model.config.prefix + en_text, return_tensors="pt") + input_ids = input_ids.to(torch_device) + output = model.generate(input_ids) + translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False) + self.assertEqual(translation, expected_translation) + + @slow + def test_translation_en_to_fr(self): + model = self.model # t5-base + tok = self.tokenizer + use_task_specific_params(model, "translation_en_to_fr") + + en_text = ( + ' This image section from an infrared recording by the Spitzer telescope shows a "family portrait" of' + " countless generations of stars: the oldest stars are seen as blue dots. " + ) + + input_ids = tok.encode(model.config.prefix + en_text, return_tensors="pt") + input_ids = input_ids.to(torch_device) + + output = model.generate( + input_ids=input_ids, + num_beams=4, + length_penalty=2.0, + max_length=100, + no_repeat_ngram_size=3, + do_sample=False, + early_stopping=True, + ) + translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False) + new_truncated_translation = ( + "Cette section d'images provenant de l'enregistrement infrarouge effectué par le télescope Spitzer montre " + "un " + "« portrait familial » de générations innombrables d’étoiles : les plus anciennes sont observées " + "sous forme " + "de points bleus." + ) + + self.assertEqual(translation, new_truncated_translation) + + @slow + def test_translation_en_to_ro(self): + model = self.model + tok = self.tokenizer + use_task_specific_params(model, "translation_en_to_ro") + en_text = "Taco Bell said it plans to add 2,000 locations in the US by 2022." + expected_translation = "Taco Bell a declarat că intenţionează să adauge 2 000 de locaţii în SUA până în 2022." + + inputs = tok(model.config.prefix + en_text, return_tensors="pt").to(torch_device) + output = model.generate(**inputs) + translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False) + self.assertEqual(translation, expected_translation) + + @slow + def test_contrastive_search_t5(self): + article = ( + " 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." + ) + article = "summarize: " + article.strip() + t5_tokenizer = AutoTokenizer.from_pretrained("flax-community/t5-base-cnn-dm") + t5_model = T5ForConditionalGeneration.from_pretrained("flax-community/t5-base-cnn-dm").to(torch_device) + input_ids = t5_tokenizer( + article, add_special_tokens=False, truncation=True, max_length=512, return_tensors="pt" + ).input_ids.to(torch_device) + + outputs = t5_model.generate(input_ids, penalty_alpha=0.5, top_k=5, max_length=64) + generated_text = t5_tokenizer.batch_decode(outputs, skip_special_tokens=True) + + self.assertListEqual( + generated_text, + [ + "Liana Barrientos has been married 10 times, nine of them in the Bronx. Her husbands filed for " + "permanent residence after the marriages, prosecutors say." + ], + ) + + +@require_torch +class TestAsymmetricT5(unittest.TestCase): + def build_model_and_check_forward_pass(self, **kwargs): + tester = T5ModelTester(self, **kwargs) + config, *inputs = tester.prepare_config_and_inputs() + ( + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ) = inputs + model = T5ForConditionalGeneration(config=config).to(torch_device).eval() + outputs = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + labels=lm_labels, + ) + # outputs = model(*inputs) + assert len(outputs) == 4 + assert outputs["logits"].size() == (tester.batch_size, tester.decoder_seq_length, tester.vocab_size) + assert outputs["loss"].size() == () + return model + + def test_small_decoder(self): + # num_hidden_layers is passed to T5Config as num_layers + model = self.build_model_and_check_forward_pass(decoder_layers=1, num_hidden_layers=2) + assert len(model.encoder.block) == 2 + assert len(model.decoder.block) == 1 + + def test_defaulting_to_symmetry(self): + # num_hidden_layers is passed to T5Config as num_layers + model = self.build_model_and_check_forward_pass(num_hidden_layers=2) + assert len(model.decoder.block) == len(model.encoder.block) == 2 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_tf_t5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_tf_t5.py new file mode 100644 index 0000000000000000000000000000000000000000..9976e20baf330cbcf11c9a064c478f9f83a62e49 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_modeling_tf_t5.py @@ -0,0 +1,1040 @@ +# coding=utf-8 +# Copyright 2018 Google T5 Authors and HuggingFace Inc. team. +# +# 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. + +from __future__ import annotations + +import unittest + +from transformers import T5Config, is_tf_available +from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow +from transformers.utils import cached_property + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import ByT5Tokenizer, T5Tokenizer, TFT5EncoderModel, TFT5ForConditionalGeneration, TFT5Model + + +class TFT5ModelTester: + def __init__( + self, + parent, + ): + self.parent = parent + self.batch_size = 13 + self.seq_length = 7 + self.is_training = True + self.use_input_mask = True + self.use_labels = True + self.vocab_size = 99 + self.n_positions = 14 + self.hidden_size = 32 + self.num_hidden_layers = 2 + self.num_attention_heads = 4 + self.d_ff = 37 + self.relative_attention_num_buckets = 8 + self.dropout_rate = 0.1 + self.initializer_factor = 0.002 + self.eos_token_id = 1 + self.pad_token_id = 0 + self.scope = None + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_labels = None + if self.use_labels: + token_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + config = T5Config( + vocab_size=self.vocab_size, + n_positions=self.n_positions, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.pad_token_id, + ) + + return (config, input_ids, input_mask, token_labels) + + def create_and_check_t5_model(self, config, input_ids, input_mask, token_labels): + model = TFT5Model(config=config) + inputs = { + "input_ids": input_ids, + "decoder_input_ids": input_ids, + "decoder_attention_mask": input_mask, + } + result = model(inputs) + + result = model(input_ids, decoder_attention_mask=input_mask, decoder_input_ids=input_ids) + decoder_output = result.last_hidden_state + decoder_past = result.past_key_values + encoder_output = result.encoder_last_hidden_state + self.parent.assertListEqual(list(encoder_output.shape), [self.batch_size, self.seq_length, self.hidden_size]) + self.parent.assertListEqual(list(decoder_output.shape), [self.batch_size, self.seq_length, self.hidden_size]) + # There should be `num_layers` key value embeddings stored in decoder_past[1] + self.parent.assertEqual(len(decoder_past), config.num_layers) + # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past[1] tuple + self.parent.assertEqual(len(decoder_past[0]), 4) + + def create_and_check_t5_with_lm_head(self, config, input_ids, input_mask, token_labels): + model = TFT5ForConditionalGeneration(config=config) + inputs_dict = { + "input_ids": input_ids, + "decoder_input_ids": input_ids, + "decoder_attention_mask": input_mask, + } + + result = model(inputs_dict) + + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_t5_decoder_model_past(self, config, input_ids, decoder_input_ids, attention_mask): + model = TFT5Model(config=config).get_decoder() + + input_ids = input_ids[:1, :] + self.batch_size = 1 + + # first forward pass + outputs = model(input_ids, use_cache=True) + + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + + output_from_no_past = model(next_input_ids)[0] + output_from_past = model(next_tokens, past_key_values=outputs.past_key_values)[0] + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx] + output_from_past_slice = output_from_past[:, 0, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def create_and_check_t5_decoder_model_attention_mask_past( + self, config, input_ids, decoder_input_ids, attention_mask + ): + model = TFT5Model(config=config).get_decoder() + + # create attention mask + half_seq_length = self.seq_length // 2 + attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32) + attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32) + attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1) + + # first forward pass + outputs = model(input_ids, attention_mask=attn_mask, use_cache=True) + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size) + vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change) + condition = tf.transpose( + tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size)) + ) + input_ids = tf.where(condition, random_other_next_tokens, input_ids) + + # append to next input_ids and attn_mask + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + attn_mask = tf.concat( + [attn_mask, tf.ones((attn_mask.shape[0], 1), dtype=tf.int32)], + axis=1, + ) + + # get two different outputs + output_from_no_past = model(next_input_ids, attention_mask=attn_mask)[0] + output_from_past = model(next_tokens, past_key_values=outputs.past_key_values, attention_mask=attn_mask)[0] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).numpy().item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx] + output_from_past_slice = output_from_past[:, 0, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def create_and_check_t5_decoder_model_past_large_inputs( + self, config, input_ids, decoder_input_ids, attention_mask + ): + model = TFT5Model(config=config).get_decoder() + + input_ids = input_ids[:1, :] + attention_mask = attention_mask[:1, :] + self.batch_size = 1 + + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) + + # create hypothetical 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 = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([attention_mask, next_attn_mask], axis=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)[0] + output_from_past = model( + next_tokens, attention_mask=next_attention_mask, past_key_values=outputs.past_key_values + )[0] + + self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1]) + + # select random slice + random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1])) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + # test that outputs are equal for slice + tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + (config, input_ids, input_mask, token_labels) = config_and_inputs + inputs_dict = { + "input_ids": input_ids, + "decoder_input_ids": input_ids, + "decoder_attention_mask": input_mask, + } + return config, inputs_dict + + +@require_tf +class TFT5ModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + is_encoder_decoder = True + all_model_classes = (TFT5Model, TFT5ForConditionalGeneration) if is_tf_available() else () + all_generative_model_classes = (TFT5ForConditionalGeneration,) if is_tf_available() else () + pipeline_model_mapping = ( + { + "conversational": TFT5ForConditionalGeneration, + "feature-extraction": TFT5Model, + "summarization": TFT5ForConditionalGeneration, + "text2text-generation": TFT5ForConditionalGeneration, + "translation": TFT5ForConditionalGeneration, + } + if is_tf_available() + else {} + ) + test_onnx = False + + def setUp(self): + self.model_tester = TFT5ModelTester(self) + self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_t5_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_t5_model(*config_and_inputs) + + def test_t5_model_v1_1(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config = config_and_inputs[0] + config.tie_word_embeddings = False + config.feed_forward_proj = "gated-gelu" + self.model_tester.create_and_check_t5_model(config, *config_and_inputs[1:]) + + def test_with_lm_head(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_t5_with_lm_head(*config_and_inputs) + + def test_t5_decoder_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_t5_decoder_model_past(*config_and_inputs) + + def test_t5_decoder_model_past_with_attn_mask(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_t5_decoder_model_attention_mask_past(*config_and_inputs) + + def test_t5_decoder_model_past_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + + # `create_and_check_t5_decoder_model_past_large_inputs` has special inputs: + # (config, input_ids, decoder_input_ids, attention_mask) + # and we have to prepare it correctly here. + config, input_ids, input_mask, token_labels = config_and_inputs + config_and_inputs = (config, input_ids, None, input_mask) + + self.model_tester.create_and_check_t5_decoder_model_past_large_inputs(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + model = TFT5Model.from_pretrained("t5-small") + self.assertIsNotNone(model) + + def test_generate_with_headmasking(self): + # TODO: Fix head-masking according to PyTorch T5 model + pass + + # This test is run in `TFT5EncoderOnlyModelTest`, where the main layer has the same inputs as the model + @unittest.skip(reason="The inputs of the Main Layer are different.") + def test_keras_save_load(self): + pass + + @unittest.skip("Does not support conversations.") + def test_pipeline_conversational(self): + pass + + +class TFT5EncoderOnlyModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + # For common tests + use_attention_mask=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + is_training=False, + dropout_rate=0.1, + initializer_factor=0.002, + is_encoder_decoder=False, + eos_token_id=1, + pad_token_id=0, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + # For common tests + self.seq_length = self.encoder_seq_length + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.is_encoder_decoder = is_encoder_decoder + self.scope = None + self.is_training = is_training + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) + + config = T5Config( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + is_encoder_decoder=self.is_encoder_decoder, + ) + + return ( + config, + input_ids, + attention_mask, + ) + + def create_and_check_model( + self, + config, + input_ids, + attention_mask, + ): + model = TFT5EncoderModel(config=config) + result = model( + input_ids=input_ids, + attention_mask=attention_mask, + ) + result = model(input_ids=input_ids) + encoder_output = result.last_hidden_state + + self.parent.assertEqual(encoder_output.shape, (self.batch_size, self.encoder_seq_length, self.hidden_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + attention_mask, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + +class TFT5EncoderOnlyModelTest(TFModelTesterMixin, unittest.TestCase): + is_encoder_decoder = False + all_model_classes = (TFT5EncoderModel,) if is_tf_available() else () + test_onnx = False + + def setUp(self): + self.model_tester = TFT5EncoderOnlyModelTester(self) + self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + # is not able to be part of a pipeline + def test_train_pipeline_custom_model(self): + pass + + +@require_tf +@require_sentencepiece +@require_tokenizers +class TFT5GenerationIntegrationTests(unittest.TestCase): + @slow + def test_greedy_xla_generate_simple(self): + model = TFT5ForConditionalGeneration.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + # two examples with different lengths to confirm that attention masks are operational in XLA + sentences = [ + "Translate English to German: Today is a beautiful day.", + "Translate English to German: I have four cats, three dogs, two birds, and a horse.", + ] + input_ids = tokenizer(sentences, return_tensors="tf", padding=True).input_ids + + xla_generate = tf.function(model.generate, jit_compile=True) + + output_ids = model.generate(input_ids) + output_ids_xla = xla_generate(input_ids) + + output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + output_strings_xla = tokenizer.batch_decode(output_ids_xla, skip_special_tokens=True) + + expected_output_string = [ + "Heute ist ein schöner Tag.", + "Ich habe vier Katzen, drei Hunde, zwei Vögel und ein Pferd.", + ] + + self.assertListEqual(expected_output_string, output_strings) + self.assertListEqual(expected_output_string, output_strings_xla) + + @slow + def test_greedy_generate(self): + model = TFT5ForConditionalGeneration.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + sentences = ["Yesterday, my name was", "Today is a beautiful day and"] + input_ids = tokenizer(sentences, return_tensors="tf", padding=True).input_ids + + generation_kwargs = { + "bad_words_ids": [tokenizer("my").input_ids, tokenizer("ein schöner").input_ids], + "no_repeat_ngram_size": 3, + "do_sample": False, + "repetition_penalty": 2.2, + } + + output_ids = model.generate(input_ids, **generation_kwargs) + + output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + expected_output_string = ["Yesterday, my name was", "Heute ist ein schöne Tag und"] + + self.assertListEqual(expected_output_string, output_strings) + + @slow + def test_sample_xla_generate_simple(self): + # NOTE: due to the small numerical differences that are natural when we compile to XLA, sampling the same + # output out of the same seed is far from guaranteed. We can, however, confirm that the results are sensible + # and that we can seed both versions. + + # forces the generation to happen on CPU, to avoid GPU-related quirks + with tf.device(":/CPU:0"): + model = TFT5ForConditionalGeneration.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + sentence = "Translate English to German: I have two bananas" + input_ids = tokenizer(sentence, return_tensors="tf", padding=True).input_ids + expected_output_string = ["Ich habe zwei Bananen"] + expected_output_string_xla = ["Ich habe 2 Bananen"] + + # seed set -> deterministic sampling sequence -> deterministic generation + output_ids = model.generate(input_ids, do_sample=True, seed=[42, 0]) + output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + self.assertListEqual(expected_output_string, output_strings) + + xla_generate = tf.function(model.generate, jit_compile=True) + # seed set -> deterministic sampling sequence -> deterministic generation + output_ids_xla = xla_generate(input_ids, do_sample=True, seed=[42, 0]) + output_strings_xla = tokenizer.batch_decode(output_ids_xla, skip_special_tokens=True) + self.assertListEqual(expected_output_string_xla, output_strings_xla) + + @slow + def test_sample_generate(self): + model = TFT5ForConditionalGeneration.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + sentences = ["I really love my", "Translate English to German: the transformers are truly amazing"] + input_ids = tokenizer(sentences, return_tensors="tf", padding=True).input_ids + + generation_kwargs = { + "do_sample": True, + "bad_words_ids": [tokenizer("my").input_ids, tokenizer("ein schöner").input_ids], + "no_repeat_ngram_size": 3, + "repetition_penalty": 2.2, + "temperature": 0.8, + "top_k": 500, + "top_p": 0.9, + "seed": [20, 0], # seed set -> deterministic sampling sequence -> deterministic generation + } + + # forces the generation to happen on CPU, to avoid GPU-related quirks + with tf.device(":/CPU:0"): + output_ids = model.generate(input_ids, **generation_kwargs) + + output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + expected_output_string = ["- I really love my way of this.", "die Transformatoren sind wirklich erstaunlich"] + + self.assertListEqual(expected_output_string, output_strings) + + # TODO (ydshieh): undo skip once a fix is done on TF side. + @unittest.skip("Skip for now as TF 2.13 breaks it on GPU") + @slow + def test_beam_search_xla_generate_simple(self): + model = TFT5ForConditionalGeneration.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + # tests XLA with task specific arguments + task_specific_config = getattr(model.config, "task_specific_params", {}) + translation_config = task_specific_config.get("translation_en_to_fr", {}) + model.config.update(translation_config) + + # two examples with different lengths to confirm that attention masks are operational in XLA + sentences = [ + model.config.prefix + "Today is a beautiful day.", + model.config.prefix + "I have four cats, three dogs, two birds, and a horse.", + ] + input_ids = tokenizer(sentences, return_tensors="tf", padding=True).input_ids + + xla_generate = tf.function(model.generate, jit_compile=True) + + output_ids = model.generate(input_ids, num_beams=2) + output_ids_xla = xla_generate(input_ids, num_beams=2) + + output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + output_strings_xla = tokenizer.batch_decode(output_ids_xla, skip_special_tokens=True) + + expected_output_string = [ + "Aujourd'hui est une belle journée.", + "J'ai quatre chats, trois chiens, deux oiseaux et un cheval.", + ] + + self.assertListEqual(expected_output_string, output_strings) + self.assertListEqual(expected_output_string, output_strings_xla) + + @slow + def test_beam_search_generate(self): + model = TFT5ForConditionalGeneration.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + sentences = ["I really love my", "Translate English to German: the transformers are truly amazing"] + input_ids = tokenizer(sentences, return_tensors="tf", padding=True).input_ids + + generation_kwargs = { + "bad_words_ids": [tokenizer("my").input_ids, tokenizer("ein schöner").input_ids], + "no_repeat_ngram_size": 3, + "do_sample": False, + "repetition_penalty": 2.2, + "num_beams": 4, + } + + output_ids = model.generate(input_ids, **generation_kwargs) + + output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + + expected_output_string = ["Ich liebe es so sehr!", "die Transformatoren sind wirklich erstaunlich"] + self.assertListEqual(expected_output_string, output_strings) + + @unittest.skip("Does not support conversations.") + def test_pipeline_conversational(self): + pass + + +@require_tf +@require_sentencepiece +@require_tokenizers +class TFT5ModelIntegrationTests(unittest.TestCase): + @cached_property + def model(self): + return TFT5ForConditionalGeneration.from_pretrained("t5-base") + + @slow + def test_small_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.7.1 + >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary + + >>> path_to_mtf_small_t5_checkpoint = '' + >>> path_to_mtf_small_spm_model_path = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_mtf_small_t5_checkpoint, batch_size=1, tpu=None) + >>> vocab = SentencePieceVocabulary(path_to_mtf_small_spm_model_path, extra_ids=100) + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = TFT5ForConditionalGeneration.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + + input_ids = tokenizer("Hello there", return_tensors="tf").input_ids + labels = tokenizer("Hi I am", return_tensors="tf").input_ids + + loss = model(input_ids, labels=labels).loss + mtf_score = -tf.math.reduce_mean(loss).numpy() + + EXPECTED_SCORE = -4.771147 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_small_v1_1_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.7.1 + >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary + + >>> path_to_mtf_small_t5_v1.1_checkpoint = '' + >>> path_to_mtf_small_spm_model_path = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_mtf_small_t5_v1.1_checkpoint, batch_size=1, tpu=None) + >>> vocab = SentencePieceVocabulary(path_to_mtf_small_spm_model_path, extra_ids=100) + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = TFT5ForConditionalGeneration.from_pretrained("google/t5-v1_1-small") + tokenizer = T5Tokenizer.from_pretrained("google/t5-v1_1-small") + + input_ids = tokenizer("Hello there", return_tensors="tf").input_ids + labels = tokenizer("Hi I am", return_tensors="tf").input_ids + + loss = model(input_ids, labels=labels).loss + mtf_score = -tf.math.reduce_mean(loss).numpy() + + EXPECTED_SCORE = -14.757326 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_small_byt5_integration_test(self): + """ + For comparision run: + >>> import t5 # pip install t5==0.9.1 + + >>> path_to_byt5_small_checkpoint = '' + >>> t5_model = t5.models.MtfModel(model_dir=path_to_tf_checkpoint, batch_size=1, tpu=None) + >>> vocab = t5.data.ByteVocabulary() + >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab) + """ + + model = TFT5ForConditionalGeneration.from_pretrained("google/byt5-small") + tokenizer = ByT5Tokenizer.from_pretrained("google/byt5-small") + + input_ids = tokenizer("Hello there", return_tensors="tf").input_ids + labels = tokenizer("Hi I am", return_tensors="tf").input_ids + + loss = model(input_ids, labels=labels).loss + mtf_score = -tf.math.reduce_mean(loss).numpy() + + EXPECTED_SCORE = -7.592465 + self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4) + + @slow + def test_summarization(self): + model = self.model + tok = T5Tokenizer.from_pretrained("t5-base") + + FRANCE_ARTICLE = ( # @noqa + "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." + ) + + 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." + ) + + expected_summaries = [ + 'prosecutor: "so far no videos were used in the crash investigation" two magazines claim to have found a' + " cell phone video of the final seconds . \"one can hear cries of 'My God' in several languages,\" one" + " magazine says .", + "the formal accession was marked by a ceremony at The Hague, in the Netherlands . the ICC opened a" + " preliminary examination into the situation in the occupied Palestinian territory . as members of the" + " court, Palestinians may be subject to counter-charges as well .", + "the u.s. and its negotiating partners reached a very strong framework agreement with Iran . aaron miller:" + " the debate that has already begun since the announcement of the new framework will likely result in more" + " heat than light . the deal would reduce Iran's low-enriched uranium stockpile, cut centrifuges and" + " implement a rigorous inspection regime .", + "prosecutors say the marriages were part of an immigration scam . if convicted, barrientos faces two" + ' criminal counts of "offering a false instrument for filing in the first degree" she has been married 10' + " times, with nine of her marriages occurring between 1999 and 2002 .", + ] + + task_specific_config = getattr(model.config, "task_specific_params", {}) + summarization_config = task_specific_config.get("summarization", {}) + model.config.update(summarization_config) + + dct = tok( + [model.config.prefix + x for x in [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY]], + max_length=512, + padding="max_length", + truncation=True, + return_tensors="tf", + ) + self.assertEqual(512, dct["input_ids"].shape[1]) + + hypotheses_batch = model.generate( + input_ids=dct["input_ids"], + attention_mask=dct["attention_mask"], + num_beams=4, + length_penalty=2.0, + max_length=142, + min_length=56, + no_repeat_ngram_size=3, + do_sample=False, + early_stopping=True, + ) + + decoded = [ + tok.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in hypotheses_batch + ] + + self.assertListEqual( + expected_summaries, + decoded, + ) + + @slow + def test_translation_en_to_de(self): + tok = T5Tokenizer.from_pretrained("t5-base") + model = self.model + + task_specific_config = getattr(model.config, "task_specific_params", {}) + translation_config = task_specific_config.get("translation_en_to_de", {}) + self.model.config.update(translation_config) + + original_input = '"Luigi often said to me that he never wanted the brothers to end up in court", she wrote.' + expected_translation = ( + '"Luigi sagte mir oft, dass er nie wollte, dass die Brüder am Gericht sitzen", schrieb sie.' + ) + + input_ids = tok.encode(model.config.prefix + original_input, return_tensors="tf") + + output = model.generate( + input_ids=input_ids, + num_beams=4, + length_penalty=2.0, + max_length=50, + no_repeat_ngram_size=3, + do_sample=False, + early_stopping=True, + ) + translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False) + + self.assertEqual(translation, expected_translation) + + @slow + def test_translation_en_to_fr(self): + model = self.model + tok = T5Tokenizer.from_pretrained("t5-base") + + task_specific_config = getattr(model.config, "task_specific_params", {}) + translation_config = task_specific_config.get("translation_en_to_fr", {}) + model.config.update(translation_config) + + en_text = ( + ' This image section from an infrared recording by the Spitzer telescope shows a "family portrait" of' + " countless generations of stars: the oldest stars are seen as blue dots. " + ) + + new_truncated_translation = ( + "Cette section d'images provenant de l'enregistrement infrarouge effectué par le télescope Spitzer montre " + "un " + "« portrait familial » de générations innombrables d’étoiles : les plus anciennes sont observées " + "sous forme " + "de points bleus." + ) + + input_ids = tok(model.config.prefix + en_text, return_tensors="tf").input_ids + + output = model.generate( + input_ids=input_ids, + num_beams=4, + length_penalty=2.0, + max_length=100, + no_repeat_ngram_size=3, + do_sample=False, + early_stopping=True, + ) + translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False) + + self.assertEqual(translation, new_truncated_translation) + + @slow + def test_translation_en_to_ro(self): + model = self.model + tok = T5Tokenizer.from_pretrained("t5-base") + + task_specific_config = getattr(model.config, "task_specific_params", {}) + translation_config = task_specific_config.get("translation_en_to_ro", {}) + model.config.update(translation_config) + + original_input = "Taco Bell said it plans to add 2,000 locations in the US by 2022." + expected_translation = "Taco Bell a declarat că intenţionează să adauge 2 000 de locaţii în SUA până în 2022." + + input_ids = tok.encode(model.config.prefix + original_input, return_tensors="tf") + + output = model.generate( + input_ids=input_ids, + num_beams=4, + length_penalty=2.0, + max_length=50, + no_repeat_ngram_size=3, + do_sample=False, + early_stopping=True, + ) + translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False) + + self.assertEqual(translation, expected_translation) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_tokenization_t5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_tokenization_t5.py new file mode 100644 index 0000000000000000000000000000000000000000..a141dea86b71a59cd123dd62092e5b07e37efb3a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/t5/test_tokenization_t5.py @@ -0,0 +1,585 @@ +# coding=utf-8 +# Copyright 2018 Google T5 Authors and HuggingFace Inc. team. +# +# 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 re +import tempfile +import unittest + +from transformers import SPIECE_UNDERLINE, AddedToken, BatchEncoding, T5Tokenizer, T5TokenizerFast +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_seqio, require_tokenizers, slow +from transformers.utils import cached_property, is_tf_available, is_torch_available + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + +if is_torch_available(): + FRAMEWORK = "pt" +elif is_tf_available(): + FRAMEWORK = "tf" +else: + FRAMEWORK = "jax" + + +@require_sentencepiece +@require_tokenizers +class T5TokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = T5Tokenizer + rust_tokenizer_class = T5TokenizerFast + test_rust_tokenizer = True + test_sentencepiece = True + + def setUp(self): + super().setUp() + + # We have a SentencePiece fixture for testing + tokenizer = T5Tokenizer(SAMPLE_VOCAB) + tokenizer.save_pretrained(self.tmpdirname) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "" + token_id = 1 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + self.assertEqual(vocab_keys[1100], "") + self.assertEqual(len(vocab_keys), 1_101) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 1000) + self.assertEqual(len(self.get_tokenizer()), 1101) + + def test_full_tokenizer(self): + tokenizer = T5Tokenizer(SAMPLE_VOCAB) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [285, 46, 10, 170, 382]) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "é", + ".", + ], + ) + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual(ids, [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual( + back_tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "", + ".", + ], + ) + + @cached_property + def t5_base_tokenizer(self): + return T5Tokenizer.from_pretrained("t5-base") + + @cached_property + def t5_base_tokenizer_fast(self): + return T5TokenizerFast.from_pretrained("t5-base") + + def get_tokenizer(self, **kwargs) -> T5Tokenizer: + return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs) + + def get_rust_tokenizer(self, **kwargs) -> T5TokenizerFast: + return self.rust_tokenizer_class.from_pretrained(self.tmpdirname, **kwargs) + + def test_rust_and_python_full_tokenizers(self): + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + sequence = "I was born in 92000, and this is falsé." + + tokens = tokenizer.tokenize(sequence) + rust_tokens = rust_tokenizer.tokenize(sequence) + self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + rust_tokenizer = self.get_rust_tokenizer() + ids = tokenizer.encode(sequence) + rust_ids = rust_tokenizer.encode(sequence) + self.assertListEqual(ids, rust_ids) + + def test_eos_treatment(self): + tokenizer = self.t5_base_tokenizer + batch_with_eos_added = tokenizer(["hi", "I went to the gym", ""]) + batch_without_eos_added = tokenizer(["hi", "I went to the gym", ""]) + self.assertListEqual(batch_with_eos_added["input_ids"], batch_without_eos_added["input_ids"]) + + def test_prepare_batch(self): + tokenizer = self.t5_base_tokenizer + src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] + expected_src_tokens = [71, 307, 8986, 21, 4505, 1635, 1707, 5, tokenizer.eos_token_id] + batch = tokenizer(src_text, padding=True, return_tensors=FRAMEWORK) + self.assertIsInstance(batch, BatchEncoding) + + if FRAMEWORK != "jax": + result = list(batch.input_ids.numpy()[0]) + else: + result = list(batch.input_ids.tolist()[0]) + + self.assertListEqual(expected_src_tokens, result) + + self.assertEqual((2, 9), batch.input_ids.shape) + self.assertEqual((2, 9), batch.attention_mask.shape) + + def test_empty_target_text(self): + tokenizer = self.t5_base_tokenizer + src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] + batch = tokenizer(src_text, padding=True, return_tensors=FRAMEWORK) + # check if input_ids are returned and no decoder_input_ids + self.assertIn("input_ids", batch) + self.assertIn("attention_mask", batch) + self.assertNotIn("decoder_input_ids", batch) + self.assertNotIn("decoder_attention_mask", batch) + + def test_max_length(self): + tokenizer = self.t5_base_tokenizer + tgt_text = [ + "Summary of the text.", + "Another summary.", + ] + targets = tokenizer( + text_target=tgt_text, max_length=32, padding="max_length", truncation=True, return_tensors=FRAMEWORK + ) + self.assertEqual(32, targets["input_ids"].shape[1]) + + def test_outputs_not_longer_than_maxlen(self): + tokenizer = self.t5_base_tokenizer + + batch = tokenizer( + ["I am a small frog" * 1000, "I am a small frog"], padding=True, truncation=True, return_tensors=FRAMEWORK + ) + self.assertIsInstance(batch, BatchEncoding) + # Since T5 does NOT have a max input length, + # this test should be changed to the following in Transformers v5: + # self.assertEqual(batch.input_ids.shape, (2, 8001)) + self.assertEqual(batch.input_ids.shape, (2, 512)) + + def test_eos_in_input(self): + tokenizer = self.t5_base_tokenizer + src_text = ["A long paragraph for summarization. "] + tgt_text = ["Summary of the text. "] + expected_src_tokens = [71, 307, 8986, 21, 4505, 1635, 1707, 5, 1] + expected_tgt_tokens = [20698, 13, 8, 1499, 5, 1] + + batch = tokenizer(src_text, text_target=tgt_text) + + self.assertEqual(expected_src_tokens, batch["input_ids"][0]) + self.assertEqual(expected_tgt_tokens, batch["labels"][0]) + + def test_token_type_ids(self): + src_text_1 = ["A first paragraph for summarization."] + src_text_2 = ["A second paragraph for summarization."] + + fast_token_type_ids = self.t5_base_tokenizer_fast( + src_text_1, src_text_2, add_special_tokens=True, return_token_type_ids=True + ).token_type_ids + slow_token_type_ids = self.t5_base_tokenizer( + src_text_1, src_text_2, add_special_tokens=True, return_token_type_ids=True + ).token_type_ids + + self.assertEqual(slow_token_type_ids, fast_token_type_ids) + self.assertEqual(len(slow_token_type_ids[0]), 18) + + def test_fast_and_slow_same_result(self): + src_text = " Today is nice day " + tgt_ids = [0, 1960, 19, 2, 1245, 239, 1] + tgt_text = " Today is nice day" + + fast_ids = self.t5_base_tokenizer_fast(src_text, add_special_tokens=False).input_ids + slow_ids = self.t5_base_tokenizer(src_text, add_special_tokens=False).input_ids + self.assertEqual(tgt_ids, fast_ids) + self.assertEqual(tgt_ids, slow_ids) + + fast_text = self.t5_base_tokenizer_fast.decode(fast_ids) + slow_text = self.t5_base_tokenizer.decode(fast_ids) + self.assertEqual(tgt_text, fast_text) + self.assertEqual(tgt_text, slow_text) + + def test_special_tokens_initialization(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + added_tokens = [f"" for i in range(100)] + [AddedToken("", lstrip=True)] + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, additional_special_tokens=added_tokens, **kwargs + ) + tokenizer_cr = self.rust_tokenizer_class.from_pretrained( + pretrained_name, additional_special_tokens=added_tokens, **kwargs, from_slow=True + ) + tokenizer_p = self.tokenizer_class.from_pretrained( + pretrained_name, additional_special_tokens=added_tokens, **kwargs + ) + + p_output = tokenizer_p.encode("Hey this is a token") + r_output = tokenizer_r.encode("Hey this is a token") + cr_output = tokenizer_cr.encode("Hey this is a token") + + special_token_id = tokenizer_r.encode("", add_special_tokens=False)[0] + + self.assertEqual(p_output, r_output) + self.assertEqual(cr_output, r_output) + self.assertTrue(special_token_id in p_output) + self.assertTrue(special_token_id in r_output) + self.assertTrue(special_token_id in cr_output) + + def test_special_tokens_initialization_with_non_empty_additional_special_tokens(self): + tokenizer_list = [] + if self.test_slow_tokenizer: + tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) + + if self.test_rust_tokenizer: + tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())) + + for tokenizer_class, tokenizer_utils in tokenizer_list: + with tempfile.TemporaryDirectory() as tmp_dir: + tokenizer_utils.save_pretrained(tmp_dir) + + with open(os.path.join(tmp_dir, "special_tokens_map.json"), encoding="utf-8") as json_file: + special_tokens_map = json.load(json_file) + + with open(os.path.join(tmp_dir, "tokenizer_config.json"), encoding="utf-8") as json_file: + tokenizer_config = json.load(json_file) + + added_tokens_extra_ids = [f"" for i in range(100)] + + special_tokens_map["additional_special_tokens"] = added_tokens_extra_ids + [ + "an_additional_special_token" + ] + tokenizer_config["additional_special_tokens"] = added_tokens_extra_ids + [ + "an_additional_special_token" + ] + + with open(os.path.join(tmp_dir, "special_tokens_map.json"), "w", encoding="utf-8") as outfile: + json.dump(special_tokens_map, outfile) + with open(os.path.join(tmp_dir, "tokenizer_config.json"), "w", encoding="utf-8") as outfile: + json.dump(tokenizer_config, outfile) + + # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes + # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and + # "special_tokens_map.json" files + tokenizer_without_change_in_init = tokenizer_class.from_pretrained( + tmp_dir, + ) + self.assertIn( + "an_additional_special_token", tokenizer_without_change_in_init.additional_special_tokens + ) + # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab + self.assertEqual( + ["an_additional_special_token"], + tokenizer_without_change_in_init.convert_ids_to_tokens( + tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"]) + ), + ) + + # Now we test that we can change the value of additional_special_tokens in the from_pretrained + new_added_tokens = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token", lstrip=True)] + tokenizer = tokenizer_class.from_pretrained( + tmp_dir, + additional_special_tokens=new_added_tokens, + ) + + self.assertIn("a_new_additional_special_token", tokenizer.additional_special_tokens) + self.assertEqual( + ["a_new_additional_special_token"], + tokenizer.convert_ids_to_tokens( + tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"]) + ), + ) + + # overwritten from `test_tokenization_common` since T5 has no max length + def test_pretrained_model_lists(self): + # We should have at least one default checkpoint for each tokenizer + # We should specify the max input length as well (used in some part to list the pretrained checkpoints) + self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map), 1) + self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values())[0]), 1) + + @slow + def test_tokenizer_integration(self): + expected_encoding = {'input_ids': [[31220, 7, 41, 14034, 801, 38, 3, 102, 63, 17, 127, 524, 18, 7031, 2032, 277, 11, 3, 102, 63, 17, 127, 524, 18, 2026, 17, 10761, 18, 7041, 61, 795, 879, 18, 19681, 4648, 7, 41, 12920, 382, 6, 350, 6383, 4949, 6, 2158, 12920, 382, 9, 6, 3, 4, 11160, 6, 2043, 17153, 279, 49, 17, 6, 3, 4, 434, 9688, 11439, 21, 6869, 10509, 17725, 41, 567, 9138, 61, 11, 6869, 10509, 11946, 41, 18207, 517, 61, 28, 147, 3538, 1220, 7140, 10761, 2250, 16, 910, 1220, 8024, 11, 1659, 1413, 32, 883, 2020, 344, 2215, 226, 6, 12901, 382, 127, 524, 11, 4738, 7, 127, 15390, 5, 1], [272, 24203, 19, 876, 12, 554, 18, 9719, 1659, 2647, 26352, 6497, 7, 45, 73, 9339, 400, 26, 1499, 57, 22801, 10760, 30, 321, 646, 11, 269, 2625, 16, 66, 7500, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [37, 1704, 4216, 3, 20400, 4418, 7, 147, 8, 19743, 1782, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: skip + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, + model_name="t5-base", + revision="5a7ff2d8f5117c194c7e32ec1ccbf04642cca99b", + ) + + def test_get_sentinel_tokens(self): + tokenizer = T5Tokenizer(SAMPLE_VOCAB, extra_ids=10) + sentinel_tokens = tokenizer.get_sentinel_tokens() + self.assertEqual(len(sentinel_tokens), 10) + self.assertListEqual(sorted(sentinel_tokens), sorted([f"" for i in range(0, 10)])) + self.assertTrue([re.search(r"", token) is not None for token in sentinel_tokens]) + + def test_get_sentinel_token_ids(self): + tokenizer = T5Tokenizer(SAMPLE_VOCAB, extra_ids=10) + self.assertListEqual(sorted(tokenizer.get_sentinel_token_ids()), sorted(range(1000, 1010))) + + def test_get_sentinel_tokens_for_fasttokenizer(self): + tokenizer = T5TokenizerFast(SAMPLE_VOCAB, extra_ids=10) + sentinel_tokens = tokenizer.get_sentinel_tokens() + self.assertEqual(len(sentinel_tokens), 10) + self.assertListEqual(sorted(sentinel_tokens), sorted([f"" for i in range(0, 10)])) + self.assertTrue([re.search(r"", token) is not None for token in sentinel_tokens]) + + def test_get_sentinel_token_ids_for_fasttokenizer(self): + tokenizer = T5TokenizerFast(SAMPLE_VOCAB, extra_ids=10) + self.assertListEqual(sorted(tokenizer.get_sentinel_token_ids()), sorted(range(1000, 1010))) + + def test_some_edge_cases(self): + tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=False) + + sp_tokens = tokenizer.sp_model.encode(">", out_type=str) + self.assertEqual(sp_tokens, ["<", "/", "s", ">", ">"]) + tokens = tokenizer.tokenize(">") + self.assertNotEqual(sp_tokens, tokens) + self.assertEqual(tokens, ["", ">"]) + + tokens = tokenizer.tokenize("") + self.assertEqual(tokens, []) + self.assertEqual(tokens, tokenizer.sp_model.encode("", out_type=str)) + + tokens = tokenizer.tokenize(" ") + self.assertEqual(tokens, []) + self.assertEqual(tokens, tokenizer.sp_model.encode(" ", out_type=str)) + + tokens = tokenizer.tokenize("▁") + self.assertEqual(tokens, []) + self.assertEqual(tokens, tokenizer.sp_model.encode("▁", out_type=str)) + + tokens = tokenizer.tokenize(" ▁") + self.assertEqual(tokens, []) + self.assertEqual(tokens, tokenizer.sp_model.encode("▁", out_type=str)) + + +@require_sentencepiece +@require_tokenizers +class CommonSpmIntegrationTests(unittest.TestCase): + """ + A class that regroups important test to make sure that we properly handle the special tokens. + """ + + @classmethod + def setUpClass(cls): + tokenizer = T5Tokenizer(SAMPLE_VOCAB, extra_ids=0, legacy=False) + tokenizer.add_special_tokens( + {"additional_special_tokens": [AddedToken("", rstrip=False, lstrip=False)]} + ) + # TODO ArthurZ the above is necessary as addedTokens / intialization sucks. Trie is not correctly created + # So the extra ids are split.... + cls.tokenizer = tokenizer + + def test_add_dummy_prefix(self): + # make sure `'▁'` is prepended, and outputs match sp_model's + # `sentencepiece.NormalizerSpec.add_dummy_prefix` attribute + input_ids = self.tokenizer.encode(". Hello", add_special_tokens=False) + self.assertEqual(input_ids, [7, 4, 156, 86, 20]) + sp_encode = self.tokenizer.sp_model.encode(". Hello") + self.assertEqual(input_ids, [7] + sp_encode) + tokens = self.tokenizer.tokenize(". Hello") + self.assertEqual(tokens, ["▁", ".", "▁He", "ll", "o"]) + + tokens = self.tokenizer.tokenize("") + self.assertEqual(tokens, []) + self.assertEqual(tokens, self.tokenizer.sp_model.encode("", out_type=str)) + + tokens = self.tokenizer.tokenize(" ") + self.assertEqual(tokens, []) + self.assertEqual(tokens, self.tokenizer.sp_model.encode(" ", out_type=str)) + + tokens = self.tokenizer.tokenize("▁") + self.assertEqual(tokens, []) + self.assertEqual(tokens, self.tokenizer.sp_model.encode("▁", out_type=str)) + + def test_remove_extra_whitespaces(self): + # make sure the extra spaces are eaten + # sentencepiece.NormalizerSpec.remove_extra_whitespaces attribute + input_ids = self.tokenizer.encode(" . Hello", add_special_tokens=False) + self.assertEqual(input_ids, [7, 4, 156, 86, 20]) + sp_encode = self.tokenizer.sp_model.encode(" . Hello") + self.assertEqual(input_ids, [7] + sp_encode) + tokens = self.tokenizer.tokenize(" . Hello") + self.assertEqual(tokens, ["▁", ".", "▁He", "ll", "o"]) + + # `'▁'` is also a whitespace + input_ids = self.tokenizer.encode("▁He is not") + self.assertEqual(input_ids, [156, 46, 44, 2]) + tokens = self.tokenizer.tokenize("▁He is not") + self.assertEqual(tokens, ["▁He", "▁is", "▁not"]) # no extra space added + + input_ids = self.tokenizer.encode("▁He is not ▁He") + # here t5x does not eat with lstrip, so there is and extra ▁He in the original one + self.assertEqual(input_ids, [156, 46, 44, 1001, 156, 2]) + tokens = self.tokenizer.tokenize("▁He is not ▁He") + self.assertEqual(tokens, ["▁He", "▁is", "▁not", "", "▁He"]) # spaces are eaten by spm + # make sure that the output after the extra id is the same as if + # extra_id was not there + input_ids = self.tokenizer.encode("▁He is not ▁He") + self.assertEqual(input_ids, [156, 46, 44, 156, 2]) + tokens = self.tokenizer.tokenize("▁He is not ▁He") + self.assertEqual(tokens, ["▁He", "▁is", "▁not", "▁He"]) # spaces are eaten by spm even if not start + + def test_character_after_special_token(self): + # Make sure that `tokenizer.tokenize` is similar to + # adding the equivalent special token to the vocab + input_ids = self.tokenizer.encode("Hey I") + self.assertEqual(input_ids, [156, 30, 1001, 100, 2]) + tokens = self.tokenizer.tokenize("Hey I") + self.assertEqual(tokens, ["▁He", "y", "", "I"]) + + input_ids = self.tokenizer.encode("Hello, ,") + self.assertEqual(input_ids, [156, 86, 20, 3, 1001, 3, 2]) + tokens = self.tokenizer.tokenize("Hello, ,") + self.assertEqual(tokens, ["▁He", "ll", "o", ",", "", ","]) + + def test_special_tokens_strip(self): + input_ids = self.tokenizer.encode(" ,") + self.assertEqual(input_ids, [1001, 7, 3, 2]) + tokens = self.tokenizer.tokenize(" ,") + # spaces are not longer eaten by rstrip and lstrip + self.assertEqual(tokens, ["", "▁", ","]) + + # test with a begin of word like `▁He` + input_ids = self.tokenizer.encode("No He") + self.assertEqual(input_ids, [284, 1001, 156, 2]) + # spaces are eaten by rstrip / lstrip, so this is expected. Don't strip otherwise you break + tokens = self.tokenizer.tokenize("No He") + self.assertEqual(tokens, ["▁No", "", "▁He"]) + + # Make sure this does not happen if we don't strip + tokenizer = T5Tokenizer(SAMPLE_VOCAB, extra_ids=0) + tokenizer.add_special_tokens({"bos_token": AddedToken("")}) + input_ids = tokenizer.encode("No He") + self.assertEqual(input_ids, [284, 1001, 156, 2]) + tokens = tokenizer.tokenize("No He") + # the first `' '` after `'No'` is eaten by spm: + self.assertEqual(tokenizer.sp_model.encode("No ", out_type=str), ["▁No"]) + self.assertEqual(tokens, ["▁No", "", "▁He"]) + + @require_seqio + @unittest.skipIf( + os.getenv("RUN_TOKENIZER_INTEGRATION", "0") == "0", + "RUN_TOKENIZER_INTEGRATION=1 to run tokenizer integration tests", + ) + def test_integration_seqio(self): + from datasets import load_dataset + from seqio import SentencePieceVocabulary + + ds = load_dataset("xnli", "all_languages", split="train+test+validation") + + # TODO @ArthurZucker fix the 3 commented tests with #23909 + input_texts = [ + "Bonjour .", + # "Bonjour.", # this will fail. In T5 the special token has to be at the end. + # because in T5 they add `_` to the vocab, not ``. + " Hey I love you", + # "Hey I love you", # this will fail, we strip left, to _I vs I + # "Hey ▁He", # this will fail for the same reason, we replace `_` then strip + ] + + import tqdm + + # Test with umt5 + vocab_path = "gs://t5-data/vocabs/umt5.256000/sentencepiece.model" + t5x_tokenizer = SentencePieceVocabulary(vocab_path, extra_ids=300) + hf_tokenizer = T5Tokenizer.from_pretrained("google/umt5-small", legacy=False) + for text in input_texts: + self.assertEqual( + hf_tokenizer.encode(text, add_special_tokens=False), t5x_tokenizer.tokenizer.tokenize(text), f"{text}" + ) + for texts in tqdm.tqdm(ds["premise"]): + for text in texts: + self.assertEqual( + hf_tokenizer.encode(text, add_special_tokens=False), + t5x_tokenizer.tokenizer.tokenize(text), + f"{text}", + ) + + # Test with T5 + hf_tokenizer = T5Tokenizer.from_pretrained("t5-small") + vocab_path = "gs://t5-data/vocabs/cc_all.32000/sentencepiece.model" + t5x_tokenizer = SentencePieceVocabulary(vocab_path, extra_ids=300) + for text in input_texts: + self.assertEqual( + hf_tokenizer.encode(text, add_special_tokens=False), t5x_tokenizer.tokenizer.tokenize(text), f"{text}" + ) + for texts in tqdm.tqdm(ds["premise"]): + for text in texts: + self.assertEqual( + hf_tokenizer.encode(text, add_special_tokens=False), + t5x_tokenizer.tokenizer.tokenize(text), + f"{text}", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/table_transformer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/table_transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/table_transformer/test_modeling_table_transformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/table_transformer/test_modeling_table_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..d81c52ff1307c9654b61d213078c203312170a0e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/table_transformer/test_modeling_table_transformer.py @@ -0,0 +1,541 @@ +# coding=utf-8 +# Copyright 2022 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 Table Transformer model. """ + + +import inspect +import math +import unittest + +from huggingface_hub import hf_hub_download + +from transformers import ResNetConfig, TableTransformerConfig, is_torch_available, is_vision_available +from transformers.testing_utils import require_timm, require_torch, require_vision, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import TableTransformerForObjectDetection, TableTransformerModel + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class TableTransformerModelTester: + def __init__( + self, + parent, + batch_size=8, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=8, + intermediate_size=4, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + num_queries=12, + num_channels=3, + min_size=200, + max_size=200, + n_targets=8, + num_labels=3, + ): + self.parent = parent + self.batch_size = batch_size + self.is_training = is_training + self.use_labels = use_labels + 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.num_queries = num_queries + self.num_channels = num_channels + self.min_size = min_size + self.max_size = max_size + self.n_targets = n_targets + self.num_labels = num_labels + + # we also set the expected seq length for both encoder and decoder + self.encoder_seq_length = math.ceil(self.min_size / 32) * math.ceil(self.max_size / 32) + self.decoder_seq_length = self.num_queries + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]) + + pixel_mask = torch.ones([self.batch_size, self.min_size, self.max_size], device=torch_device) + + labels = None + if self.use_labels: + # labels is a list of Dict (each Dict being the labels for a given example in the batch) + labels = [] + for i in range(self.batch_size): + target = {} + target["class_labels"] = torch.randint( + high=self.num_labels, size=(self.n_targets,), device=torch_device + ) + target["boxes"] = torch.rand(self.n_targets, 4, device=torch_device) + target["masks"] = torch.rand(self.n_targets, self.min_size, self.max_size, device=torch_device) + labels.append(target) + + config = self.get_config() + return config, pixel_values, pixel_mask, labels + + def get_config(self): + resnet_config = ResNetConfig( + num_channels=3, + embeddings_size=10, + hidden_sizes=[10, 20, 30, 40], + depths=[1, 1, 2, 1], + hidden_act="relu", + num_labels=3, + out_features=["stage2", "stage3", "stage4"], + out_indices=[2, 3, 4], + ) + return TableTransformerConfig( + 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, + num_queries=self.num_queries, + num_labels=self.num_labels, + use_timm_backbone=False, + backbone_config=resnet_config, + ) + + def prepare_config_and_inputs_for_common(self): + config, pixel_values, pixel_mask, labels = self.prepare_config_and_inputs() + inputs_dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} + return config, inputs_dict + + def create_and_check_table_transformer_model(self, config, pixel_values, pixel_mask, labels): + model = TableTransformerModel(config=config) + model.to(torch_device) + model.eval() + + result = model(pixel_values=pixel_values, pixel_mask=pixel_mask) + result = model(pixel_values) + + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.decoder_seq_length, self.hidden_size) + ) + + def create_and_check_table_transformer_object_detection_head_model(self, config, pixel_values, pixel_mask, labels): + model = TableTransformerForObjectDetection(config=config) + model.to(torch_device) + model.eval() + + result = model(pixel_values=pixel_values, pixel_mask=pixel_mask) + result = model(pixel_values) + + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1)) + self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4)) + + result = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=labels) + + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1)) + self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4)) + + def create_and_check_table_transformer_no_timm_backbone(self, config, pixel_values, pixel_mask, labels): + config.use_timm_backbone = False + config.backbone_config = ResNetConfig() + model = TableTransformerForObjectDetection(config=config) + model.to(torch_device) + model.eval() + + result = model(pixel_values=pixel_values, pixel_mask=pixel_mask) + result = model(pixel_values) + + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1)) + self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4)) + + result = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=labels) + + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1)) + self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4)) + + +@require_torch +class TableTransformerModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TableTransformerModel, + TableTransformerForObjectDetection, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + {"feature-extraction": TableTransformerModel, "object-detection": TableTransformerForObjectDetection} + if is_torch_available() + else {} + ) + is_encoder_decoder = True + test_torchscript = False + test_pruning = False + test_head_masking = False + test_missing_keys = False + + # special case for head models + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) + + if return_labels: + if model_class.__name__ in ["TableTransformerForObjectDetection"]: + labels = [] + for i in range(self.model_tester.batch_size): + target = {} + target["class_labels"] = torch.ones( + size=(self.model_tester.n_targets,), device=torch_device, dtype=torch.long + ) + target["boxes"] = torch.ones( + self.model_tester.n_targets, 4, device=torch_device, dtype=torch.float + ) + target["masks"] = torch.ones( + self.model_tester.n_targets, + self.model_tester.min_size, + self.model_tester.max_size, + device=torch_device, + dtype=torch.float, + ) + labels.append(target) + inputs_dict["labels"] = labels + + return inputs_dict + + def setUp(self): + self.model_tester = TableTransformerModelTester(self) + self.config_tester = ConfigTester(self, config_class=TableTransformerConfig, has_text_modality=False) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_table_transformer_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_table_transformer_model(*config_and_inputs) + + def test_table_transformer_object_detection_head_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_table_transformer_object_detection_head_model(*config_and_inputs) + + def test_table_transformer_no_timm_backbone(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_table_transformer_no_timm_backbone(*config_and_inputs) + + @unittest.skip(reason="Table Transformer does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="Table Transformer does not have a get_input_embeddings method") + def test_model_common_attributes(self): + pass + + @unittest.skip(reason="Table Transformer is not a generative model") + def test_generate_without_input_ids(self): + pass + + @unittest.skip(reason="Table Transformer does not use token embeddings") + def test_resize_tokens_embeddings(self): + pass + + @slow + def test_model_outputs_equivalence(self): + # TODO Niels: fix me! + pass + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + decoder_seq_length = self.model_tester.decoder_seq_length + encoder_seq_length = self.model_tester.encoder_seq_length + decoder_key_length = self.model_tester.decoder_seq_length + encoder_key_length = self.model_tester.encoder_seq_length + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + out_len = len(outputs) + + if self.is_encoder_decoder: + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + # Object Detection model returns pred_logits and pred_boxes + if model_class.__name__ == "TableTransformerForObjectDetection": + correct_outlen += 2 + + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + elif self.is_encoder_decoder: + added_hidden_states = 2 + else: + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + def test_retain_grad_hidden_states_attentions(self): + # removed retain_grad and grad on decoder_hidden_states, as queries don't require grad + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs = model(**inputs) + + output = outputs[0] + + encoder_hidden_states = outputs.encoder_hidden_states[0] + encoder_attentions = outputs.encoder_attentions[0] + encoder_hidden_states.retain_grad() + encoder_attentions.retain_grad() + + decoder_attentions = outputs.decoder_attentions[0] + decoder_attentions.retain_grad() + + cross_attentions = outputs.cross_attentions[0] + cross_attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(encoder_hidden_states.grad) + self.assertIsNotNone(encoder_attentions.grad) + self.assertIsNotNone(decoder_attentions.grad) + self.assertIsNotNone(cross_attentions.grad) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + if model.config.is_encoder_decoder: + expected_arg_names = ["pixel_values", "pixel_mask"] + expected_arg_names.extend( + ["head_mask", "decoder_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" in arg_names + else [] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + else: + expected_arg_names = ["pixel_values", "pixel_mask"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_different_timm_backbone(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # let's pick a random timm backbone + config.backbone = "tf_mobilenetv3_small_075" + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if model_class.__name__ == "TableTransformerForObjectDetection": + expected_shape = ( + self.model_tester.batch_size, + self.model_tester.num_queries, + self.model_tester.num_labels + 1, + ) + self.assertEqual(outputs.logits.shape, expected_shape) + + self.assertTrue(outputs) + + def test_greyscale_images(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # use greyscale pixel values + inputs_dict["pixel_values"] = floats_tensor( + [self.model_tester.batch_size, 1, self.model_tester.min_size, self.model_tester.max_size] + ) + + # let's set num_channels to 1 + config.num_channels = 1 + config.backbone_config.num_channels = 1 + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertTrue(outputs) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + configs_no_init.init_xavier_std = 1e9 + + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if param.requires_grad: + if "bbox_attention" in name and "bias" not in name: + self.assertLess( + 100000, + abs(param.data.max().item()), + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + +TOLERANCE = 1e-4 + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_timm +@require_vision +@slow +class TableTransformerModelIntegrationTests(unittest.TestCase): + def test_table_detection(self): + image_processor = AutoImageProcessor.from_pretrained("microsoft/table-transformer-detection") + model = TableTransformerForObjectDetection.from_pretrained("microsoft/table-transformer-detection") + model.to(torch_device) + + file_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename="example_pdf.png") + image = Image.open(file_path).convert("RGB") + inputs = image_processor(image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + expected_shape = (1, 15, 3) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_logits = torch.tensor( + [[-6.7329, -16.9590, 6.7447], [-8.0038, -22.3071, 6.9288], [-7.2445, -20.9855, 7.3465]], + device=torch_device, + ) + self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_logits, atol=1e-4)) + + expected_boxes = torch.tensor( + [[0.4868, 0.1764, 0.6729], [0.6674, 0.4621, 0.3864], [0.4720, 0.1757, 0.6362]], device=torch_device + ) + self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_boxes, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_modeling_tapas.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_modeling_tapas.py new file mode 100644 index 0000000000000000000000000000000000000000..6a482d03bed987cf857f6dd54487c44c1f7e7a81 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_modeling_tapas.py @@ -0,0 +1,1115 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import unittest + +import numpy as np +import pandas as pd + +from transformers import ( + MODEL_FOR_CAUSAL_LM_MAPPING, + MODEL_FOR_MASKED_LM_MAPPING, + MODEL_FOR_MULTIPLE_CHOICE_MAPPING, + MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING, + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + TapasConfig, + is_torch_available, +) +from transformers.models.auto import get_values +from transformers.testing_utils import require_tensorflow_probability, require_torch, slow, torch_device +from transformers.utils import cached_property + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + TapasForMaskedLM, + TapasForQuestionAnswering, + TapasForSequenceClassification, + TapasModel, + TapasTokenizer, + ) + from transformers.models.tapas.modeling_tapas import ( + IndexMap, + ProductIndexMap, + flatten, + gather, + range_index_map, + reduce_max, + reduce_mean, + reduce_sum, + ) + from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_12 +else: + is_torch_greater_or_equal_than_1_12 = False + + +class TapasModelTester: + """You can also import this e.g from .test_modeling_tapas import TapasModelTester""" + + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + initializer_range=0.02, + max_position_embeddings=512, + type_vocab_sizes=[3, 256, 256, 2, 256, 256, 10], + type_sequence_label_size=2, + positive_weight=10.0, + num_aggregation_labels=4, + num_labels=2, + aggregation_loss_importance=0.8, + use_answer_as_supervision=True, + answer_loss_importance=0.001, + use_normalized_answer_loss=False, + huber_loss_delta=25.0, + temperature=1.0, + agg_temperature=1.0, + use_gumbel_for_cells=False, + use_gumbel_for_agg=False, + average_approximation_function="ratio", + cell_selection_preference=0.5, + answer_loss_cutoff=100, + max_num_rows=64, + max_num_columns=32, + average_logits_per_cell=True, + select_one_column=True, + allow_empty_column_selection=False, + init_cell_selection_weights_to_zero=True, + reset_position_index_per_cell=True, + disable_per_token_loss=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.initializer_range = initializer_range + self.max_position_embeddings = max_position_embeddings + self.type_vocab_sizes = type_vocab_sizes + self.type_sequence_label_size = type_sequence_label_size + self.positive_weight = positive_weight + self.num_aggregation_labels = num_aggregation_labels + self.num_labels = num_labels + self.aggregation_loss_importance = aggregation_loss_importance + self.use_answer_as_supervision = use_answer_as_supervision + self.answer_loss_importance = answer_loss_importance + self.use_normalized_answer_loss = use_normalized_answer_loss + self.huber_loss_delta = huber_loss_delta + self.temperature = temperature + self.agg_temperature = agg_temperature + self.use_gumbel_for_cells = use_gumbel_for_cells + self.use_gumbel_for_agg = use_gumbel_for_agg + self.average_approximation_function = average_approximation_function + self.cell_selection_preference = cell_selection_preference + self.answer_loss_cutoff = answer_loss_cutoff + self.max_num_rows = max_num_rows + self.max_num_columns = max_num_columns + self.average_logits_per_cell = average_logits_per_cell + self.select_one_column = select_one_column + self.allow_empty_column_selection = allow_empty_column_selection + self.init_cell_selection_weights_to_zero = init_cell_selection_weights_to_zero + self.reset_position_index_per_cell = reset_position_index_per_cell + self.disable_per_token_loss = disable_per_token_loss + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).to(torch_device) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]).to(torch_device) + + token_type_ids = [] + for type_vocab_size in self.type_vocab_sizes: + token_type_ids.append(ids_tensor(shape=[self.batch_size, self.seq_length], vocab_size=type_vocab_size)) + token_type_ids = torch.stack(token_type_ids, dim=2).to(torch_device) + + sequence_labels = None + token_labels = None + labels = None + numeric_values = None + numeric_values_scale = None + float_answer = None + aggregation_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size).to(torch_device) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels).to(torch_device) + labels = ids_tensor([self.batch_size, self.seq_length], vocab_size=2).to(torch_device) + numeric_values = floats_tensor([self.batch_size, self.seq_length]).to(torch_device) + numeric_values_scale = floats_tensor([self.batch_size, self.seq_length]).to(torch_device) + float_answer = floats_tensor([self.batch_size]).to(torch_device) + aggregation_labels = ids_tensor([self.batch_size], self.num_aggregation_labels).to(torch_device) + + config = self.get_config() + + return ( + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ) + + def get_config(self): + return TapasConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_sizes=self.type_vocab_sizes, + initializer_range=self.initializer_range, + positive_weight=self.positive_weight, + num_aggregation_labels=self.num_aggregation_labels, + num_labels=self.num_labels, + aggregation_loss_importance=self.aggregation_loss_importance, + use_answer_as_supervision=self.use_answer_as_supervision, + answer_loss_importance=self.answer_loss_importance, + use_normalized_answer_loss=self.use_normalized_answer_loss, + huber_loss_delta=self.huber_loss_delta, + temperature=self.temperature, + agg_temperature=self.agg_temperature, + use_gumbel_for_cells=self.use_gumbel_for_cells, + use_gumbel_for_agg=self.use_gumbel_for_agg, + average_approximation_function=self.average_approximation_function, + cell_selection_preference=self.cell_selection_preference, + answer_loss_cutoff=self.answer_loss_cutoff, + max_num_rows=self.max_num_rows, + max_num_columns=self.max_num_columns, + average_logits_per_cell=self.average_logits_per_cell, + select_one_column=self.select_one_column, + allow_empty_column_selection=self.allow_empty_column_selection, + init_cell_selection_weights_to_zero=self.init_cell_selection_weights_to_zero, + reset_position_index_per_cell=self.reset_position_index_per_cell, + disable_per_token_loss=self.disable_per_token_loss, + ) + + def create_and_check_model( + self, + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ): + model = TapasModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_for_masked_lm( + self, + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ): + model = TapasForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_question_answering( + self, + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ): + # inference: without aggregation head (SQA). Model only returns logits + sqa_config = copy.copy(config) + sqa_config.num_aggregation_labels = 0 + sqa_config.use_answer_as_supervision = False + model = TapasForQuestionAnswering(config=sqa_config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + + # inference: with aggregation head (WTQ, WikiSQL-supervised). Model returns logits and aggregation logits + model = TapasForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.logits_aggregation.shape, (self.batch_size, self.num_aggregation_labels)) + + # training: can happen in 3 main ways + # case 1: conversational (SQA) + model = TapasForQuestionAnswering(config=sqa_config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=labels, + ) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + + # case 2: weak supervision for aggregation (WTQ) + model = TapasForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=labels, + numeric_values=numeric_values, + numeric_values_scale=numeric_values_scale, + float_answer=float_answer, + ) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.logits_aggregation.shape, (self.batch_size, self.num_aggregation_labels)) + + # case 3: strong supervision for aggregation (WikiSQL-supervised) + wikisql_config = copy.copy(config) + wikisql_config.use_answer_as_supervision = False + model = TapasForQuestionAnswering(config=wikisql_config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + labels=labels, + aggregation_labels=aggregation_labels, + ) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.logits_aggregation.shape, (self.batch_size, self.num_aggregation_labels)) + + def create_and_check_for_sequence_classification( + self, + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ): + config.num_labels = self.num_labels + model = TapasForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, labels=sequence_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@unittest.skipIf(not is_torch_greater_or_equal_than_1_12, reason="Tapas is only available in torch v1.12+") +@require_torch +class TapasModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TapasModel, + TapasForMaskedLM, + TapasForQuestionAnswering, + TapasForSequenceClassification, + ) + if is_torch_available() + else None + ) + pipeline_model_mapping = ( + { + "feature-extraction": TapasModel, + "fill-mask": TapasForMaskedLM, + "table-question-answering": TapasForQuestionAnswering, + "text-classification": TapasForSequenceClassification, + "zero-shot": TapasForSequenceClassification, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_resize_embeddings = True + test_head_masking = False + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = copy.deepcopy(inputs_dict) + if model_class in get_values(MODEL_FOR_MULTIPLE_CHOICE_MAPPING): + inputs_dict = { + k: v.unsqueeze(1).expand(-1, self.model_tester.num_choices, -1).contiguous() + if isinstance(v, torch.Tensor) and v.ndim > 1 + else v + for k, v in inputs_dict.items() + } + + if return_labels: + if model_class in get_values(MODEL_FOR_MULTIPLE_CHOICE_MAPPING): + inputs_dict["labels"] = torch.ones(self.model_tester.batch_size, dtype=torch.long, device=torch_device) + elif model_class in get_values(MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING): + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + inputs_dict["aggregation_labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + inputs_dict["numeric_values"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), + dtype=torch.float, + device=torch_device, + ) + inputs_dict["numeric_values_scale"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), + dtype=torch.float, + device=torch_device, + ) + inputs_dict["float_answer"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.float, device=torch_device + ) + elif model_class in [ + *get_values(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING), + *get_values(MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING), + ]: + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + elif model_class in [ + *get_values(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING), + *get_values(MODEL_FOR_CAUSAL_LM_MAPPING), + *get_values(MODEL_FOR_MASKED_LM_MAPPING), + *get_values(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING), + ]: + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + return inputs_dict + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + return True + + def setUp(self): + self.model_tester = TapasModelTester(self) + self.config_tester = ConfigTester(self, config_class=TapasConfig, dim=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + @require_tensorflow_probability + def test_pt_tf_model_equivalence(self): + super().test_pt_tf_model_equivalence() + + +def prepare_tapas_single_inputs_for_inference(): + # Here we prepare a single table-question pair to test TAPAS inference on: + data = { + "Footballer": ["Lionel Messi", "Cristiano Ronaldo"], + "Age": ["33", "35"], + } + queries = "Which footballer is 33 years old?" + table = pd.DataFrame.from_dict(data) + + return table, queries + + +def prepare_tapas_batch_inputs_for_inference(): + # Here we prepare a batch of 2 table-question pairs to test TAPAS inference on: + data = { + "Footballer": ["Lionel Messi", "Cristiano Ronaldo"], + "Age": ["33", "35"], + "Number of goals": ["712", "750"], + } + queries = ["Which footballer is 33 years old?", "How many goals does Ronaldo have?"] + table = pd.DataFrame.from_dict(data) + + return table, queries + + +def prepare_tapas_batch_inputs_for_training(): + # Here we prepare a DIFFERENT batch of 2 table-question pairs to test TAPAS training on: + data = { + "Footballer": ["Lionel Messi", "Cristiano Ronaldo"], + "Age": ["33", "35"], + "Number of goals": ["712", "750"], + } + queries = ["Which footballer is 33 years old?", "What's the total number of goals?"] + table = pd.DataFrame.from_dict(data) + + answer_coordinates = [[(0, 0)], [(0, 2), (1, 2)]] + answer_text = [["Lionel Messi"], ["1462"]] + float_answer = [float("NaN"), float("1462")] + + return table, queries, answer_coordinates, answer_text, float_answer + + +@unittest.skipIf(not is_torch_greater_or_equal_than_1_12, reason="Tapas is only available in torch v1.12+") +@require_torch +class TapasModelIntegrationTest(unittest.TestCase): + @cached_property + def default_tokenizer(self): + return TapasTokenizer.from_pretrained("google/tapas-base-finetuned-wtq") + + @slow + def test_inference_no_head(self): + # ideally we want to test this with the weights of tapas_inter_masklm_base_reset, + # but since it's not straightforward to do this with the TF 1 implementation, we test it with + # the weights of the WTQ base model (i.e. tapas_wtq_wikisql_sqa_inter_masklm_base_reset) + model = TapasModel.from_pretrained("google/tapas-base-finetuned-wtq").to(torch_device) + + tokenizer = self.default_tokenizer + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="pt") + inputs = {k: v.to(torch_device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + # test the sequence output + expected_slice = torch.tensor( + [ + [ + [-0.141581565, -0.599805772, 0.747186482], + [-0.143664181, -0.602008104, 0.749218345], + [-0.15169853, -0.603363097, 0.741370678], + ] + ], + device=torch_device, + ) + + self.assertTrue(torch.allclose(outputs.last_hidden_state[:, :3, :3], expected_slice, atol=0.0005)) + + # test the pooled output + expected_slice = torch.tensor([[0.987518311, -0.970520139, -0.994303405]], device=torch_device) + + self.assertTrue(torch.allclose(outputs.pooler_output[:, :3], expected_slice, atol=0.0005)) + + @unittest.skip(reason="Model not available yet") + def test_inference_masked_lm(self): + pass + + # TapasForQuestionAnswering has 3 possible ways of being fine-tuned: + # - conversational set-up (SQA) + # - weak supervision for aggregation (WTQ, WikiSQL) + # - strong supervision for aggregation (WikiSQL-supervised) + # We test all of them: + @slow + def test_inference_question_answering_head_conversational(self): + # note that google/tapas-base-finetuned-sqa should correspond to tapas_sqa_inter_masklm_base_reset + model = TapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-sqa").to(torch_device) + + tokenizer = self.default_tokenizer + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="pt") + inputs = {k: v.to(torch_device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + # test the logits + logits = outputs.logits + expected_shape = torch.Size((1, 21)) + self.assertEqual(logits.shape, expected_shape) + + expected_tensor = torch.tensor( + [ + [ + -9997.22461, + -9997.22461, + -9997.22461, + -9997.22461, + -9997.22461, + -9997.22461, + -9997.22461, + -9997.22461, + -9997.22461, + -16.2628059, + -10004.082, + 15.4330549, + 15.4330549, + 15.4330549, + -9990.42, + -16.3270779, + -16.3270779, + -16.3270779, + -16.3270779, + -16.3270779, + -10004.8506, + ] + ], + device=torch_device, + ) + + self.assertTrue(torch.allclose(logits, expected_tensor, atol=0.015)) + + @slow + def test_inference_question_answering_head_conversational_absolute_embeddings(self): + # note that google/tapas-small-finetuned-sqa should correspond to tapas_sqa_inter_masklm_small_reset + # however here we test the version with absolute position embeddings + model = TapasForQuestionAnswering.from_pretrained("google/tapas-small-finetuned-sqa", revision="no_reset").to( + torch_device + ) + + tokenizer = self.default_tokenizer + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="pt") + inputs = {k: v.to(torch_device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + # test the logits + logits = outputs.logits + expected_shape = torch.Size((1, 21)) + self.assertEqual(logits.shape, expected_shape) + + expected_tensor = torch.tensor( + [ + [ + -10014.7793, + -10014.7793, + -10014.7793, + -10014.7793, + -10014.7793, + -10014.7793, + -10014.7793, + -10014.7793, + -10014.7793, + -18.8419304, + -10018.0391, + 17.7848816, + 17.7848816, + 17.7848816, + -9981.02832, + -16.4005489, + -16.4005489, + -16.4005489, + -16.4005489, + -16.4005489, + -10013.4736, + ] + ], + device=torch_device, + ) + + self.assertTrue(torch.allclose(logits, expected_tensor, atol=0.01)) + + @slow + def test_inference_question_answering_head_weak_supervision(self): + # note that google/tapas-base-finetuned-wtq should correspond to tapas_wtq_wikisql_sqa_inter_masklm_base_reset + model = TapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq").to(torch_device) + + tokenizer = self.default_tokenizer + # let's test on a batch + table, queries = prepare_tapas_batch_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, padding="longest", return_tensors="pt") + inputs_on_device = {k: v.to(torch_device) for k, v in inputs.items()} + + with torch.no_grad(): + outputs = model(**inputs_on_device) + # test the logits + logits = outputs.logits + expected_shape = torch.Size((2, 28)) + self.assertEqual(logits.shape, expected_shape) + + expected_slice = torch.tensor( + [ + [-160.375504, -160.375504, -160.375504, -10072.3965, -10070.9414, -10094.9736], + [-9861.6123, -9861.6123, -9861.6123, -9861.6123, -9891.01172, 146.600677], + ], + device=torch_device, + ) + + self.assertTrue(torch.allclose(logits[:, -6:], expected_slice, atol=0.4)) + + # test the aggregation logits + logits_aggregation = outputs.logits_aggregation + expected_shape = torch.Size((2, 4)) + self.assertEqual(logits_aggregation.shape, expected_shape) + expected_tensor = torch.tensor( + [[18.8545208, -9.76614857, -6.3128891, -2.93525243], [-4.05782509, 40.0351, -5.35329962, 23.3978653]], + device=torch_device, + ) + + self.assertTrue(torch.allclose(logits_aggregation, expected_tensor, atol=0.001)) + + # test the predicted answer coordinates and aggregation indices + EXPECTED_PREDICTED_ANSWER_COORDINATES = [[(0, 0)], [(1, 2)]] + EXPECTED_PREDICTED_AGGREGATION_INDICES = [0, 1] + + predicted_answer_coordinates, predicted_aggregation_indices = tokenizer.convert_logits_to_predictions( + inputs, outputs.logits.detach().cpu(), outputs.logits_aggregation.detach().cpu() + ) + + self.assertEqual(EXPECTED_PREDICTED_ANSWER_COORDINATES, predicted_answer_coordinates) + self.assertEqual(EXPECTED_PREDICTED_AGGREGATION_INDICES, predicted_aggregation_indices) + + @slow + def test_training_question_answering_head_weak_supervision(self): + # note that google/tapas-base-finetuned-wtq should correspond to tapas_wtq_wikisql_sqa_inter_masklm_base_reset + model = TapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq").to(torch_device) + model.to(torch_device) + # normally we should put the model in training mode but it's a pain to do this with the TF 1 implementation + + tokenizer = self.default_tokenizer + # let's test on a batch + table, queries, answer_coordinates, answer_text, float_answer = prepare_tapas_batch_inputs_for_training() + inputs = tokenizer( + table=table, + queries=queries, + answer_coordinates=answer_coordinates, + answer_text=answer_text, + padding="longest", + return_tensors="pt", + ) + + # prepare data (created by the tokenizer) and move to torch_device + input_ids = inputs["input_ids"].to(torch_device) + attention_mask = inputs["attention_mask"].to(torch_device) + token_type_ids = inputs["token_type_ids"].to(torch_device) + labels = inputs["labels"].to(torch_device) + numeric_values = inputs["numeric_values"].to(torch_device) + numeric_values_scale = inputs["numeric_values_scale"].to(torch_device) + + # the answer should be prepared by the user + float_answer = torch.FloatTensor(float_answer).to(torch_device) + + # forward pass to get loss + logits: + with torch.no_grad(): + outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + labels=labels, + numeric_values=numeric_values, + numeric_values_scale=numeric_values_scale, + float_answer=float_answer, + ) + + # test the loss + loss = outputs.loss + expected_loss = torch.tensor(3.3527612686157227e-08, device=torch_device) + self.assertTrue(torch.allclose(loss, expected_loss, atol=1e-6)) + + # test the logits on the first example + logits = outputs.logits + expected_shape = torch.Size((2, 29)) + self.assertEqual(logits.shape, expected_shape) + expected_slice = torch.tensor( + [ + -160.0156, + -160.0156, + -160.0156, + -160.0156, + -160.0156, + -10072.2266, + -10070.8896, + -10092.6006, + -10092.6006, + ], + device=torch_device, + ) + + self.assertTrue(torch.allclose(logits[0, -9:], expected_slice, atol=1e-6)) + + # test the aggregation logits on the second example + logits_aggregation = outputs.logits_aggregation + expected_shape = torch.Size((2, 4)) + self.assertEqual(logits_aggregation.shape, expected_shape) + expected_slice = torch.tensor([-4.0538, 40.0304, -5.3554, 23.3965], device=torch_device) + + self.assertTrue(torch.allclose(logits_aggregation[1, -4:], expected_slice, atol=1e-4)) + + @slow + def test_inference_question_answering_head_strong_supervision(self): + # note that google/tapas-base-finetuned-wikisql-supervised should correspond to tapas_wikisql_sqa_inter_masklm_base_reset + model = TapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wikisql-supervised").to( + torch_device + ) + + tokenizer = self.default_tokenizer + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="pt") + inputs = {k: v.to(torch_device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + # test the logits + logits = outputs.logits + expected_shape = torch.Size((1, 21)) + self.assertEqual(logits.shape, expected_shape) + expected_tensor = torch.tensor( + [ + [ + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -18.6185989, + -10008.7969, + 17.6355762, + 17.6355762, + 17.6355762, + -10002.4404, + -18.7111301, + -18.7111301, + -18.7111301, + -18.7111301, + -18.7111301, + -10007.0977, + ] + ], + device=torch_device, + ) + + self.assertTrue(torch.allclose(logits, expected_tensor, atol=0.02)) + + # test the aggregation logits + logits_aggregation = outputs.logits_aggregation + expected_shape = torch.Size((1, 4)) + self.assertEqual(logits_aggregation.shape, expected_shape) + expected_tensor = torch.tensor( + [[16.5659733, -3.06624889, -2.34152961, -0.970244825]], device=torch_device + ) # PyTorch model outputs [[16.5679, -3.0668, -2.3442, -0.9674]] + + self.assertTrue(torch.allclose(logits_aggregation, expected_tensor, atol=0.003)) + + @slow + def test_inference_classification_head(self): + # note that google/tapas-base-finetuned-tabfact should correspond to tapas_tabfact_inter_masklm_base_reset + model = TapasForSequenceClassification.from_pretrained("google/tapas-base-finetuned-tabfact").to(torch_device) + + tokenizer = self.default_tokenizer + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, padding="longest", return_tensors="pt") + inputs = {k: v.to(torch_device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + + # test the classification logits + logits = outputs.logits + expected_shape = torch.Size((1, 2)) + self.assertEqual(logits.shape, expected_shape) + expected_tensor = torch.tensor( + [[0.795137286, 9.5572]], device=torch_device + ) # Note that the PyTorch model outputs [[0.8057, 9.5281]] + + self.assertTrue(torch.allclose(outputs.logits, expected_tensor, atol=0.05)) + + +# Below: tests for Tapas utilities which are defined in modeling_tapas.py. +# These are based on segmented_tensor_test.py of the original implementation. +# URL: https://github.com/google-research/tapas/blob/master/tapas/models/segmented_tensor_test.py +@unittest.skipIf(not is_torch_greater_or_equal_than_1_12, reason="Tapas is only available in torch v1.12+") +@require_torch +class TapasUtilitiesTest(unittest.TestCase): + def _prepare_tables(self): + """Prepares two tables, both with three distinct rows. + The first table has two columns: + 1.0, 2.0 | 3.0 + 2.0, 0.0 | 1.0 + 1.0, 3.0 | 4.0 + The second table has three columns: + 1.0 | 2.0 | 3.0 + 2.0 | 0.0 | 1.0 + 1.0 | 3.0 | 4.0 + Returns: + SegmentedTensors with the tables. + """ + values = torch.tensor( + [ + [[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]], + [[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]], + ] + ) + row_index = IndexMap( + indices=torch.tensor( + [ + [[0, 0, 0], [1, 1, 1], [2, 2, 2]], + [[0, 0, 0], [1, 1, 1], [2, 2, 2]], + ] + ), + num_segments=3, + batch_dims=1, + ) + col_index = IndexMap( + indices=torch.tensor( + [ + [[0, 0, 1], [0, 0, 1], [0, 0, 1]], + [[0, 1, 2], [0, 1, 2], [0, 1, 2]], + ] + ), + num_segments=3, + batch_dims=1, + ) + return values, row_index, col_index + + def test_product_index(self): + _, row_index, col_index = self._prepare_tables() + cell_index = ProductIndexMap(row_index, col_index) + row_index_proj = cell_index.project_outer(cell_index) + col_index_proj = cell_index.project_inner(cell_index) + + ind = cell_index.indices + self.assertEqual(cell_index.num_segments, 9) + + # Projections should give back the original indices. + # we use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(row_index.indices.numpy(), row_index_proj.indices.numpy()) + self.assertEqual(row_index.num_segments, row_index_proj.num_segments) + self.assertEqual(row_index.batch_dims, row_index_proj.batch_dims) + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(col_index.indices.numpy(), col_index_proj.indices.numpy()) + self.assertEqual(col_index.batch_dims, col_index_proj.batch_dims) + + # The first and second "column" are identified in the first table. + for i in range(3): + self.assertEqual(ind[0, i, 0], ind[0, i, 1]) + self.assertNotEqual(ind[0, i, 0], ind[0, i, 2]) + + # All rows are distinct in the first table. + for i, i_2 in zip(range(3), range(3)): + for j, j_2 in zip(range(3), range(3)): + if i != i_2 and j != j_2: + self.assertNotEqual(ind[0, i, j], ind[0, i_2, j_2]) + + # All cells are distinct in the second table. + for i, i_2 in zip(range(3), range(3)): + for j, j_2 in zip(range(3), range(3)): + if i != i_2 or j != j_2: + self.assertNotEqual(ind[1, i, j], ind[1, i_2, j_2]) + + def test_flatten(self): + _, row_index, col_index = self._prepare_tables() + row_index_flat = flatten(row_index) + col_index_flat = flatten(col_index) + + shape = [3, 4, 5] + batched_index = IndexMap(indices=torch.zeros(shape).type(torch.LongTensor), num_segments=1, batch_dims=3) + batched_index_flat = flatten(batched_index) + + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal( + row_index_flat.indices.numpy(), [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5] + ) + np.testing.assert_array_equal( + col_index_flat.indices.numpy(), [0, 0, 1, 0, 0, 1, 0, 0, 1, 3, 4, 5, 3, 4, 5, 3, 4, 5] + ) + self.assertEqual(batched_index_flat.num_segments.numpy(), np.prod(shape)) + np.testing.assert_array_equal(batched_index_flat.indices.numpy(), range(np.prod(shape))) + + def test_range_index_map(self): + batch_shape = [3, 4] + num_segments = 5 + index = range_index_map(batch_shape, num_segments) + + self.assertEqual(num_segments, index.num_segments) + self.assertEqual(2, index.batch_dims) + indices = index.indices + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(list(indices.size()), [3, 4, 5]) + for i in range(batch_shape[0]): + for j in range(batch_shape[1]): + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(indices[i, j, :].numpy(), range(num_segments)) + + def test_reduce_sum(self): + values, row_index, col_index = self._prepare_tables() + cell_index = ProductIndexMap(row_index, col_index) + row_sum, _ = reduce_sum(values, row_index) + col_sum, _ = reduce_sum(values, col_index) + cell_sum, _ = reduce_sum(values, cell_index) + + # We use np.testing.assert_allclose rather than Tensorflow's assertAllClose + np.testing.assert_allclose(row_sum.numpy(), [[6.0, 3.0, 8.0], [6.0, 3.0, 8.0]]) + np.testing.assert_allclose(col_sum.numpy(), [[9.0, 8.0, 0.0], [4.0, 5.0, 8.0]]) + np.testing.assert_allclose( + cell_sum.numpy(), + [[3.0, 3.0, 0.0, 2.0, 1.0, 0.0, 4.0, 4.0, 0.0], [1.0, 2.0, 3.0, 2.0, 0.0, 1.0, 1.0, 3.0, 4.0]], + ) + + def test_reduce_mean(self): + values, row_index, col_index = self._prepare_tables() + cell_index = ProductIndexMap(row_index, col_index) + row_mean, _ = reduce_mean(values, row_index) + col_mean, _ = reduce_mean(values, col_index) + cell_mean, _ = reduce_mean(values, cell_index) + + # We use np.testing.assert_allclose rather than Tensorflow's assertAllClose + np.testing.assert_allclose( + row_mean.numpy(), [[6.0 / 3.0, 3.0 / 3.0, 8.0 / 3.0], [6.0 / 3.0, 3.0 / 3.0, 8.0 / 3.0]] + ) + np.testing.assert_allclose(col_mean.numpy(), [[9.0 / 6.0, 8.0 / 3.0, 0.0], [4.0 / 3.0, 5.0 / 3.0, 8.0 / 3.0]]) + np.testing.assert_allclose( + cell_mean.numpy(), + [ + [3.0 / 2.0, 3.0, 0.0, 2.0 / 2.0, 1.0, 0.0, 4.0 / 2.0, 4.0, 0.0], + [1.0, 2.0, 3.0, 2.0, 0.0, 1.0, 1.0, 3.0, 4.0], + ], + ) + + def test_reduce_max(self): + values = torch.as_tensor([2.0, 1.0, 0.0, 3.0]) + index = IndexMap(indices=torch.as_tensor([0, 1, 0, 1]), num_segments=2) + maximum, _ = reduce_max(values, index) + + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(maximum.numpy(), [2, 3]) + + def test_reduce_sum_vectorized(self): + values = torch.as_tensor([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0], [3.0, 4.0, 5.0]]) + index = IndexMap(indices=torch.as_tensor([[0, 0, 1]]), num_segments=2, batch_dims=0) + sums, new_index = reduce_sum(values, index) + + # We use np.testing.assert_allclose rather than Tensorflow's assertAllClose + np.testing.assert_allclose(sums.numpy(), [3.0, 3.0]) + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(new_index.indices.numpy(), [0, 1]) + np.testing.assert_array_equal(new_index.num_segments.numpy(), 2) + np.testing.assert_array_equal(new_index.batch_dims, 0) + + def test_gather(self): + values, row_index, col_index = self._prepare_tables() + cell_index = ProductIndexMap(row_index, col_index) + + # Compute sums and then gather. The result should have the same shape as + # the original table and each element should contain the sum the values in + # its cell. + sums, _ = reduce_sum(values, cell_index) + cell_sum = gather(sums, cell_index) + assert cell_sum.size() == values.size() + + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_allclose( + cell_sum.numpy(), + [[[3.0, 3.0, 3.0], [2.0, 2.0, 1.0], [4.0, 4.0, 4.0]], [[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]]], + ) + + def test_gather_vectorized(self): + values = torch.as_tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) + index = IndexMap(indices=torch.as_tensor([[0, 1], [1, 0]]), num_segments=2, batch_dims=1) + result = gather(values, index) + + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(result.numpy(), [[[1, 2], [3, 4]], [[7, 8], [5, 6]]]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_modeling_tf_tapas.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_modeling_tf_tapas.py new file mode 100644 index 0000000000000000000000000000000000000000..7687144eaf2f9d2f031e9861cb2beb1313549d2b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_modeling_tf_tapas.py @@ -0,0 +1,1066 @@ +# coding=utf-8 +# 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. + +from __future__ import annotations + +import copy +import unittest + +import numpy as np +import pandas as pd + +from transformers import ( + TF_MODEL_FOR_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_MASKED_LM_MAPPING, + TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, + TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, + TF_MODEL_FOR_PRETRAINING_MAPPING, + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING, + TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + TapasConfig, + TapasTokenizer, + is_tf_available, +) +from transformers.models.auto import get_values +from transformers.testing_utils import require_tensorflow_probability, require_tf, slow +from transformers.utils import cached_property + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import ( + TFTapasForMaskedLM, + TFTapasForQuestionAnswering, + TFTapasForSequenceClassification, + TFTapasModel, + ) + from transformers.models.tapas.modeling_tf_tapas import ( + IndexMap, + ProductIndexMap, + flatten, + gather, + range_index_map, + reduce_max, + reduce_mean, + reduce_sum, + ) + + +class TFTapasModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + initializer_range=0.02, + max_position_embeddings=512, + type_vocab_sizes=[3, 256, 256, 2, 256, 256, 10], + type_sequence_label_size=2, + positive_weight=10.0, + num_aggregation_labels=4, + num_labels=2, + aggregation_loss_importance=0.8, + use_answer_as_supervision=True, + answer_loss_importance=0.001, + use_normalized_answer_loss=False, + huber_loss_delta=25.0, + temperature=1.0, + agg_temperature=1.0, + use_gumbel_for_cells=False, + use_gumbel_for_agg=False, + average_approximation_function="ratio", + cell_selection_preference=0.5, + answer_loss_cutoff=100, + max_num_rows=64, + max_num_columns=32, + average_logits_per_cell=True, + select_one_column=True, + allow_empty_column_selection=False, + init_cell_selection_weights_to_zero=True, + reset_position_index_per_cell=True, + disable_per_token_loss=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.initializer_range = initializer_range + self.max_position_embeddings = max_position_embeddings + self.type_vocab_sizes = type_vocab_sizes + self.type_sequence_label_size = type_sequence_label_size + self.positive_weight = positive_weight + self.num_aggregation_labels = num_aggregation_labels + self.num_labels = num_labels + self.aggregation_loss_importance = aggregation_loss_importance + self.use_answer_as_supervision = use_answer_as_supervision + self.answer_loss_importance = answer_loss_importance + self.use_normalized_answer_loss = use_normalized_answer_loss + self.huber_loss_delta = huber_loss_delta + self.temperature = temperature + self.agg_temperature = agg_temperature + self.use_gumbel_for_cells = use_gumbel_for_cells + self.use_gumbel_for_agg = use_gumbel_for_agg + self.average_approximation_function = average_approximation_function + self.cell_selection_preference = cell_selection_preference + self.answer_loss_cutoff = answer_loss_cutoff + self.max_num_rows = max_num_rows + self.max_num_columns = max_num_columns + self.average_logits_per_cell = average_logits_per_cell + self.select_one_column = select_one_column + self.allow_empty_column_selection = allow_empty_column_selection + self.init_cell_selection_weights_to_zero = init_cell_selection_weights_to_zero + self.reset_position_index_per_cell = reset_position_index_per_cell + self.disable_per_token_loss = disable_per_token_loss + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = [] + for type_vocab_size in self.type_vocab_sizes: + token_type_ids.append(ids_tensor(shape=[self.batch_size, self.seq_length], vocab_size=type_vocab_size)) + token_type_ids = tf.stack(token_type_ids, axis=2) + + sequence_labels = None + token_labels = None + labels = None + numeric_values = None + numeric_values_scale = None + float_answer = None + aggregation_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + labels = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + numeric_values = ids_tensor([self.batch_size, self.seq_length], vocab_size=2, dtype=tf.float32) + numeric_values_scale = ids_tensor([self.batch_size, self.seq_length], vocab_size=2, dtype=tf.float32) + float_answer = ids_tensor([self.batch_size], vocab_size=2, dtype=tf.float32) + aggregation_labels = ids_tensor([self.batch_size], self.num_aggregation_labels) + + config = self.get_config() + + return ( + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ) + + def get_config(self): + return TapasConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_sizes=self.type_vocab_sizes, + initializer_range=self.initializer_range, + positive_weight=self.positive_weight, + num_aggregation_labels=self.num_aggregation_labels, + num_labels=self.num_labels, + aggregation_loss_importance=self.aggregation_loss_importance, + use_answer_as_supervision=self.use_answer_as_supervision, + answer_loss_importance=self.answer_loss_importance, + use_normalized_answer_loss=self.use_normalized_answer_loss, + huber_loss_delta=self.huber_loss_delta, + temperature=self.temperature, + agg_temperature=self.agg_temperature, + use_gumbel_for_cells=self.use_gumbel_for_cells, + use_gumbel_for_agg=self.use_gumbel_for_agg, + average_approximation_function=self.average_approximation_function, + cell_selection_preference=self.cell_selection_preference, + answer_loss_cutoff=self.answer_loss_cutoff, + max_num_rows=self.max_num_rows, + max_num_columns=self.max_num_columns, + average_logits_per_cell=self.average_logits_per_cell, + select_one_column=self.select_one_column, + allow_empty_column_selection=self.allow_empty_column_selection, + init_cell_selection_weights_to_zero=self.init_cell_selection_weights_to_zero, + reset_position_index_per_cell=self.reset_position_index_per_cell, + disable_per_token_loss=self.disable_per_token_loss, + ) + + def create_and_check_model( + self, + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ): + model = TFTapasModel(config=config) + + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + result = model(inputs) + inputs.pop("attention_mask") + result = model(inputs) + inputs.pop("token_type_ids") + result = model(inputs) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_for_masked_lm( + self, + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ): + model = TFTapasForMaskedLM(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "labels": token_labels, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_sequence_classification( + self, + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ): + config.num_labels = self.num_labels + model = TFTapasForSequenceClassification(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "labels": sequence_labels, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_question_answering( + self, + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ): + # inference: without aggregation head (SQA). Model only returns logits + sqa_config = copy.copy(config) + sqa_config.num_aggregation_labels = 0 + sqa_config.use_answer_as_supervision = False + model = TFTapasForQuestionAnswering(config=sqa_config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + + # inference: with aggregation head (WTQ, WikiSQL-supervised). Model returns logits and aggregation logits + model = TFTapasForQuestionAnswering(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.logits_aggregation.shape, (self.batch_size, self.num_aggregation_labels)) + + # training: can happen in 3 main ways + # case 1: conversational (SQA) + model = TFTapasForQuestionAnswering(config=sqa_config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "labels": labels, + } + result = model(inputs) + self.parent.assertEqual(result.loss.shape, (1,)) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + + # case 2: weak supervision for aggregation (WTQ) + model = TFTapasForQuestionAnswering(config=config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "labels": labels, + "numeric_values": numeric_values, + "numeric_values_scale": numeric_values_scale, + "float_answer": float_answer, + } + result = model(inputs) + self.parent.assertEqual(result.loss.shape, (1,)) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.logits_aggregation.shape, (self.batch_size, self.num_aggregation_labels)) + + # case 3: strong supervision for aggregation (WikiSQL-supervised) + wikisql_config = copy.copy(config) + wikisql_config.use_answer_as_supervision = False + model = TFTapasForQuestionAnswering(config=wikisql_config) + inputs = { + "input_ids": input_ids, + "attention_mask": input_mask, + "token_type_ids": token_type_ids, + "labels": labels, + "aggregation_labels": aggregation_labels, + } + result = model(inputs) + self.parent.assertEqual(result.loss.shape, (1,)) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.logits_aggregation.shape, (self.batch_size, self.num_aggregation_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + input_mask, + token_type_ids, + sequence_labels, + token_labels, + labels, + numeric_values, + numeric_values_scale, + float_answer, + aggregation_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_tensorflow_probability +@require_tf +class TFTapasModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TFTapasModel, + TFTapasForMaskedLM, + TFTapasForSequenceClassification, + TFTapasForQuestionAnswering, + ) + if is_tf_available() + else () + ) + pipeline_model_mapping = ( + { + "feature-extraction": TFTapasModel, + "fill-mask": TFTapasForMaskedLM, + "text-classification": TFTapasForSequenceClassification, + "zero-shot": TFTapasForSequenceClassification, + } + if is_tf_available() + else {} + ) + test_head_masking = False + test_onnx = False + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + return True + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False) -> dict: + inputs_dict = copy.deepcopy(inputs_dict) + + if model_class in get_values(TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING): + inputs_dict = { + k: tf.tile(tf.expand_dims(v, 1), (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)) + if isinstance(v, tf.Tensor) and v.ndim > 0 + else v + for k, v in inputs_dict.items() + } + + if return_labels: + if model_class in get_values(TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING): + inputs_dict["labels"] = tf.ones(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in get_values(TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING): + inputs_dict["labels"] = tf.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=tf.int32 + ) + inputs_dict["aggregation_labels"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + inputs_dict["numeric_values"] = tf.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=tf.float32 + ) + inputs_dict["numeric_values_scale"] = tf.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=tf.float32 + ) + inputs_dict["float_answer"] = tf.zeros(self.model_tester.batch_size, dtype=tf.float32) + elif model_class in get_values(TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING): + inputs_dict["labels"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in get_values(TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING): + inputs_dict["next_sentence_label"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in [ + *get_values(TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING), + *get_values(TF_MODEL_FOR_CAUSAL_LM_MAPPING), + *get_values(TF_MODEL_FOR_MASKED_LM_MAPPING), + *get_values(TF_MODEL_FOR_PRETRAINING_MAPPING), + *get_values(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING), + ]: + inputs_dict["labels"] = tf.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=tf.int32 + ) + return inputs_dict + + def setUp(self): + self.model_tester = TFTapasModelTester(self) + self.config_tester = ConfigTester(self, config_class=TapasConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + @unittest.skip(reason="The default test gets NaN losses with the test-generated inputs") + def test_dataset_conversion(self): + pass + + @unittest.skip(reason="The default test gets NaN losses with the test-generated inputs") + def test_keras_fit(self): + pass + + @unittest.skip(reason="The default test gets NaN losses with the test-generated inputs") + def test_loss_computation(self): + pass + + +def prepare_tapas_single_inputs_for_inference(): + # Here we prepare a single table-question pair to test TAPAS inference on: + data = { + "Footballer": ["Lionel Messi", "Cristiano Ronaldo"], + "Age": ["33", "35"], + } + queries = "Which footballer is 33 years old?" + table = pd.DataFrame.from_dict(data) + + return table, queries + + +def prepare_tapas_batch_inputs_for_inference(): + # Here we prepare a batch of 2 table-question pairs to test TAPAS inference on: + data = { + "Footballer": ["Lionel Messi", "Cristiano Ronaldo"], + "Age": ["33", "35"], + "Number of goals": ["712", "750"], + } + queries = ["Which footballer is 33 years old?", "How many goals does Ronaldo have?"] + table = pd.DataFrame.from_dict(data) + + return table, queries + + +def prepare_tapas_batch_inputs_for_training(): + # Here we prepare a DIFFERENT batch of 2 table-question pairs to test TAPAS training on: + data = { + "Footballer": ["Lionel Messi", "Cristiano Ronaldo"], + "Age": ["33", "35"], + "Number of goals": ["712", "750"], + } + queries = ["Which footballer is 33 years old?", "What's the total number of goals?"] + table = pd.DataFrame.from_dict(data) + + answer_coordinates = [[(0, 0)], [(0, 2), (1, 2)]] + answer_text = [["Lionel Messi"], ["1462"]] + float_answer = [float("NaN"), float("1462")] + + return table, queries, answer_coordinates, answer_text, float_answer + + +@require_tensorflow_probability +@require_tf +class TFTapasModelIntegrationTest(unittest.TestCase): + @cached_property + def default_tokenizer(self): + return TapasTokenizer.from_pretrained("google/tapas-base-finetuned-wtq") + + @slow + def test_inference_no_head(self): + # ideally we want to test this with the weights of tapas_inter_masklm_base_reset, + # but since it's not straightforward to do this with the TF 1 implementation, we test it with + # the weights of the WTQ base model (i.e. tapas_wtq_wikisql_sqa_inter_masklm_base_reset) + model = TFTapasModel.from_pretrained("google/tapas-base-finetuned-wtq") + tokenizer = self.default_tokenizer + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="tf") + outputs = model(**inputs) + + # test the sequence output + expected_slice = tf.constant( + [ + [ + [-0.141581565, -0.599805772, 0.747186482], + [-0.143664181, -0.602008104, 0.749218345], + [-0.15169853, -0.603363097, 0.741370678], + ] + ] + ) + tf.debugging.assert_near(outputs.last_hidden_state[:, :3, :3], expected_slice, atol=0.0005) + + # test the pooled output + expected_slice = tf.constant([[0.987518311, -0.970520139, -0.994303405]]) + + tf.debugging.assert_near(outputs.pooler_output[:, :3], expected_slice, atol=0.0005) + + @unittest.skip(reason="Model not available yet") + def test_inference_masked_lm(self): + pass + + # TapasForQuestionAnswering has 3 possible ways of being fine-tuned: + # - conversational set-up (SQA) + # - weak supervision for aggregation (WTQ, WikiSQL) + # - strong supervision for aggregation (WikiSQL-supervised) + # We test all of them: + @slow + def test_inference_question_answering_head_conversational(self): + # note that google/tapas-base-finetuned-sqa should correspond to tapas_sqa_inter_masklm_base_reset + model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-sqa") + tokenizer = self.default_tokenizer + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="tf") + outputs = model(**inputs) + + # test the logits + logits = outputs.logits + expected_shape = tf.TensorShape([1, 21]) + tf.debugging.assert_equal(logits.shape, expected_shape) + + expected_slice = tf.constant( + [ + [ + -9997.274, + -9997.274, + -9997.274, + -9997.274, + -9997.274, + -9997.274, + -9997.274, + -9997.274, + -9997.274, + -16.262585, + -10004.089, + 15.435196, + 15.435196, + 15.435196, + -9990.443, + -16.327433, + -16.327433, + -16.327433, + -16.327433, + -16.327433, + -10004.84, + ] + ] + ) + + tf.debugging.assert_near(logits, expected_slice, atol=0.015) + + @slow + def test_inference_question_answering_head_conversational_absolute_embeddings(self): + # note that google/tapas-small-finetuned-sqa should correspond to tapas_sqa_inter_masklm_small_reset + # however here we test the version with absolute position embeddings + model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-small-finetuned-sqa") + tokenizer = self.default_tokenizer + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="tf") + outputs = model(**inputs) + + # test the logits + logits = outputs.logits + expected_shape = tf.TensorShape([1, 21]) + tf.debugging.assert_equal(logits.shape, expected_shape) + + expected_slice = tf.constant( + [ + [ + -10000.041, + -10000.041, + -10000.041, + -10000.041, + -10000.041, + -10000.041, + -10000.041, + -10000.041, + -10000.041, + -18.369339, + -10014.692, + 17.730324, + 17.730324, + 17.730324, + -9984.974, + -18.322773, + -18.322773, + -18.322773, + -18.322773, + -18.322773, + -10007.267, + ] + ] + ) + + tf.debugging.assert_near(logits, expected_slice, atol=0.01) + + @slow + def test_inference_question_answering_head_weak_supervision(self): + # note that google/tapas-base-finetuned-wtq should correspond to tapas_wtq_wikisql_sqa_inter_masklm_base_reset + model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq") + + tokenizer = self.default_tokenizer + # let's test on a batch + table, queries = prepare_tapas_batch_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, padding="longest", return_tensors="tf") + outputs = model(**inputs) + + # test the logits + logits = outputs.logits + expected_shape = tf.TensorShape([2, 28]) + tf.debugging.assert_equal(logits.shape, expected_shape) + + expected_slice = tf.constant( + [ + [-160.375504, -160.375504, -160.375504, -10072.3965, -10070.9414, -10094.9736], + [-9861.6123, -9861.6123, -9861.6123, -9861.6123, -9891.01172, 146.600677], + ] + ) + + tf.debugging.assert_near(logits[:, -6:], expected_slice, atol=0.4) + + # test the aggregation logits + logits_aggregation = outputs.logits_aggregation + expected_shape = tf.TensorShape([2, 4]) + tf.debugging.assert_equal(logits_aggregation.shape, expected_shape) + expected_tensor = tf.constant( + [[18.8545208, -9.76614857, -6.3128891, -2.93525243], [-4.05782509, 40.0351, -5.35329962, 23.3978653]] + ) + tf.debugging.assert_near(logits_aggregation, expected_tensor, atol=0.001) + + # test the predicted answer coordinates and aggregation indices + EXPECTED_PREDICTED_ANSWER_COORDINATES = [[(0, 0)], [(1, 2)]] + EXPECTED_PREDICTED_AGGREGATION_INDICES = [0, 1] + + predicted_answer_coordinates, predicted_aggregation_indices = tokenizer.convert_logits_to_predictions( + inputs, outputs.logits, outputs.logits_aggregation + ) + tf.debugging.assert_equal(EXPECTED_PREDICTED_ANSWER_COORDINATES, predicted_answer_coordinates) + tf.debugging.assert_equal(EXPECTED_PREDICTED_AGGREGATION_INDICES, predicted_aggregation_indices) + + @slow + def test_training_question_answering_head_weak_supervision(self): + # note that google/tapas-base-finetuned-wtq should correspond to tapas_wtq_wikisql_sqa_inter_masklm_base_reset + model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq") + tokenizer = self.default_tokenizer + # let's test on a batch + table, queries, answer_coordinates, answer_text, float_answer = prepare_tapas_batch_inputs_for_training() + inputs = tokenizer( + table=table, + queries=queries, + answer_coordinates=answer_coordinates, + answer_text=answer_text, + padding="longest", + return_tensors="tf", + ) + # the answer should be prepared by the user + float_answer = tf.constant(float_answer, dtype=tf.float32) + outputs = model( + input_ids=inputs["input_ids"], + attention_mask=inputs["attention_mask"], + token_type_ids=inputs["token_type_ids"], + labels=inputs["labels"], + numeric_values=inputs["numeric_values"], + numeric_values_scale=inputs["numeric_values_scale"], + float_answer=float_answer, + ) + + # test the loss + loss = outputs.loss + expected_loss = tf.constant(3.3527612686157227e-08) + tf.debugging.assert_near(loss, expected_loss, atol=1e-6) + + # test the logits on the first example + logits = outputs.logits + expected_shape = tf.TensorShape([2, 29]) + tf.debugging.assert_equal(logits.shape, expected_shape) + expected_slice = tf.constant( + [ + -160.0156, + -160.0156, + -160.0156, + -160.0156, + -160.0156, + -10072.2266, + -10070.8896, + -10092.6006, + -10092.6006, + ] + ) + tf.debugging.assert_near(logits[0, -9:], expected_slice, atol=1e-6) + + # test the aggregation logits on the second example + logits_aggregation = outputs.logits_aggregation + expected_shape = tf.TensorShape([2, 4]) + tf.debugging.assert_equal(logits_aggregation.shape, expected_shape) + expected_tensor = tf.constant([-4.0538, 40.0304, -5.3554, 23.3965]) + tf.debugging.assert_near(logits_aggregation[1, -4:], expected_tensor, atol=1e-4) + + @slow + def test_inference_question_answering_head_strong_supervision(self): + # note that google/tapas-base-finetuned-wikisql-supervised should correspond to tapas_wikisql_sqa_inter_masklm_base_reset + model = TFTapasForQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wikisql-supervised") + tokenizer = self.default_tokenizer + + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="tf") + outputs = model(**inputs) + + # test the logits + logits = outputs.logits + expected_shape = tf.TensorShape([1, 21]) + tf.debugging.assert_equal(logits.shape, expected_shape) + expected_slice = tf.constant( + [ + [ + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -10011.1084, + -18.6185989, + -10008.7969, + 17.6355762, + 17.6355762, + 17.6355762, + -10002.4404, + -18.7111301, + -18.7111301, + -18.7111301, + -18.7111301, + -18.7111301, + -10007.0977, + ] + ] + ) + tf.debugging.assert_near(logits, expected_slice, atol=0.02) + + # test the aggregation logits + logits_aggregation = outputs.logits_aggregation + expected_shape = tf.TensorShape([1, 4]) + tf.debugging.assert_equal(logits_aggregation.shape, expected_shape) + expected_tensor = tf.constant([[16.5659733, -3.06624889, -2.34152961, -0.970244825]]) + tf.debugging.assert_near(logits_aggregation, expected_tensor, atol=0.003) + + @slow + def test_inference_classification_head(self): + # note that google/tapas-base-finetuned-tabfact should correspond to tapas_tabfact_inter_masklm_base_reset + model = TFTapasForSequenceClassification.from_pretrained("google/tapas-base-finetuned-tabfact") + tokenizer = self.default_tokenizer + + table, queries = prepare_tapas_single_inputs_for_inference() + inputs = tokenizer(table=table, queries=queries, return_tensors="tf") + outputs = model(**inputs) + + # test the classification logits + logits = outputs.logits + expected_shape = tf.TensorShape([1, 2]) + tf.debugging.assert_equal(logits.shape, expected_shape) + expected_slice = tf.constant([[0.795137286, 9.5572]]) + tf.debugging.assert_near(logits, expected_slice, atol=0.05) + + +# Below: tests for Tapas utilities which are defined in modeling_tf_tapas.py. +# These are based on segmented_tensor_test.py of the original implementation. +# URL: https://github.com/google-research/tapas/blob/master/tapas/models/segmented_tensor_test.py +@require_tensorflow_probability +class TFTapasUtilsTest(unittest.TestCase): + def _prepare_tables(self): + """Prepares two tables, both with three distinct rows. + The first table has two columns: + 1.0, 2.0 | 3.0 + 2.0, 0.0 | 1.0 + 1.0, 3.0 | 4.0 + The second table has three columns: + 1.0 | 2.0 | 3.0 + 2.0 | 0.0 | 1.0 + 1.0 | 3.0 | 4.0 + Returns: + SegmentedTensors with the tables. + """ + values = tf.constant( + [ + [[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]], + [[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]], + ] + ) + row_index = IndexMap( + indices=[ + [[0, 0, 0], [1, 1, 1], [2, 2, 2]], + [[0, 0, 0], [1, 1, 1], [2, 2, 2]], + ], + num_segments=3, + batch_dims=1, + ) + col_index = IndexMap( + indices=[ + [[0, 0, 1], [0, 0, 1], [0, 0, 1]], + [[0, 1, 2], [0, 1, 2], [0, 1, 2]], + ], + num_segments=3, + batch_dims=1, + ) + return values, row_index, col_index + + def test_product_index(self): + _, row_index, col_index = self._prepare_tables() + cell_index = ProductIndexMap(row_index, col_index) + row_index_proj = cell_index.project_outer(cell_index) + col_index_proj = cell_index.project_inner(cell_index) + + ind = cell_index.indices + self.assertEqual(cell_index.num_segments, 9) + + # Projections should give back the original indices. + # we use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(row_index.indices.numpy(), row_index_proj.indices.numpy()) + self.assertEqual(row_index.num_segments, row_index_proj.num_segments) + self.assertEqual(row_index.batch_dims, row_index_proj.batch_dims) + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(col_index.indices.numpy(), col_index_proj.indices.numpy()) + self.assertEqual(col_index.batch_dims, col_index_proj.batch_dims) + + # The first and second "column" are identified in the first table. + for i in range(3): + self.assertEqual(ind[0, i, 0], ind[0, i, 1]) + self.assertNotEqual(ind[0, i, 0], ind[0, i, 2]) + + # All rows are distinct in the first table. + for i, i_2 in zip(range(3), range(3)): + for j, j_2 in zip(range(3), range(3)): + if i != i_2 and j != j_2: + self.assertNotEqual(ind[0, i, j], ind[0, i_2, j_2]) + + # All cells are distinct in the second table. + for i, i_2 in zip(range(3), range(3)): + for j, j_2 in zip(range(3), range(3)): + if i != i_2 or j != j_2: + self.assertNotEqual(ind[1, i, j], ind[1, i_2, j_2]) + + def test_flatten(self): + _, row_index, col_index = self._prepare_tables() + row_index_flat = flatten(row_index) + col_index_flat = flatten(col_index) + + shape = [3, 4, 5] + batched_index = IndexMap(indices=tf.zeros(shape, dtype=tf.int32), num_segments=1, batch_dims=3) + batched_index_flat = flatten(batched_index) + + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal( + row_index_flat.indices.numpy(), [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5] + ) + np.testing.assert_array_equal( + col_index_flat.indices.numpy(), [0, 0, 1, 0, 0, 1, 0, 0, 1, 3, 4, 5, 3, 4, 5, 3, 4, 5] + ) + self.assertEqual(batched_index_flat.num_segments.numpy(), np.prod(shape)) + np.testing.assert_array_equal(batched_index_flat.indices.numpy(), range(np.prod(shape))) + + def test_range_index_map(self): + batch_shape = [3, 4] + num_segments = 5 + index = range_index_map(batch_shape, num_segments) + + self.assertEqual(num_segments, index.num_segments) + self.assertEqual(2, index.batch_dims) + indices = index.indices + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(list(indices.shape), [3, 4, 5]) + for i in range(batch_shape[0]): + for j in range(batch_shape[1]): + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(indices[i, j, :].numpy(), range(num_segments)) + + def test_reduce_sum(self): + values, row_index, col_index = self._prepare_tables() + cell_index = ProductIndexMap(row_index, col_index) + row_sum, _ = reduce_sum(values, row_index) + col_sum, _ = reduce_sum(values, col_index) + cell_sum, _ = reduce_sum(values, cell_index) + + # We use np.testing.assert_allclose rather than Tensorflow's assertAllClose + np.testing.assert_allclose(row_sum.numpy(), [[6.0, 3.0, 8.0], [6.0, 3.0, 8.0]]) + np.testing.assert_allclose(col_sum.numpy(), [[9.0, 8.0, 0.0], [4.0, 5.0, 8.0]]) + np.testing.assert_allclose( + cell_sum.numpy(), + [[3.0, 3.0, 0.0, 2.0, 1.0, 0.0, 4.0, 4.0, 0.0], [1.0, 2.0, 3.0, 2.0, 0.0, 1.0, 1.0, 3.0, 4.0]], + ) + + def test_reduce_mean(self): + values, row_index, col_index = self._prepare_tables() + cell_index = ProductIndexMap(row_index, col_index) + row_mean, _ = reduce_mean(values, row_index) + col_mean, _ = reduce_mean(values, col_index) + cell_mean, _ = reduce_mean(values, cell_index) + + # We use np.testing.assert_allclose rather than Tensorflow's assertAllClose + np.testing.assert_allclose( + row_mean.numpy(), [[6.0 / 3.0, 3.0 / 3.0, 8.0 / 3.0], [6.0 / 3.0, 3.0 / 3.0, 8.0 / 3.0]] + ) + np.testing.assert_allclose(col_mean.numpy(), [[9.0 / 6.0, 8.0 / 3.0, 0.0], [4.0 / 3.0, 5.0 / 3.0, 8.0 / 3.0]]) + np.testing.assert_allclose( + cell_mean.numpy(), + [ + [3.0 / 2.0, 3.0, 0.0, 2.0 / 2.0, 1.0, 0.0, 4.0 / 2.0, 4.0, 0.0], + [1.0, 2.0, 3.0, 2.0, 0.0, 1.0, 1.0, 3.0, 4.0], + ], + ) + + def test_reduce_max(self): + values = tf.convert_to_tensor([2.0, 1.0, 0.0, 3.0]) + index = IndexMap(indices=tf.convert_to_tensor([0, 1, 0, 1]), num_segments=2) + maximum, _ = reduce_max(values, index) + + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(maximum.numpy(), [2, 3]) + + def test_reduce_sum_vectorized(self): + values = tf.convert_to_tensor([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0], [3.0, 4.0, 5.0]]) + index = IndexMap(indices=tf.convert_to_tensor([0, 0, 1]), num_segments=2, batch_dims=0) + sums, new_index = reduce_sum(values, index) + + # We use np.testing.assert_allclose rather than Tensorflow's assertAllClose + np.testing.assert_allclose(sums.numpy(), [[3.0, 5.0, 7.0], [3.0, 4.0, 5.0]]) + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(new_index.indices.numpy(), [0, 1]) + np.testing.assert_array_equal(new_index.num_segments.numpy(), 2) + np.testing.assert_array_equal(new_index.batch_dims, 0) + + def test_gather(self): + values, row_index, col_index = self._prepare_tables() + cell_index = ProductIndexMap(row_index, col_index) + + # Compute sums and then gather. The result should have the same shape as + # the original table and each element should contain the sum the values in + # its cell. + sums, _ = reduce_sum(values, cell_index) + cell_sum = gather(sums, cell_index) + assert cell_sum.shape == values.shape + + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_allclose( + cell_sum.numpy(), + [[[3.0, 3.0, 3.0], [2.0, 2.0, 1.0], [4.0, 4.0, 4.0]], [[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]]], + ) + + def test_gather_vectorized(self): + values = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) + index = IndexMap(indices=tf.convert_to_tensor([[0, 1], [1, 0]]), num_segments=2, batch_dims=1) + result = gather(values, index) + + # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual + np.testing.assert_array_equal(result.numpy(), [[[1, 2], [3, 4]], [[7, 8], [5, 6]]]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_tokenization_tapas.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_tokenization_tapas.py new file mode 100644 index 0000000000000000000000000000000000000000..692dc91b6d88a6046c64cbfb78c50955cd98a67a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tapas/test_tokenization_tapas.py @@ -0,0 +1,1276 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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 os +import shutil +import tempfile +import unittest +from typing import List + +import numpy as np +import pandas as pd + +from transformers import AddedToken, is_torch_available +from transformers.models.tapas.tokenization_tapas import ( + VOCAB_FILES_NAMES, + BasicTokenizer, + TapasTokenizer, + WordpieceTokenizer, + _is_control, + _is_punctuation, + _is_whitespace, +) +from transformers.testing_utils import ( + is_pt_tf_cross_test, + require_pandas, + require_tensorflow_probability, + require_tokenizers, + require_torch, + slow, +) + +from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english, merge_model_tokenizer_mappings + + +if is_torch_available(): + from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_12 +else: + is_torch_greater_or_equal_than_1_12 = False + + +@require_tokenizers +@require_pandas +class TapasTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = TapasTokenizer + test_rust_tokenizer = False + space_between_special_tokens = True + from_pretrained_filter = filter_non_english + test_seq2seq = False + + def get_table( + self, + tokenizer: TapasTokenizer, + length=5, + ): + toks = [tokenizer.decode([i], clean_up_tokenization_spaces=False) for i in range(len(tokenizer))] + + if length == 0: + data = {} + else: + data = {toks[0]: [toks[tok] for tok in range(1, length)]} + + table = pd.DataFrame.from_dict(data) + + return table + + def get_table_and_query( + self, + tokenizer: TapasTokenizer, + length=5, + ): + toks = [tokenizer.decode([i], clean_up_tokenization_spaces=False) for i in range(len(tokenizer))] + table = self.get_table(tokenizer, length=length - 3) + query = " ".join(toks[:3]) + + return table, query + + def get_clean_sequence( + self, + tokenizer: TapasTokenizer, + with_prefix_space=False, + max_length=20, + min_length=5, + empty_table: bool = False, + add_special_tokens: bool = True, + return_table_and_query: bool = False, + ): + toks = [tokenizer.decode([i], clean_up_tokenization_spaces=False) for i in range(len(tokenizer))] + + if empty_table: + table = pd.DataFrame.from_dict({}) + query = " ".join(toks[:min_length]) + else: + data = {toks[0]: [toks[tok] for tok in range(1, min_length - 3)]} + table = pd.DataFrame.from_dict(data) + query = " ".join(toks[:3]) + + output_ids = tokenizer.encode(table, query, add_special_tokens=add_special_tokens) + output_txt = tokenizer.decode(output_ids) + + assert len(output_ids) >= min_length, "Update the code to generate the sequences so that they are larger" + assert len(output_ids) <= max_length, "Update the code to generate the sequences so that they are smaller" + + if return_table_and_query: + return output_txt, output_ids, table, query + + return output_txt, output_ids + + def setUp(self): + super().setUp() + + vocab_tokens = [ + "[UNK]", + "[CLS]", + "[SEP]", + "[PAD]", + "[MASK]", + "want", + "##want", + "##ed", + "wa", + "un", + "runn", + "##ing", + ",", + "low", + "lowest", + ] + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def get_input_output_texts(self, tokenizer): + input_text = "UNwant\u00E9d,running" + output_text = "unwanted, running" + return input_text, output_text + + @require_tensorflow_probability + @slow + def test_tf_encode_plus_sent_to_model(self): + from transformers import TF_MODEL_MAPPING, TOKENIZER_MAPPING + + MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(TF_MODEL_MAPPING, TOKENIZER_MAPPING) + + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING: + return + + config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__] + config = config_class() + + if config.is_encoder_decoder or config.pad_token_id is None: + return + + model = model_class(config) + + # Make sure the model contains at least the full vocabulary size in its embedding matrix + self.assertGreaterEqual(model.config.vocab_size, len(tokenizer)) + + # Build sequence + first_ten_tokens = list(tokenizer.get_vocab().keys())[:10] + sequence = " ".join(first_ten_tokens) + table = self.get_table(tokenizer, length=0) + encoded_sequence = tokenizer.encode_plus(table, sequence, return_tensors="tf") + batch_encoded_sequence = tokenizer.batch_encode_plus(table, [sequence, sequence], return_tensors="tf") + + # This should not fail + model(encoded_sequence) + model(batch_encoded_sequence) + + def test_rust_and_python_full_tokenizers(self): + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + sequence = "UNwant\u00E9d,running" + + tokens = tokenizer.tokenize(sequence) + rust_tokens = rust_tokenizer.tokenize(sequence) + self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + rust_tokenizer = self.get_rust_tokenizer() + ids = tokenizer.encode(sequence) + rust_ids = rust_tokenizer.encode(sequence) + self.assertListEqual(ids, rust_ids) + + # With lower casing + tokenizer = self.get_tokenizer(do_lower_case=True) + rust_tokenizer = self.get_rust_tokenizer(do_lower_case=True) + + sequence = "UNwant\u00E9d,running" + + tokens = tokenizer.tokenize(sequence) + rust_tokens = rust_tokenizer.tokenize(sequence) + self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + rust_tokenizer = self.get_rust_tokenizer() + ids = tokenizer.encode(sequence) + rust_ids = rust_tokenizer.encode(sequence) + self.assertListEqual(ids, rust_ids) + + def test_chinese(self): + tokenizer = BasicTokenizer() + + self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"), ["ah", "\u535A", "\u63A8", "zz"]) + + def test_basic_tokenizer_lower(self): + tokenizer = BasicTokenizer(do_lower_case=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["hello", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_lower_strip_accents_false(self): + tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hällo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["h\u00E9llo"]) + + def test_basic_tokenizer_lower_strip_accents_true(self): + tokenizer = BasicTokenizer(do_lower_case=True, strip_accents=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_lower_strip_accents_default(self): + tokenizer = BasicTokenizer(do_lower_case=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["hallo", "!", "how", "are", "you", "?"] + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"]) + + def test_basic_tokenizer_no_lower(self): + tokenizer = BasicTokenizer(do_lower_case=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? "), ["HeLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_no_lower_strip_accents_false(self): + tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=False) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HäLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_no_lower_strip_accents_true(self): + tokenizer = BasicTokenizer(do_lower_case=False, strip_accents=True) + + self.assertListEqual( + tokenizer.tokenize(" \tHäLLo!how \n Are yoU? "), ["HaLLo", "!", "how", "Are", "yoU", "?"] + ) + + def test_basic_tokenizer_respects_never_split_tokens(self): + tokenizer = BasicTokenizer(do_lower_case=False, never_split=["[UNK]"]) + + self.assertListEqual( + tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]"), ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] + ) + + def test_wordpiece_tokenizer(self): + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] + + vocab = {} + for i, token in enumerate(vocab_tokens): + vocab[token] = i + tokenizer = WordpieceTokenizer(vocab=vocab, unk_token="[UNK]") + + self.assertListEqual(tokenizer.tokenize(""), []) + + self.assertListEqual(tokenizer.tokenize("unwanted running"), ["un", "##want", "##ed", "runn", "##ing"]) + + self.assertListEqual(tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"]) + + def test_is_whitespace(self): + self.assertTrue(_is_whitespace(" ")) + self.assertTrue(_is_whitespace("\t")) + self.assertTrue(_is_whitespace("\r")) + self.assertTrue(_is_whitespace("\n")) + self.assertTrue(_is_whitespace("\u00A0")) + + self.assertFalse(_is_whitespace("A")) + self.assertFalse(_is_whitespace("-")) + + def test_is_control(self): + self.assertTrue(_is_control("\u0005")) + + self.assertFalse(_is_control("A")) + self.assertFalse(_is_control(" ")) + self.assertFalse(_is_control("\t")) + self.assertFalse(_is_control("\r")) + + def test_is_punctuation(self): + self.assertTrue(_is_punctuation("-")) + self.assertTrue(_is_punctuation("$")) + self.assertTrue(_is_punctuation("`")) + self.assertTrue(_is_punctuation(".")) + + self.assertFalse(_is_punctuation("A")) + self.assertFalse(_is_punctuation(" ")) + + def test_clean_text(self): + tokenizer = self.get_tokenizer() + + # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 + self.assertListEqual( + [tokenizer.tokenize(t) for t in ["Test", "\xad", "test"]], [["[UNK]"], ["[EMPTY]"], ["[UNK]"]] + ) + + @slow + def test_sequence_builders(self): + tokenizer = self.tokenizer_class.from_pretrained("google/tapas-base-finetuned-wtq") + + empty_table = self.get_table(tokenizer, length=0) + table = self.get_table(tokenizer, length=10) + + text = tokenizer.encode(table, add_special_tokens=False) + text_2 = tokenizer.encode(empty_table, "multi-sequence build", add_special_tokens=False) + + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_pair == [101] + text + [102] + text_2 + + def test_offsets_with_special_characters(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) + + sentence = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." + tokens = tokenizer_r.encode_plus( + sentence, + return_attention_mask=False, + return_token_type_ids=False, + return_offsets_mapping=True, + add_special_tokens=True, + ) + + do_lower_case = tokenizer_r.do_lower_case if hasattr(tokenizer_r, "do_lower_case") else False + expected_results = ( + [ + ((0, 0), tokenizer_r.cls_token), + ((0, 1), "A"), + ((1, 2), ","), + ((3, 5), "na"), + ((5, 6), "##ï"), + ((6, 8), "##ve"), + ((9, 15), tokenizer_r.mask_token), + ((16, 21), "Allen"), + ((21, 23), "##NL"), + ((23, 24), "##P"), + ((25, 33), "sentence"), + ((33, 34), "."), + ((0, 0), tokenizer_r.sep_token), + ] + if not do_lower_case + else [ + ((0, 0), tokenizer_r.cls_token), + ((0, 1), "a"), + ((1, 2), ","), + ((3, 8), "naive"), + ((9, 15), tokenizer_r.mask_token), + ((16, 21), "allen"), + ((21, 23), "##nl"), + ((23, 24), "##p"), + ((25, 33), "sentence"), + ((33, 34), "."), + ((0, 0), tokenizer_r.sep_token), + ] + ) + + self.assertEqual( + [e[1] for e in expected_results], tokenizer_r.convert_ids_to_tokens(tokens["input_ids"]) + ) + self.assertEqual([e[0] for e in expected_results], tokens["offset_mapping"]) + + def test_add_special_tokens(self): + tokenizers: List[TapasTokenizer] = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + input_table = self.get_table(tokenizer, length=0) + + special_token = "[SPECIAL_TOKEN]" + + tokenizer.add_special_tokens({"cls_token": special_token}) + encoded_special_token = tokenizer.encode(input_table, special_token, add_special_tokens=False) + self.assertEqual(len(encoded_special_token), 1) + + decoded = tokenizer.decode(encoded_special_token, skip_special_tokens=True) + self.assertTrue(special_token not in decoded) + + def test_add_tokens_tokenizer(self): + tokenizers: List[TapasTokenizer] = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + vocab_size = tokenizer.vocab_size + all_size = len(tokenizer) + + self.assertNotEqual(vocab_size, 0) + + # We usually have added tokens from the start in tests because our vocab fixtures are + # smaller than the original vocabs - let's not assert this + # self.assertEqual(vocab_size, all_size) + + new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd"] + added_toks = tokenizer.add_tokens(new_toks) + vocab_size_2 = tokenizer.vocab_size + all_size_2 = len(tokenizer) + + self.assertNotEqual(vocab_size_2, 0) + self.assertEqual(vocab_size, vocab_size_2) + self.assertEqual(added_toks, len(new_toks)) + self.assertEqual(all_size_2, all_size + len(new_toks)) + + tokens = tokenizer.encode(table, "aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False) + + self.assertGreaterEqual(len(tokens), 4) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-2], tokenizer.vocab_size - 1) + + new_toks_2 = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} + added_toks_2 = tokenizer.add_special_tokens(new_toks_2) + vocab_size_3 = tokenizer.vocab_size + all_size_3 = len(tokenizer) + + self.assertNotEqual(vocab_size_3, 0) + self.assertEqual(vocab_size, vocab_size_3) + self.assertEqual(added_toks_2, len(new_toks_2)) + self.assertEqual(all_size_3, all_size_2 + len(new_toks_2)) + + tokens = tokenizer.encode( + table, + ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", + add_special_tokens=False, + ) + + self.assertGreaterEqual(len(tokens), 6) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[0], tokens[1]) + self.assertGreater(tokens[-2], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-2], tokens[-3]) + self.assertEqual(tokens[0], tokenizer.eos_token_id) + self.assertEqual(tokens[-2], tokenizer.pad_token_id) + + @require_tokenizers + def test_encode_decode_with_spaces(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + + new_toks = [AddedToken("[ABC]", normalized=False), AddedToken("[DEF]", normalized=False)] + tokenizer.add_tokens(new_toks) + input = "[ABC][DEF][ABC][DEF]" + if self.space_between_special_tokens: + output = "[ABC] [DEF] [ABC] [DEF]" + else: + output = input + encoded = tokenizer.encode(table, input, add_special_tokens=False) + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=self.space_between_special_tokens) + self.assertIn(decoded, [output, output.lower()]) + + def test_encode_plus_with_padding(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + sequence = "Sequence" + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequence) + + padding_size = 10 + padding_idx = tokenizer.pad_token_id + token_type_padding_idx = tokenizer.pad_token_type_id + + encoded_sequence = tokenizer.encode_plus(table, sequence, return_special_tokens_mask=True) + input_ids = encoded_sequence["input_ids"] + special_tokens_mask = encoded_sequence["special_tokens_mask"] + sequence_length = len(input_ids) + + # Test 'longest' and 'no_padding' don't do anything + tokenizer.padding_side = "right" + + not_padded_sequence = tokenizer.encode_plus( + table, + sequence, + padding=False, + return_special_tokens_mask=True, + ) + not_padded_input_ids = not_padded_sequence["input_ids"] + + not_padded_special_tokens_mask = not_padded_sequence["special_tokens_mask"] + not_padded_sequence_length = len(not_padded_input_ids) + + assert sequence_length == not_padded_sequence_length + assert input_ids == not_padded_input_ids + assert special_tokens_mask == not_padded_special_tokens_mask + + not_padded_sequence = tokenizer.encode_plus( + table, + sequence, + padding=False, + return_special_tokens_mask=True, + ) + not_padded_input_ids = not_padded_sequence["input_ids"] + + not_padded_special_tokens_mask = not_padded_sequence["special_tokens_mask"] + not_padded_sequence_length = len(not_padded_input_ids) + + assert sequence_length == not_padded_sequence_length + assert input_ids == not_padded_input_ids + assert special_tokens_mask == not_padded_special_tokens_mask + + # Test right padding + tokenizer.padding_side = "right" + + right_padded_sequence = tokenizer.encode_plus( + table, + sequence, + max_length=sequence_length + padding_size, + padding="max_length", + return_special_tokens_mask=True, + ) + right_padded_input_ids = right_padded_sequence["input_ids"] + + right_padded_special_tokens_mask = right_padded_sequence["special_tokens_mask"] + right_padded_sequence_length = len(right_padded_input_ids) + + assert sequence_length + padding_size == right_padded_sequence_length + assert input_ids + [padding_idx] * padding_size == right_padded_input_ids + assert special_tokens_mask + [1] * padding_size == right_padded_special_tokens_mask + + # Test left padding + tokenizer.padding_side = "left" + left_padded_sequence = tokenizer.encode_plus( + table, + sequence, + max_length=sequence_length + padding_size, + padding="max_length", + return_special_tokens_mask=True, + ) + left_padded_input_ids = left_padded_sequence["input_ids"] + left_padded_special_tokens_mask = left_padded_sequence["special_tokens_mask"] + left_padded_sequence_length = len(left_padded_input_ids) + + assert sequence_length + padding_size == left_padded_sequence_length + assert [padding_idx] * padding_size + input_ids == left_padded_input_ids + assert [1] * padding_size + special_tokens_mask == left_padded_special_tokens_mask + + if "token_type_ids" in tokenizer.model_input_names: + token_type_ids = encoded_sequence["token_type_ids"] + left_padded_token_type_ids = left_padded_sequence["token_type_ids"] + right_padded_token_type_ids = right_padded_sequence["token_type_ids"] + + assert ( + token_type_ids + [[token_type_padding_idx] * 7] * padding_size == right_padded_token_type_ids + ) + assert [[token_type_padding_idx] * 7] * padding_size + token_type_ids == left_padded_token_type_ids + + if "attention_mask" in tokenizer.model_input_names: + attention_mask = encoded_sequence["attention_mask"] + right_padded_attention_mask = right_padded_sequence["attention_mask"] + left_padded_attention_mask = left_padded_sequence["attention_mask"] + + assert attention_mask + [0] * padding_size == right_padded_attention_mask + assert [0] * padding_size + attention_mask == left_padded_attention_mask + + def test_internal_consistency(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + input_text, output_text = self.get_input_output_texts(tokenizer) + + tokens = tokenizer.tokenize(input_text) + ids = tokenizer.convert_tokens_to_ids(tokens) + ids_2 = tokenizer.encode(table, input_text, add_special_tokens=False) + self.assertListEqual(ids, ids_2) + + tokens_2 = tokenizer.convert_ids_to_tokens(ids) + self.assertNotEqual(len(tokens_2), 0) + text_2 = tokenizer.decode(ids) + self.assertIsInstance(text_2, str) + + self.assertEqual(text_2, output_text) + + def test_mask_output(self): + tokenizers = self.get_tokenizers(fast=False, do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table, query = self.get_table_and_query(tokenizer) + + if ( + tokenizer.build_inputs_with_special_tokens.__qualname__.split(".")[0] != "PreTrainedTokenizer" + and "token_type_ids" in tokenizer.model_input_names + ): + information = tokenizer.encode_plus(table, query, add_special_tokens=True) + sequences, mask = information["input_ids"], information["token_type_ids"] + self.assertEqual(len(sequences), len(mask)) + + @unittest.skip("TAPAS tokenizer only handles two sequences.") + def test_maximum_encoding_length_pair_input(self): + pass + + @unittest.skip("TAPAS tokenizer only handles two sequences.") + def test_maximum_encoding_length_single_input(self): + pass + + def test_number_of_added_tokens(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table, query = self.get_table_and_query(tokenizer) + + sequences = tokenizer.encode(table, query, add_special_tokens=False) + attached_sequences = tokenizer.encode(table, query, add_special_tokens=True) + + # Method is implemented (e.g. not GPT-2) + if len(attached_sequences) != 2: + self.assertEqual( + tokenizer.num_special_tokens_to_add(pair=True), len(attached_sequences) - len(sequences) + ) + + def test_padding_to_max_length(self): + """We keep this test for backward compatibility but it should be removed when `pad_to_max_length` will be deprecated""" + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer) + sequence = "Sequence" + padding_size = 10 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequence) + + padding_idx = tokenizer.pad_token_id + + # Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "right" + encoded_sequence = tokenizer.encode(table, sequence) + sequence_length = len(encoded_sequence) + # FIXME: the next line should be padding(max_length) to avoid warning + padded_sequence = tokenizer.encode( + table, sequence, max_length=sequence_length + padding_size, padding=True + ) + padded_sequence_length = len(padded_sequence) + assert sequence_length + padding_size == padded_sequence_length + assert encoded_sequence + [padding_idx] * padding_size == padded_sequence + + # Check that nothing is done when a maximum length is not specified + encoded_sequence = tokenizer.encode(table, sequence) + sequence_length = len(encoded_sequence) + + tokenizer.padding_side = "right" + padded_sequence_right = tokenizer.encode(table, sequence, pad_to_max_length=True) + padded_sequence_right_length = len(padded_sequence_right) + assert sequence_length == padded_sequence_right_length + assert encoded_sequence == padded_sequence_right + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + # Test not batched + table = self.get_table(tokenizer, length=0) + encoded_sequences_1 = tokenizer.encode_plus(table, sequences[0]) + encoded_sequences_2 = tokenizer(table, sequences[0]) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + # Test not batched pairs + table = self.get_table(tokenizer, length=10) + encoded_sequences_1 = tokenizer.encode_plus(table, sequences[1]) + encoded_sequences_2 = tokenizer(table, sequences[1]) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + # Test batched + table = self.get_table(tokenizer, length=0) + encoded_sequences_1 = tokenizer.batch_encode_plus(table, sequences) + encoded_sequences_2 = tokenizer(table, sequences) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + def test_batch_encode_plus_batch_sequence_length(self): + # Tests that all encoded values have the correct size + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + encoded_sequences = [tokenizer.encode_plus(table, sequence) for sequence in sequences] + encoded_sequences_batch = tokenizer.batch_encode_plus(table, sequences, padding=False) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + maximum_length = len( + max([encoded_sequence["input_ids"] for encoded_sequence in encoded_sequences], key=len) + ) + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences_padded = [ + tokenizer.encode_plus(table, sequence, max_length=maximum_length, padding="max_length") + for sequence in sequences + ] + + encoded_sequences_batch_padded = tokenizer.batch_encode_plus(table, sequences, padding=True) + self.assertListEqual( + encoded_sequences_padded, + self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch_padded), + ) + + # check 'longest' is unsensitive to a max length + encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(table, sequences, padding=True) + encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus( + table, sequences, max_length=maximum_length + 10, padding="longest" + ) + for key in encoded_sequences_batch_padded_1.keys(): + self.assertListEqual( + encoded_sequences_batch_padded_1[key], + encoded_sequences_batch_padded_2[key], + ) + + # check 'no_padding' is unsensitive to a max length + encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(table, sequences, padding=False) + encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus( + table, sequences, max_length=maximum_length + 10, padding=False + ) + for key in encoded_sequences_batch_padded_1.keys(): + self.assertListEqual( + encoded_sequences_batch_padded_1[key], + encoded_sequences_batch_padded_2[key], + ) + + @unittest.skip("batch_encode_plus does not handle overflowing tokens.") + def test_batch_encode_plus_overflowing_tokens(self): + pass + + def test_batch_encode_plus_padding(self): + # Test that padded sequences are equivalent between batch_encode_plus and encode_plus + + # Right padding tests + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + max_length = 100 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences = [ + tokenizer.encode_plus(table, sequence, max_length=max_length, padding="max_length") + for sequence in sequences + ] + encoded_sequences_batch = tokenizer.batch_encode_plus( + table, sequences, max_length=max_length, padding="max_length" + ) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + # Left padding tests + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokenizer.padding_side = "left" + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + max_length = 100 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences = [ + tokenizer.encode_plus(table, sequence, max_length=max_length, padding="max_length") + for sequence in sequences + ] + encoded_sequences_batch = tokenizer.batch_encode_plus( + table, sequences, max_length=max_length, padding="max_length" + ) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + def test_padding_to_multiple_of(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + if tokenizer.pad_token is None: + self.skipTest("No padding token.") + else: + empty_tokens = tokenizer(table, padding=True, pad_to_multiple_of=8) + normal_tokens = tokenizer(table, "This is a sample input", padding=True, pad_to_multiple_of=8) + for key, value in empty_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + normal_tokens = tokenizer(table, "This", pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # Should also work with truncation + normal_tokens = tokenizer(table, "This", padding=True, truncation=True, pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + @unittest.skip("TAPAS cannot handle `prepare_for_model` without passing by `encode_plus` or `batch_encode_plus`") + def test_prepare_for_model(self): + pass + + def test_tokenizer_slow_store_full_signature(self): + signature = inspect.signature(self.tokenizer_class.__init__) + tokenizer = self.get_tokenizer() + + for parameter_name, parameter in signature.parameters.items(): + if parameter.default != inspect.Parameter.empty: + self.assertIn(parameter_name, tokenizer.init_kwargs) + + def test_special_tokens_mask_input_pairs(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence_0 = "Encode this." + empty_table = self.get_table(tokenizer, length=0) + table = self.get_table(tokenizer, length=10) + encoded_sequence = tokenizer.encode(empty_table, sequence_0, add_special_tokens=False) + encoded_sequence += tokenizer.encode(table, "", add_special_tokens=False) + encoded_sequence_dict = tokenizer.encode_plus( + table, + sequence_0, + add_special_tokens=True, + return_special_tokens_mask=True, + # add_prefix_space=False, + ) + encoded_sequence_w_special = encoded_sequence_dict["input_ids"] + special_tokens_mask = encoded_sequence_dict["special_tokens_mask"] + self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special)) + + filtered_sequence = [ + (x if not special_tokens_mask[i] else None) for i, x in enumerate(encoded_sequence_w_special) + ] + filtered_sequence = [x for x in filtered_sequence if x is not None] + self.assertEqual(encoded_sequence, filtered_sequence) + + def test_special_tokens_mask(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + sequence_0 = "Encode this." + # Testing single inputs + encoded_sequence = tokenizer.encode(table, sequence_0, add_special_tokens=False) + encoded_sequence_dict = tokenizer.encode_plus( + table, sequence_0, add_special_tokens=True, return_special_tokens_mask=True + ) + encoded_sequence_w_special = encoded_sequence_dict["input_ids"] + special_tokens_mask = encoded_sequence_dict["special_tokens_mask"] + self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special)) + + filtered_sequence = [x for i, x in enumerate(encoded_sequence_w_special) if not special_tokens_mask[i]] + self.assertEqual(encoded_sequence, filtered_sequence) + + def test_save_and_load_tokenizer(self): + # safety check on max_len default value so we are sure the test works + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + self.assertNotEqual(tokenizer.model_max_length, 42) + + # Now let's start the test + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Isolate this from the other tests because we save additional tokens/etc + table = self.get_table(tokenizer, length=0) + tmpdirname = tempfile.mkdtemp() + + sample_text = " He is very happy, UNwant\u00E9d,running" + before_tokens = tokenizer.encode(table, sample_text, add_special_tokens=False) + before_vocab = tokenizer.get_vocab() + tokenizer.save_pretrained(tmpdirname) + + after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname) + after_tokens = after_tokenizer.encode(table, sample_text, add_special_tokens=False) + after_vocab = after_tokenizer.get_vocab() + self.assertListEqual(before_tokens, after_tokens) + self.assertDictEqual(before_vocab, after_vocab) + + shutil.rmtree(tmpdirname) + + @unittest.skip("Not implemented") + def test_right_and_left_truncation(self): + pass + + def test_right_and_left_padding(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + table = self.get_table(tokenizer, length=0) + sequence = "Sequence" + padding_size = 10 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequence) + + padding_idx = tokenizer.pad_token_id + + # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "right" + encoded_sequence = tokenizer.encode(table, sequence) + sequence_length = len(encoded_sequence) + padded_sequence = tokenizer.encode( + table, sequence, max_length=sequence_length + padding_size, padding="max_length" + ) + padded_sequence_length = len(padded_sequence) + assert sequence_length + padding_size == padded_sequence_length + assert encoded_sequence + [padding_idx] * padding_size == padded_sequence + + # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "left" + encoded_sequence = tokenizer.encode(table, sequence) + sequence_length = len(encoded_sequence) + padded_sequence = tokenizer.encode( + table, sequence, max_length=sequence_length + padding_size, padding="max_length" + ) + padded_sequence_length = len(padded_sequence) + assert sequence_length + padding_size == padded_sequence_length + assert [padding_idx] * padding_size + encoded_sequence == padded_sequence + + # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding' + encoded_sequence = tokenizer.encode(table, sequence) + sequence_length = len(encoded_sequence) + + tokenizer.padding_side = "right" + padded_sequence_right = tokenizer.encode(table, sequence, padding=True) + padded_sequence_right_length = len(padded_sequence_right) + assert sequence_length == padded_sequence_right_length + assert encoded_sequence == padded_sequence_right + + tokenizer.padding_side = "left" + padded_sequence_left = tokenizer.encode(table, sequence, padding="longest") + padded_sequence_left_length = len(padded_sequence_left) + assert sequence_length == padded_sequence_left_length + assert encoded_sequence == padded_sequence_left + + tokenizer.padding_side = "right" + padded_sequence_right = tokenizer.encode(table, sequence) + padded_sequence_right_length = len(padded_sequence_right) + assert sequence_length == padded_sequence_right_length + assert encoded_sequence == padded_sequence_right + + tokenizer.padding_side = "left" + padded_sequence_left = tokenizer.encode(table, sequence, padding=False) + padded_sequence_left_length = len(padded_sequence_left) + assert sequence_length == padded_sequence_left_length + assert encoded_sequence == padded_sequence_left + + def test_token_type_ids(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + empty_table = self.get_table(tokenizer, length=0) + seq_0 = "Test this method." + + # We want to have sequence 0 and sequence 1 are tagged + # respectively with 0 and 1 token_ids + # (regardless of whether the model use token type ids) + # We use this assumption in the QA pipeline among other place + output = tokenizer(empty_table, seq_0, return_token_type_ids=True) + + # Assert that the token type IDs have the same length as the input IDs + self.assertEqual(len(output["token_type_ids"]), len(output["input_ids"])) + + # Assert that each token type ID has 7 values + self.assertTrue(all(len(token_type_ids) == 7 for token_type_ids in output["token_type_ids"])) + + # Do the same test as modeling common. + self.assertIn(0, output["token_type_ids"][0]) + + @unittest.skipIf(not is_torch_greater_or_equal_than_1_12, reason="Tapas is only available in torch v1.12+") + @require_torch + @slow + def test_torch_encode_plus_sent_to_model(self): + import torch + + from transformers import MODEL_MAPPING, TOKENIZER_MAPPING + + MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING) + + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING: + return + + config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__] + config = config_class() + + if config.is_encoder_decoder or config.pad_token_id is None: + return + + model = model_class(config) + + # Make sure the model contains at least the full vocabulary size in its embedding matrix + is_using_common_embeddings = hasattr(model.get_input_embeddings(), "weight") + assert ( + (model.get_input_embeddings().weight.shape[0] >= len(tokenizer)) + if is_using_common_embeddings + else True + ) + + # Build sequence + first_ten_tokens = list(tokenizer.get_vocab().keys())[:10] + sequence = " ".join(first_ten_tokens) + table = self.get_table(tokenizer, length=0) + encoded_sequence = tokenizer.encode_plus(table, sequence, return_tensors="pt") + batch_encoded_sequence = tokenizer.batch_encode_plus(table, [sequence, sequence], return_tensors="pt") + # This should not fail + + with torch.no_grad(): # saves some time + model(**encoded_sequence) + model(**batch_encoded_sequence) + + @unittest.skip("TAPAS doesn't handle pre-tokenized inputs.") + def test_pretokenized_inputs(self): + pass + + @slow + def test_tapas_truncation_integration_test(self): + data = { + "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], + "Age": ["56", "45", "59"], + "Number of movies": ["87", "53", "69"], + "Date of birth": ["18 december 1963", "11 november 1974", "6 may 1961"], + } + queries = [ + "When was Brad Pitt born?", + "Which actor appeared in the least number of movies?", + "What is the average number of movies?", + ] + table = pd.DataFrame.from_dict(data) + + tokenizer = TapasTokenizer.from_pretrained("lysandre/tapas-temporary-repo", model_max_length=512) + + for i in range(12): + # The table cannot even encode the headers, so raise an error + with self.assertRaises(ValueError): + tokenizer.encode(table=table, query=queries[0], max_length=i, truncation="drop_rows_to_fit") + + for i in range(12, 512): + new_encoded_inputs = tokenizer.encode( + table=table, query=queries[0], max_length=i, truncation="drop_rows_to_fit" + ) + + # Ensure that the input IDs are less than the max length defined. + self.assertLessEqual(len(new_encoded_inputs), i) + + tokenizer.model_max_length = 20 + new_encoded_inputs = tokenizer.encode(table=table, query=queries[0], truncation=True) + dropped_encoded_inputs = tokenizer.encode(table=table, query=queries[0], truncation="drop_rows_to_fit") + + # Ensure that the input IDs are still truncated when no max_length is specified + self.assertListEqual(new_encoded_inputs, dropped_encoded_inputs) + self.assertLessEqual(len(new_encoded_inputs), 20) + + @slow + def test_min_max_question_length(self): + data = { + "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], + "Age": ["56", "45", "59"], + "Number of movies": ["87", "53", "69"], + "Date of birth": ["18 december 1963", "11 november 1974", "6 may 1961"], + } + queries = "When was Brad Pitt born?" + table = pd.DataFrame.from_dict(data) + + # test max_question_length + tokenizer = TapasTokenizer.from_pretrained("lysandre/tapas-temporary-repo", max_question_length=2) + + encoding = tokenizer(table=table, queries=queries) + + # query should not be tokenized as it's longer than the specified max_question_length + expected_results = [101, 102] + + self.assertListEqual(encoding.input_ids[:2], expected_results) + + # test min_question_length + tokenizer = TapasTokenizer.from_pretrained("lysandre/tapas-temporary-repo", min_question_length=30) + + encoding = tokenizer(table=table, queries=queries) + + # query should not be tokenized as it's shorter than the specified min_question_length + expected_results = [101, 102] + + self.assertListEqual(encoding.input_ids[:2], expected_results) + + @is_pt_tf_cross_test + def test_batch_encode_plus_tensors(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + table = self.get_table(tokenizer, length=0) + + # A Tensor cannot be build by sequences which are not the same size + self.assertRaises(ValueError, tokenizer.batch_encode_plus, table, sequences, return_tensors="pt") + self.assertRaises(ValueError, tokenizer.batch_encode_plus, table, sequences, return_tensors="tf") + + if tokenizer.pad_token_id is None: + self.assertRaises( + ValueError, + tokenizer.batch_encode_plus, + table, + sequences, + padding=True, + return_tensors="pt", + ) + self.assertRaises( + ValueError, + tokenizer.batch_encode_plus, + table, + sequences, + padding="longest", + return_tensors="tf", + ) + else: + pytorch_tensor = tokenizer.batch_encode_plus(table, sequences, padding=True, return_tensors="pt") + tensorflow_tensor = tokenizer.batch_encode_plus( + table, sequences, padding="longest", return_tensors="tf" + ) + encoded_sequences = tokenizer.batch_encode_plus(table, sequences, padding=True) + + for key in encoded_sequences.keys(): + pytorch_value = pytorch_tensor[key].tolist() + tensorflow_value = tensorflow_tensor[key].numpy().tolist() + encoded_value = encoded_sequences[key] + + self.assertEqual(pytorch_value, tensorflow_value, encoded_value) + + @slow + def test_tapas_integration_test(self): + data = { + "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], + "Age": ["56", "45", "59"], + "Number of movies": ["87", "53", "69"], + "Date of birth": ["18 december 1963", "11 november 1974", "6 may 1961"], + } + queries = [ + "When was Brad Pitt born?", + "Which actor appeared in the least number of movies?", + "What is the average number of movies?", + ] + table = pd.DataFrame.from_dict(data) + + tokenizer = TapasTokenizer.from_pretrained("google/tapas-base-finetuned-wtq", model_max_length=512) + + expected_results = {'input_ids':[101,2043,2001,8226,15091,2141,1029,102,5889,2287,2193,1997,5691,3058,1997,4182,8226,15091,5179,6584,2324,2285,3699,14720,4487,6178,9488,3429,5187,2340,2281,3326,2577,18856,7828,3240,5354,6353,1020,2089,3777],'attention_mask':[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],'token_type_ids':[[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[1,1,0,0,0,0,0],[1,2,0,0,0,0,0],[1,3,0,0,0,0,0],[1,3,0,0,0,0,0],[1,3,0,0,0,0,0],[1,4,0,0,0,0,0],[1,4,0,0,0,0,0],[1,4,0,0,0,0,0],[1,1,1,0,0,0,0],[1,1,1,0,0,0,0],[1,2,1,0,2,2,0],[1,3,1,0,3,1,0],[1,4,1,0,2,2,0],[1,4,1,0,2,2,0],[1,4,1,0,2,2,0],[1,1,2,0,0,0,0],[1,1,2,0,0,0,0],[1,1,2,0,0,0,0],[1,1,2,0,0,0,0],[1,2,2,0,1,3,0],[1,3,2,0,1,3,0],[1,4,2,0,3,1,0],[1,4,2,0,3,1,0],[1,4,2,0,3,1,0],[1,1,3,0,0,0,0],[1,1,3,0,0,0,0],[1,1,3,0,0,0,0],[1,1,3,0,0,0,0],[1,2,3,0,3,1,0],[1,3,3,0,2,2,0],[1,4,3,0,1,3,0],[1,4,3,0,1,3,0],[1,4,3,0,1,3,0]]} # fmt: skip + + new_encoded_inputs = tokenizer.encode_plus(table=table, query=queries[0]) + + self.assertDictEqual(dict(new_encoded_inputs), expected_results) + + @slow + def test_full_tokenizer(self): + data = [ + ["Pos", "No", "Driver", "Team", "Laps", "Time/Retired", "Grid", "Points"], + ["1", "32", "Patrick Carpentier", "Team Player's", "87", "1:48:11.023", "1", "22"], + ["2", "1", "Bruno Junqueira", "Newman/Haas Racing", "87", "+0.8 secs", "2", "17"], + ["3", "3", "Paul Tracy", "Team Player's", "87", "+28.6 secs", "3", "14"], + ["4", "9", "Michel Jourdain, Jr.", "Team Rahal", "87", "+40.8 secs", "13", "12"], + ["5", "34", "Mario Haberfeld", "Mi-Jack Conquest Racing", "87", "+42.1 secs", "6", "10"], + ["6", "20", "Oriol Servia", "Patrick Racing", "87", "+1:00.2", "10", "8"], + ["7", "51", "Adrian Fernandez", "Fernandez Racing", "87", "+1:01.4", "5", "6"], + ["8", "12", "Jimmy Vasser", "American Spirit Team Johansson", "87", "+1:01.8", "8", "5"], + ["9", "7", "Tiago Monteiro", "Fittipaldi-Dingman Racing", "86", "+ 1 Lap", "15", "4"], + ["10", "55", "Mario Dominguez", "Herdez Competition", "86", "+ 1 Lap", "11", "3"], + ["11", "27", "Bryan Herta", "PK Racing", "86", "+ 1 Lap", "12", "2"], + ["12", "31", "Ryan Hunter-Reay", "American Spirit Team Johansson", "86", "+ 1 Lap", "17", "1"], + ["13", "19", "Joel Camathias", "Dale Coyne Racing", "85", "+ 2 Laps", "18", "0"], + ["14", "33", "Alex Tagliani", "Rocketsports Racing", "85", "+ 2 Laps", "14", "0"], + ["15", "4", "Roberto Moreno", "Herdez Competition", "85", "+ 2 Laps", "9", "0"], + ["16", "11", "Geoff Boss", "Dale Coyne Racing", "83", "Mechanical", "19", "0"], + ["17", "2", "Sebastien Bourdais", "Newman/Haas Racing", "77", "Mechanical", "4", "0"], + ["18", "15", "Darren Manning", "Walker Racing", "12", "Mechanical", "7", "0"], + ["19", "5", "Rodolfo Lavin", "Walker Racing", "10", "Mechanical", "16", "0"], + ] + query = "what were the drivers names?" + table = pd.DataFrame.from_records(data[1:], columns=data[0]) + + tokenizer = TapasTokenizer.from_pretrained("google/tapas-base-finetuned-wtq", model_max_length=512) + model_inputs = tokenizer(table, query, padding="max_length") + + input_ids = model_inputs["input_ids"] + token_type_ids = np.array(model_inputs["token_type_ids"]) + segment_ids = token_type_ids[:, 0] + column_ids = token_type_ids[:, 1] + row_ids = token_type_ids[:, 2] + + expected_results = {'input_ids':[101,2054,2020,1996,6853,3415,1029,102,13433,2015,2053,4062,2136,10876,2051,1013,3394,8370,2685,1015,3590,4754,29267,4765,3771,2136,2447,1005,1055,6584,1015,1024,4466,1024,2340,1012,6185,2509,1015,2570,1016,1015,10391,12022,4226,7895,10625,1013,22996,3868,6584,1009,1014,1012,1022,10819,2015,1016,2459,1017,1017,2703,10555,2136,2447,1005,1055,6584,1009,2654,1012,1020,10819,2015,1017,2403,1018,1023,8709,8183,3126,21351,2078,1010,3781,1012,2136,10958,8865,6584,1009,2871,1012,1022,10819,2015,2410,2260,1019,4090,7986,5292,5677,8151,2771,1011,2990,9187,3868,6584,1009,4413,1012,1015,10819,2015,1020,2184,1020,2322,2030,20282,14262,9035,4754,3868,6584,1009,1015,1024,4002,1012,1016,2184,1022,1021,4868,7918,12023,12023,3868,6584,1009,1015,1024,5890,1012,1018,1019,1020,1022,2260,5261,12436,18116,2137,4382,2136,26447,6584,1009,1015,1024,5890,1012,1022,1022,1019,1023,1021,27339,3995,10125,9711,4906,25101,24657,1011,22033,2386,3868,6564,1009,1015,5001,2321,1018,2184,4583,7986,14383,2075,29488,14906,9351,2971,6564,1009,1015,5001,2340,1017,2340,2676,8527,2014,2696,1052,2243,3868,6564,1009,1015,5001,2260,1016,2260,2861,4575,4477,1011,2128,4710,2137,4382,2136,26447,6564,1009,1015,5001,2459,1015,2410,2539,8963,11503,25457,3022,8512,2522,9654,3868,5594,1009,1016,10876,2324,1014,2403,3943,4074,6415,15204,2072,12496,25378,3868,5594,1009,1016,10876,2403,1014,2321,1018,10704,17921,14906,9351,2971,5594,1009,1016,10876,1023,1014,2385,2340,14915,5795,8512,2522,9654,3868,6640,6228,2539,1014,2459,1016,28328,8945,3126,21351,2015,10625,1013,22996,3868,6255,6228,1018,1014,2324,2321,12270,11956,5232,3868,2260,6228,1021,1014,2539,1019,8473,28027,2080,2474,6371,5232,3868,2184,6228,2385,1014,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],'column_ids':[0,0,0,0,0,0,0,0,1,1,2,3,4,5,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,5,6,6,6,6,6,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,4,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,3,3,3,3,3,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,3,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,4,4,4,4,5,6,6,6,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,4,4,4,5,6,6,6,7,8,1,2,3,3,3,3,4,4,4,5,6,6,6,7,8,1,2,3,3,3,4,4,4,5,6,6,6,7,8,1,2,3,3,3,3,3,4,4,4,4,5,6,6,6,7,8,1,2,3,3,3,3,4,4,4,4,5,6,6,6,7,8,1,2,3,3,3,3,4,4,4,5,6,6,6,7,8,1,2,3,3,4,4,4,5,6,6,6,7,8,1,2,3,3,4,4,4,4,5,6,7,8,1,2,3,3,3,3,3,4,4,4,4,5,6,7,8,1,2,3,3,4,4,5,6,7,8,1,2,3,3,3,3,3,4,4,5,6,7,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],'row_ids':[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],'segment_ids':[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]} # fmt: skip + + self.assertListEqual(input_ids, expected_results["input_ids"]) + self.assertListEqual(segment_ids.tolist(), expected_results["segment_ids"]) + self.assertListEqual(column_ids.tolist(), expected_results["column_ids"]) + self.assertListEqual(row_ids.tolist(), expected_results["row_ids"]) + + @unittest.skip("Skip this test while all models are still to be uploaded.") + def test_pretrained_model_lists(self): + pass + + @unittest.skip("Doesn't support another framework than PyTorch") + def test_np_encode_plus_sent_to_model(self): + pass + + @unittest.skip("Chat is not supported") + def test_chat_template(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/time_series_transformer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/time_series_transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/time_series_transformer/test_modeling_time_series_transformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/time_series_transformer/test_modeling_time_series_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a3646a5bebfcc890e7885efb6864d3e53f7afa --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/time_series_transformer/test_modeling_time_series_transformer.py @@ -0,0 +1,554 @@ +# coding=utf-8 +# Copyright 2022 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 TimeSeriesTransformer model. """ + +import inspect +import tempfile +import unittest + +from huggingface_hub import hf_hub_download +from parameterized import parameterized + +from transformers import is_torch_available +from transformers.testing_utils import is_flaky, require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +TOLERANCE = 1e-4 + +if is_torch_available(): + import torch + + from transformers import ( + TimeSeriesTransformerConfig, + TimeSeriesTransformerForPrediction, + TimeSeriesTransformerModel, + ) + from transformers.models.time_series_transformer.modeling_time_series_transformer import ( + TimeSeriesTransformerDecoder, + TimeSeriesTransformerEncoder, + ) + + +@require_torch +class TimeSeriesTransformerModelTester: + def __init__( + self, + parent, + batch_size=13, + prediction_length=7, + context_length=14, + cardinality=19, + embedding_dimension=5, + num_time_features=4, + is_training=True, + hidden_size=64, + 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, + lags_sequence=[1, 2, 3, 4, 5], + ): + self.parent = parent + self.batch_size = batch_size + self.prediction_length = prediction_length + self.context_length = context_length + self.cardinality = cardinality + self.num_time_features = num_time_features + self.lags_sequence = lags_sequence + self.embedding_dimension = embedding_dimension + self.is_training = is_training + 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.encoder_seq_length = context_length + self.decoder_seq_length = prediction_length + + def get_config(self): + return TimeSeriesTransformerConfig( + 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, + prediction_length=self.prediction_length, + context_length=self.context_length, + lags_sequence=self.lags_sequence, + num_time_features=self.num_time_features, + num_static_real_features=1, + num_static_categorical_features=1, + cardinality=[self.cardinality], + embedding_dimension=[self.embedding_dimension], + ) + + def prepare_time_series_transformer_inputs_dict(self, config): + _past_length = config.context_length + max(config.lags_sequence) + + static_categorical_features = ids_tensor([self.batch_size, 1], config.cardinality[0]) + static_real_features = floats_tensor([self.batch_size, 1]) + + past_time_features = floats_tensor([self.batch_size, _past_length, config.num_time_features]) + past_values = floats_tensor([self.batch_size, _past_length]) + past_observed_mask = floats_tensor([self.batch_size, _past_length]) > 0.5 + + # decoder inputs + future_time_features = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]) + future_values = floats_tensor([self.batch_size, config.prediction_length]) + + inputs_dict = { + "past_values": past_values, + "static_categorical_features": static_categorical_features, + "static_real_features": static_real_features, + "past_time_features": past_time_features, + "past_observed_mask": past_observed_mask, + "future_time_features": future_time_features, + "future_values": future_values, + } + return inputs_dict + + def prepare_config_and_inputs(self): + config = self.get_config() + inputs_dict = self.prepare_time_series_transformer_inputs_dict(config) + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def check_encoder_decoder_model_standalone(self, config, inputs_dict): + model = TimeSeriesTransformerModel(config=config).to(torch_device).eval() + outputs = model(**inputs_dict) + + encoder_last_hidden_state = outputs.encoder_last_hidden_state + last_hidden_state = outputs.last_hidden_state + + with tempfile.TemporaryDirectory() as tmpdirname: + encoder = model.get_encoder() + encoder.save_pretrained(tmpdirname) + encoder = TimeSeriesTransformerEncoder.from_pretrained(tmpdirname).to(torch_device) + + transformer_inputs, _, _, _ = model.create_network_inputs(**inputs_dict) + enc_input = transformer_inputs[:, : config.context_length, ...] + dec_input = transformer_inputs[:, config.context_length :, ...] + + encoder_last_hidden_state_2 = encoder(inputs_embeds=enc_input)[0] + + self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3) + + with tempfile.TemporaryDirectory() as tmpdirname: + decoder = model.get_decoder() + decoder.save_pretrained(tmpdirname) + decoder = TimeSeriesTransformerDecoder.from_pretrained(tmpdirname).to(torch_device) + + last_hidden_state_2 = decoder( + inputs_embeds=dec_input, + encoder_hidden_states=encoder_last_hidden_state, + )[0] + + self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3) + + +@require_torch +class TimeSeriesTransformerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (TimeSeriesTransformerModel, TimeSeriesTransformerForPrediction) if is_torch_available() else () + ) + all_generative_model_classes = (TimeSeriesTransformerForPrediction,) if is_torch_available() else () + pipeline_model_mapping = {"feature-extraction": TimeSeriesTransformerModel} if is_torch_available() else {} + is_encoder_decoder = True + test_pruning = False + test_head_masking = False + test_missing_keys = False + test_torchscript = False + test_inputs_embeds = False + test_model_common_attributes = False + + def setUp(self): + self.model_tester = TimeSeriesTransformerModelTester(self) + self.config_tester = ConfigTester( + self, + config_class=TimeSeriesTransformerConfig, + has_text_modality=False, + prediction_length=self.model_tester.prediction_length, + ) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_save_load_strict(self): + config, _ = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) + self.assertEqual(info["missing_keys"], []) + + 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) + + # Ignore since we have no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # # Input is 'static_categorical_features' not 'input_ids' + def test_model_main_input_name(self): + model_signature = inspect.signature(getattr(TimeSeriesTransformerModel, "forward")) + # The main input is the name of the argument after `self` + observed_main_input_name = list(model_signature.parameters.keys())[1] + self.assertEqual(TimeSeriesTransformerModel.main_input_name, observed_main_input_name) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "past_values", + "past_time_features", + "past_observed_mask", + "static_categorical_features", + "static_real_features", + "future_values", + "future_time_features", + ] + + expected_arg_names.extend( + [ + "future_observed_mask", + "decoder_attention_mask", + "head_mask", + "decoder_head_mask", + "cross_attn_head_mask", + "encoder_outputs", + "past_key_values", + "output_hidden_states", + "output_attentions", + "use_cache", + "return_dict", + ] + if "future_observed_mask" in arg_names + else [ + "decoder_attention_mask", + "head_mask", + "decoder_head_mask", + "cross_attn_head_mask", + "encoder_outputs", + "past_key_values", + "output_hidden_states", + "output_attentions", + "use_cache", + "return_dict", + ] + ) + + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_seq_length], + ) + out_len = len(outputs) + + correct_outlen = 7 + + if "last_hidden_state" in outputs: + correct_outlen += 1 + + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + if "loss" in outputs: + correct_outlen += 1 + + if "params" in outputs: + correct_outlen += 1 + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_seq_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + encoder_seq_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 2, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_seq_length], + ) + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + @parameterized.expand( + [ + (1, 5, [1]), + (1, 5, [1, 10, 15]), + (1, 5, [3, 6, 9, 10]), + (2, 5, [1, 2, 7]), + (2, 5, [2, 3, 4, 6]), + (4, 5, [1, 5, 9, 11]), + (4, 5, [7, 8, 13, 14]), + ], + ) + def test_create_network_inputs(self, prediction_length, context_length, lags_sequence): + history_length = max(lags_sequence) + context_length + + config = TimeSeriesTransformerConfig( + prediction_length=prediction_length, + context_length=context_length, + lags_sequence=lags_sequence, + scaling=False, + num_parallel_samples=10, + num_static_categorical_features=1, + cardinality=[1], + embedding_dimension=[2], + num_static_real_features=1, + ) + model = TimeSeriesTransformerModel(config) + + batch = { + "static_categorical_features": torch.tensor([[0]], dtype=torch.int64), + "static_real_features": torch.tensor([[0.0]], dtype=torch.float32), + "past_time_features": torch.arange(history_length, dtype=torch.float32).view(1, history_length, 1), + "past_values": torch.arange(history_length, dtype=torch.float32).view(1, history_length), + "past_observed_mask": torch.arange(history_length, dtype=torch.float32).view(1, history_length), + } + + # test with no future_target (only one step prediction) + batch["future_time_features"] = torch.arange(history_length, history_length + 1, dtype=torch.float32).view( + 1, 1, 1 + ) + transformer_inputs, loc, scale, _ = model.create_network_inputs(**batch) + + self.assertTrue((scale == 1.0).all()) + assert (loc == 0.0).all() + + ref = torch.arange(max(lags_sequence), history_length, dtype=torch.float32) + + for idx, lag in enumerate(lags_sequence): + assert torch.isclose(ref - lag, transformer_inputs[0, :, idx]).all() + + # test with all future data + batch["future_time_features"] = torch.arange( + history_length, history_length + prediction_length, dtype=torch.float32 + ).view(1, prediction_length, 1) + batch["future_values"] = torch.arange( + history_length, history_length + prediction_length, dtype=torch.float32 + ).view(1, prediction_length) + transformer_inputs, loc, scale, _ = model.create_network_inputs(**batch) + + assert (scale == 1.0).all() + assert (loc == 0.0).all() + + ref = torch.arange(max(lags_sequence), history_length + prediction_length, dtype=torch.float32) + + for idx, lag in enumerate(lags_sequence): + assert torch.isclose(ref - lag, transformer_inputs[0, :, idx]).all() + + # test for generation + batch.pop("future_values") + transformer_inputs, loc, scale, _ = model.create_network_inputs(**batch) + + lagged_sequence = model.get_lagged_subsequences( + sequence=batch["past_values"], + subsequences_length=1, + shift=1, + ) + # assert that the last element of the lagged sequence is the one after the encoders input + assert transformer_inputs[0, ..., 0][-1] + 1 == lagged_sequence[0, ..., 0][-1] + + future_values = torch.arange(history_length, history_length + prediction_length, dtype=torch.float32).view( + 1, prediction_length + ) + # assert that the first element of the future_values is offset by lag after the decoders input + assert lagged_sequence[0, ..., 0][-1] + lags_sequence[0] == future_values[0, ..., 0] + + @is_flaky() + def test_retain_grad_hidden_states_attentions(self): + super().test_retain_grad_hidden_states_attentions() + + +def prepare_batch(filename="train-batch.pt"): + file = hf_hub_download(repo_id="hf-internal-testing/tourism-monthly-batch", filename=filename, repo_type="dataset") + batch = torch.load(file, map_location=torch_device) + return batch + + +@require_torch +@slow +class TimeSeriesTransformerModelIntegrationTests(unittest.TestCase): + def test_inference_no_head(self): + model = TimeSeriesTransformerModel.from_pretrained("huggingface/time-series-transformer-tourism-monthly").to( + torch_device + ) + batch = prepare_batch() + + with torch.no_grad(): + output = model( + past_values=batch["past_values"], + past_time_features=batch["past_time_features"], + past_observed_mask=batch["past_observed_mask"], + static_categorical_features=batch["static_categorical_features"], + static_real_features=batch["static_real_features"], + future_values=batch["future_values"], + future_time_features=batch["future_time_features"], + ).last_hidden_state + + expected_shape = torch.Size((64, model.config.context_length, model.config.d_model)) + self.assertEqual(output.shape, expected_shape) + + expected_slice = torch.tensor( + [[0.8196, -1.5131, 1.4620], [1.1268, -1.3238, 1.5997], [1.5098, -1.0715, 1.7359]], device=torch_device + ) + self.assertTrue(torch.allclose(output[0, :3, :3], expected_slice, atol=TOLERANCE)) + + def test_inference_head(self): + model = TimeSeriesTransformerForPrediction.from_pretrained( + "huggingface/time-series-transformer-tourism-monthly" + ).to(torch_device) + batch = prepare_batch("val-batch.pt") + with torch.no_grad(): + output = model( + past_values=batch["past_values"], + past_time_features=batch["past_time_features"], + past_observed_mask=batch["past_observed_mask"], + static_categorical_features=batch["static_categorical_features"], + static_real_features=batch["static_real_features"], + future_time_features=batch["future_time_features"], + ).encoder_last_hidden_state + expected_shape = torch.Size((64, model.config.context_length, model.config.d_model)) + self.assertEqual(output.shape, expected_shape) + + expected_slice = torch.tensor( + [[-1.2957, -1.0280, -0.6045], [-0.7017, -0.8193, -0.3717], [-1.0449, -0.8149, 0.1405]], device=torch_device + ) + self.assertTrue(torch.allclose(output[0, :3, :3], expected_slice, atol=TOLERANCE)) + + def test_seq_to_seq_generation(self): + model = TimeSeriesTransformerForPrediction.from_pretrained( + "huggingface/time-series-transformer-tourism-monthly" + ).to(torch_device) + batch = prepare_batch("val-batch.pt") + with torch.no_grad(): + outputs = model.generate( + static_categorical_features=batch["static_categorical_features"], + static_real_features=batch["static_real_features"], + past_time_features=batch["past_time_features"], + past_values=batch["past_values"], + future_time_features=batch["future_time_features"], + past_observed_mask=batch["past_observed_mask"], + ) + expected_shape = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length)) + self.assertEqual(outputs.sequences.shape, expected_shape) + + expected_slice = torch.tensor([2825.2749, 3584.9207, 6763.9951], device=torch_device) + mean_prediction = outputs.sequences.mean(dim=1) + self.assertTrue(torch.allclose(mean_prediction[0, -3:], expected_slice, rtol=1e-1)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timesformer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timesformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timesformer/test_modeling_timesformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timesformer/test_modeling_timesformer.py new file mode 100644 index 0000000000000000000000000000000000000000..d4e71c8c599967f8edfd6b3fb552dbbed9e45458 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timesformer/test_modeling_timesformer.py @@ -0,0 +1,357 @@ +# coding=utf-8 +# Copyright 2022 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 TimeSformer model. """ + + +import copy +import unittest + +import numpy as np +from huggingface_hub import hf_hub_download + +from transformers import TimesformerConfig +from transformers.models.auto import get_values +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ( + MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, + TimesformerForVideoClassification, + TimesformerModel, + ) + from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from transformers import VideoMAEImageProcessor + + +class TimesformerModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=10, + num_channels=3, + patch_size=2, + num_frames=2, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + num_labels=10, + initializer_range=0.02, + attention_type="divided_space_time", + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.patch_size = patch_size + self.num_frames = num_frames + self.is_training = is_training + self.use_labels = use_labels + 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.attention_type = attention_type + self.initializer_range = initializer_range + self.scope = scope + self.num_labels = num_labels + + # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token + self.num_patches_per_frame = (image_size // patch_size) ** 2 + self.seq_length = (num_frames) * self.num_patches_per_frame + 1 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor( + [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] + ) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.num_labels) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + config = TimesformerConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + num_frames=self.num_frames, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + attention_type=self.attention_type, + ) + config.num_labels = self.num_labels + return config + + def create_and_check_model(self, config, pixel_values, labels): + model = TimesformerModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_video_classification(self, config, pixel_values, labels): + model = TimesformerForVideoClassification(config) + model.to(torch_device) + model.eval() + + result = model(pixel_values) + + # verify the logits shape + expected_shape = torch.Size((self.batch_size, self.num_labels)) + self.parent.assertEqual(result.logits.shape, expected_shape) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class TimesformerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as TimeSformer does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} + if is_torch_available() + else {} + ) + + test_pruning = False + test_torchscript = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = TimesformerModelTester(self) + self.config_tester = ConfigTester( + self, config_class=TimesformerConfig, has_text_modality=False, hidden_size=37 + ) + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = copy.deepcopy(inputs_dict) + + if return_labels: + if model_class in get_values(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING): + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + + return inputs_dict + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="TimeSformer does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_video_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_video_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TimesformerModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_attention_outputs(self): + if not self.has_attentions: + pass + + else: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + seq_len = self.model_tester.seq_length + num_frames = self.model_tester.num_frames + + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + + # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + expected_num_layers = self.model_tester.num_hidden_layers + 1 + self.assertEqual(len(hidden_states), expected_num_layers) + + seq_length = self.model_tester.seq_length + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + +# We will verify our results on a video of eating spaghetti +# Frame indices used: [164 168 172 176 181 185 189 193 198 202 206 210 215 219 223 227] +def prepare_video(): + file = hf_hub_download( + repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti.npy", repo_type="dataset" + ) + video = np.load(file) + return list(video) + + +@require_torch +@require_vision +class TimesformerModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + # logits were tested with a different mean and std, so we use the same here + return ( + VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]) + if is_vision_available() + else None + ) + + @slow + def test_inference_for_video_classification(self): + model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400").to( + torch_device + ) + + image_processor = self.default_image_processor + video = prepare_video() + inputs = image_processor(video[:8], return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 400)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-0.3016, -0.7713, -0.4205]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timm_backbone/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timm_backbone/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timm_backbone/test_modeling_timm_backbone.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timm_backbone/test_modeling_timm_backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..60ab9e2a217eb5e14a67565ff9471ac92912ac01 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/timm_backbone/test_modeling_timm_backbone.py @@ -0,0 +1,275 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import inspect +import unittest + +from transformers import AutoBackbone +from transformers.configuration_utils import PretrainedConfig +from transformers.testing_utils import require_timm, require_torch, torch_device +from transformers.utils.import_utils import is_torch_available + +from ...test_backbone_common import BackboneTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor + + +if is_torch_available(): + import torch + + from transformers import TimmBackbone, TimmBackboneConfig + +from ...test_pipeline_mixin import PipelineTesterMixin + + +class TimmBackboneModelTester: + def __init__( + self, + parent, + out_indices=None, + out_features=None, + stage_names=None, + backbone="resnet18", + batch_size=3, + image_size=32, + num_channels=3, + is_training=True, + use_pretrained_backbone=True, + ): + self.parent = parent + self.out_indices = out_indices if out_indices is not None else [4] + self.stage_names = stage_names + self.out_features = out_features + self.backbone = backbone + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.use_pretrained_backbone = use_pretrained_backbone + self.is_training = is_training + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + config = self.get_config() + + return config, pixel_values + + def get_config(self): + return TimmBackboneConfig( + image_size=self.image_size, + num_channels=self.num_channels, + out_features=self.out_features, + out_indices=self.out_indices, + stage_names=self.stage_names, + use_pretrained_backbone=self.use_pretrained_backbone, + backbone=self.backbone, + ) + + def create_and_check_model(self, config, pixel_values): + model = TimmBackbone(config=config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + result = model(pixel_values) + self.parent.assertEqual( + result.feature_map[-1].shape, + (self.batch_size, model.channels[-1], 14, 14), + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +@require_timm +class TimmBackboneModelTest(ModelTesterMixin, BackboneTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (TimmBackbone,) if is_torch_available() else () + pipeline_model_mapping = {"feature-extraction": TimmBackbone} if is_torch_available() else {} + test_resize_embeddings = False + test_head_masking = False + test_pruning = False + has_attentions = False + + def setUp(self): + self.config_class = PretrainedConfig + self.model_tester = TimmBackboneModelTester(self) + self.config_tester = ConfigTester(self, config_class=self.config_class, has_text_modality=False) + + def test_config(self): + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def test_timm_transformer_backbone_equivalence(self): + timm_checkpoint = "resnet18" + transformers_checkpoint = "microsoft/resnet-18" + + timm_model = AutoBackbone.from_pretrained(timm_checkpoint, use_timm_backbone=True) + transformers_model = AutoBackbone.from_pretrained(transformers_checkpoint) + + self.assertEqual(len(timm_model.out_features), len(transformers_model.out_features)) + self.assertEqual(len(timm_model.stage_names), len(transformers_model.stage_names)) + self.assertEqual(timm_model.channels, transformers_model.channels) + # Out indices are set to the last layer by default. For timm models, we don't know + # the number of layers in advance, so we set it to (-1,), whereas for transformers + # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). + self.assertEqual(timm_model.out_indices, (-1,)) + self.assertEqual(transformers_model.out_indices, [len(timm_model.stage_names) - 1]) + + timm_model = AutoBackbone.from_pretrained(timm_checkpoint, use_timm_backbone=True, out_indices=[1, 2, 3]) + transformers_model = AutoBackbone.from_pretrained(transformers_checkpoint, out_indices=[1, 2, 3]) + + self.assertEqual(timm_model.out_indices, transformers_model.out_indices) + self.assertEqual(len(timm_model.out_features), len(transformers_model.out_features)) + self.assertEqual(timm_model.channels, transformers_model.channels) + + @unittest.skip("TimmBackbone doesn't support feed forward chunking") + def test_feed_forward_chunking(self): + pass + + @unittest.skip("TimmBackbone doesn't have num_hidden_layers attribute") + def test_hidden_states_output(self): + pass + + @unittest.skip("TimmBackbone initialization is managed on the timm side") + def test_initialization(self): + pass + + @unittest.skip("TimmBackbone models doesn't have inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip("TimmBackbone models doesn't have inputs_embeds") + def test_model_common_attributes(self): + pass + + @unittest.skip("TimmBackbone model cannot be created without specifying a backbone checkpoint") + def test_from_pretrained_no_checkpoint(self): + pass + + @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone") + def test_save_load(self): + pass + + @unittest.skip("model weights aren't tied in TimmBackbone.") + def test_tie_model_weights(self): + pass + + @unittest.skip("model weights aren't tied in TimmBackbone.") + def test_tied_model_weights_key_ignore(self): + pass + + @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone") + def test_load_save_without_tied_weights(self): + pass + + @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone") + def test_model_weights_reload_no_missing_tied_weights(self): + pass + + @unittest.skip("TimmBackbone doesn't have hidden size info in its configuration.") + def test_channels(self): + pass + + @unittest.skip("TimmBackbone doesn't support output_attentions.") + def test_torchscript_output_attentions(self): + pass + + @unittest.skip("Safetensors is not supported by timm.") + def test_can_use_safetensors(self): + pass + + @unittest.skip("Need to use a timm backbone and there is no tiny model available.") + def test_model_is_small(self): + pass + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + inputs = self._prepare_for_class(inputs_dict, model_class) + outputs = model(**inputs) + output = outputs[0][-1] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + hidden_states.retain_grad() + + if self.has_attentions: + attentions = outputs.attentions[0] + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + + if self.has_attentions: + self.assertIsNotNone(attentions.grad) + + # TimmBackbone config doesn't have out_features attribute + def test_create_from_modified_config(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + self.assertEqual(len(result.feature_maps), len(config.out_indices)) + self.assertEqual(len(model.channels), len(config.out_indices)) + + # Check output of last stage is taken if out_features=None, out_indices=None + modified_config = copy.deepcopy(config) + modified_config.out_indices = None + model = model_class(modified_config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + self.assertEqual(len(result.feature_maps), 1) + self.assertEqual(len(model.channels), 1) + + # Check backbone can be initialized with fresh weights + modified_config = copy.deepcopy(config) + modified_config.use_pretrained_backbone = False + model = model_class(modified_config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/trocr/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/trocr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/trocr/test_modeling_trocr.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/trocr/test_modeling_trocr.py new file mode 100644 index 0000000000000000000000000000000000000000..da24c7dd430978c432c880e9bde7b10a3252b2e2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/trocr/test_modeling_trocr.py @@ -0,0 +1,198 @@ +# coding=utf-8 +# 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 TrOCR model. """ + +import unittest + +from transformers import TrOCRConfig +from transformers.testing_utils import is_torch_available, require_torch, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM + + +@require_torch +class TrOCRStandaloneDecoderModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + d_model=16, + decoder_seq_length=7, + is_training=True, + is_decoder=True, + use_attention_mask=True, + use_cache=False, + use_labels=True, + decoder_start_token_id=2, + decoder_ffn_dim=32, + decoder_layers=2, + decoder_attention_heads=4, + max_position_embeddings=30, + pad_token_id=0, + bos_token_id=1, + eos_token_id=2, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_labels = use_labels + + self.vocab_size = vocab_size + self.d_model = d_model + self.hidden_size = d_model + self.num_hidden_layers = decoder_layers + self.decoder_layers = decoder_layers + self.decoder_ffn_dim = decoder_ffn_dim + self.decoder_attention_heads = decoder_attention_heads + self.num_attention_heads = decoder_attention_heads + self.eos_token_id = eos_token_id + self.bos_token_id = bos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.use_cache = use_cache + self.max_position_embeddings = max_position_embeddings + + self.scope = None + self.decoder_key_length = decoder_seq_length + self.base_model_out_len = 2 + self.decoder_attention_idx = 1 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + attention_mask = None + if self.use_attention_mask: + attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2) + + lm_labels = None + if self.use_labels: + lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + config = TrOCRConfig( + vocab_size=self.vocab_size, + d_model=self.d_model, + decoder_layers=self.decoder_layers, + decoder_ffn_dim=self.decoder_ffn_dim, + decoder_attention_heads=self.decoder_attention_heads, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + use_cache=self.use_cache, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + max_position_embeddings=self.max_position_embeddings, + ) + + return (config, input_ids, attention_mask, lm_labels) + + def create_and_check_decoder_model_past( + self, + config, + input_ids, + attention_mask, + lm_labels, + ): + config.use_cache = True + model = TrOCRDecoder(config=config).to(torch_device).eval() + input_ids = input_ids[:2] + + input_ids[input_ids == 0] += 1 + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + past_key_values = outputs["past_key_values"] + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((2, 1), config.vocab_size - 1) + 1 + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, attention_mask, lm_labels = config_and_inputs + + inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class TrOCRStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () + all_generative_model_classes = (TrOCRForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = {"text-generation": TrOCRForCausalLM} if is_torch_available() else {} + fx_compatible = True + test_pruning = False + + def setUp(self): + self.model_tester = TrOCRStandaloneDecoderModelTester(self, is_training=False) + self.config_tester = ConfigTester(self, config_class=TrOCRConfig) + + # not implemented currently + def test_inputs_embeds(self): + pass + + # trocr has no base model + def test_save_load_fast_init_from_base(self): + pass + + # trocr has no base model + def test_save_load_fast_init_to_base(self): + pass + + def test_config(self): + self.config_tester.run_common_tests() + + def test_decoder_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_past(*config_and_inputs) + + # decoder cannot keep gradients + def test_retain_grad_hidden_states_attentions(self): + return + + @unittest.skip("The model doesn't support left padding") # and it's not used enough to be worth fixing :) + def test_left_padding_compatibility(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_feature_extraction_tvlt.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_feature_extraction_tvlt.py new file mode 100644 index 0000000000000000000000000000000000000000..e2d8c624b0b78a8266d03b0bfba0bb8941721623 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_feature_extraction_tvlt.py @@ -0,0 +1,182 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 TVLT feature extraction. """ + +import itertools +import random +import unittest + +import numpy as np + +from transformers import TvltFeatureExtractor, is_datasets_available +from transformers.testing_utils import require_torch, require_torchaudio +from transformers.utils.import_utils import is_torch_available + +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +if is_torch_available(): + import torch + +if is_datasets_available(): + from datasets import load_dataset + +global_rng = random.Random() + + +# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +class TvltFeatureExtractionTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + min_seq_length=400, + max_seq_length=2000, + spectrogram_length=2048, + feature_size=128, + num_audio_channels=1, + hop_length=512, + chunk_length=30, + sampling_rate=44100, + ): + self.parent = parent + self.batch_size = batch_size + self.min_seq_length = min_seq_length + self.max_seq_length = max_seq_length + self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) + self.spectrogram_length = spectrogram_length + self.feature_size = feature_size + self.num_audio_channels = num_audio_channels + self.hop_length = hop_length + self.chunk_length = chunk_length + self.sampling_rate = sampling_rate + + def prepare_feat_extract_dict(self): + return { + "spectrogram_length": self.spectrogram_length, + "feature_size": self.feature_size, + "num_audio_channels": self.num_audio_channels, + "hop_length": self.hop_length, + "chunk_length": self.chunk_length, + "sampling_rate": self.sampling_rate, + } + + def prepare_inputs_for_common(self, equal_length=False, numpify=False): + def _flatten(list_of_lists): + return list(itertools.chain(*list_of_lists)) + + if equal_length: + speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] + else: + # make sure that inputs increase in size + speech_inputs = [ + floats_list((x, self.feature_size)) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + return speech_inputs + + +@require_torch +@require_torchaudio +class TvltFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = TvltFeatureExtractor + + def setUp(self): + self.feat_extract_tester = TvltFeatureExtractionTester(self) + + def test_feat_extract_properties(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) + self.assertTrue(hasattr(feature_extractor, "spectrogram_length")) + self.assertTrue(hasattr(feature_extractor, "feature_size")) + self.assertTrue(hasattr(feature_extractor, "num_audio_channels")) + self.assertTrue(hasattr(feature_extractor, "hop_length")) + self.assertTrue(hasattr(feature_extractor, "chunk_length")) + self.assertTrue(hasattr(feature_extractor, "sampling_rate")) + + def test_call(self): + # Initialize feature_extractor + feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) + + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test not batched input + encoded_audios = feature_extractor(np_speech_inputs[0], return_tensors="np", sampling_rate=44100).audio_values + + self.assertTrue(encoded_audios.ndim == 4) + self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size) + self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length) + self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels) + + # Test batched + encoded_audios = feature_extractor(np_speech_inputs, return_tensors="np", sampling_rate=44100).audio_values + + self.assertTrue(encoded_audios.ndim == 4) + self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size) + self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length) + self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels) + + # Test audio masking + encoded_audios = feature_extractor( + np_speech_inputs, return_tensors="np", sampling_rate=44100, mask_audio=True + ).audio_values + + self.assertTrue(encoded_audios.ndim == 4) + self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size) + self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length) + self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels) + + # Test 2-D numpy arrays are batched. + speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] + np_speech_inputs = np.asarray(speech_inputs) + encoded_audios = feature_extractor(np_speech_inputs, return_tensors="np", sampling_rate=44100).audio_values + self.assertTrue(encoded_audios.ndim == 4) + self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size) + self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length) + self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels) + + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_integration(self): + input_speech = self._load_datasamples(1) + feature_extractor = TvltFeatureExtractor() + audio_values = feature_extractor(input_speech, return_tensors="pt").audio_values + + self.assertEquals(audio_values.shape, (1, 1, 192, 128)) + + expected_slice = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]]) + self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_image_processor_tvlt.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_image_processor_tvlt.py new file mode 100644 index 0000000000000000000000000000000000000000..8677a86665f326c7ea944b986dbe3d468ecc8431 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_image_processor_tvlt.py @@ -0,0 +1,294 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 TVLT image processor. """ + +import unittest + +import numpy as np + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + from transformers import TvltImageProcessor + + +def prepare_video(image_processor_tester, width=10, height=10, numpify=False, torchify=False): + """This function prepares a video as a list of PIL images/NumPy arrays/PyTorch tensors.""" + + video = [] + for i in range(image_processor_tester.num_frames): + video.append(np.random.randint(255, size=(image_processor_tester.num_channels, width, height), dtype=np.uint8)) + + if not numpify and not torchify: + # PIL expects the channel dimension as last dimension + video = [Image.fromarray(np.moveaxis(frame, 0, -1)) for frame in video] + + if torchify: + video = [torch.from_numpy(frame) for frame in video] + + return video + + +def prepare_video_inputs(image_processor_tester, equal_resolution=False, numpify=False, torchify=False): + """This function prepares a batch of videos: a list of list of PIL images, or a list of list of numpy arrays if + one specifies numpify=True, or a list of list of PyTorch tensors if one specifies torchify=True. + One can specify whether the videos are of the same resolution or not. + """ + + assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" + + video_inputs = [] + for i in range(image_processor_tester.batch_size): + if equal_resolution: + width = height = image_processor_tester.max_resolution + else: + width, height = np.random.choice( + np.arange(image_processor_tester.min_resolution, image_processor_tester.max_resolution), 2 + ) + video = prepare_video( + image_processor_tester=image_processor_tester, + width=width, + height=height, + numpify=numpify, + torchify=torchify, + ) + video_inputs.append(video) + + return video_inputs + + +class TvltImageProcessorTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + num_frames=4, + image_size=18, + min_resolution=30, + max_resolution=400, + do_resize=True, + size=None, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + do_center_crop=True, + crop_size=None, + ): + size = size if size is not None else {"shortest_edge": 18} + crop_size = crop_size if crop_size is not None else {"height": 18, "width": 18} + + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.num_frames = num_frames + self.image_size = image_size + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + self.do_center_crop = do_center_crop + self.crop_size = crop_size + + def prepare_image_processor_dict(self): + return { + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_normalize": self.do_normalize, + "do_resize": self.do_resize, + "size": self.size, + "do_center_crop": self.do_center_crop, + "crop_size": self.crop_size, + } + + +@require_torch +@require_vision +class TvltImageProcessorTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = TvltImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = TvltImageProcessorTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processor = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processor, "image_mean")) + self.assertTrue(hasattr(image_processor, "image_std")) + self.assertTrue(hasattr(image_processor, "do_normalize")) + self.assertTrue(hasattr(image_processor, "do_resize")) + self.assertTrue(hasattr(image_processor, "do_center_crop")) + self.assertTrue(hasattr(image_processor, "size")) + + def test_call_pil(self): + # Initialize image_processor + image_processor = self.image_processing_class(**self.image_processor_dict) + # create random PIL videos + video_inputs = prepare_video_inputs(self.image_processor_tester, equal_resolution=False) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], Image.Image) + + # Test not batched input + encoded_videos = image_processor(video_inputs[0], return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + 1, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + self.image_processor_tester.crop_size["height"], + self.image_processor_tester.crop_size["width"], + ), + ) + + # Test batched + encoded_videos = image_processor(video_inputs, return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + self.image_processor_tester.crop_size["height"], + self.image_processor_tester.crop_size["width"], + ), + ) + + def test_call_numpy(self): + # Initialize image_processor + image_processor = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + video_inputs = prepare_video_inputs(self.image_processor_tester, equal_resolution=False, numpify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], np.ndarray) + + # Test not batched input + encoded_videos = image_processor(video_inputs[0], return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + 1, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + self.image_processor_tester.crop_size["height"], + self.image_processor_tester.crop_size["width"], + ), + ) + + # Test batched + encoded_videos = image_processor(video_inputs, return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + self.image_processor_tester.crop_size["height"], + self.image_processor_tester.crop_size["width"], + ), + ) + + def test_call_numpy_4_channels(self): + # Initialize image_processor + image_processor = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + self.image_processor_tester.num_channels = 4 + video_inputs = prepare_video_inputs(self.image_processor_tester, equal_resolution=False, numpify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], np.ndarray) + + # Test not batched input + encoded_videos = image_processor( + video_inputs[0], return_tensors="pt", input_data_format="channels_first", image_mean=0, image_std=1 + ).pixel_values + self.assertEqual( + encoded_videos.shape, + ( + 1, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + self.image_processor_tester.crop_size["height"], + self.image_processor_tester.crop_size["width"], + ), + ) + + # Test batched + encoded_videos = image_processor( + video_inputs, return_tensors="pt", input_data_format="channels_first", image_mean=0, image_std=1 + ).pixel_values + self.assertEqual( + encoded_videos.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + self.image_processor_tester.crop_size["height"], + self.image_processor_tester.crop_size["width"], + ), + ) + self.image_processor_tester.num_channels = 3 + + def test_call_pytorch(self): + # Initialize image_processor + image_processor = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + video_inputs = prepare_video_inputs(self.image_processor_tester, equal_resolution=False, torchify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], torch.Tensor) + + # Test not batched input + encoded_videos = image_processor(video_inputs[0], return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + 1, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + self.image_processor_tester.crop_size["height"], + self.image_processor_tester.crop_size["width"], + ), + ) + + # Test batched + encoded_videos = image_processor(video_inputs, return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + self.image_processor_tester.crop_size["height"], + self.image_processor_tester.crop_size["width"], + ), + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_modeling_tvlt.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_modeling_tvlt.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee7f7adc7ffd5a0499c289afb78a950694767ea --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_modeling_tvlt.py @@ -0,0 +1,626 @@ +# coding=utf-8 +# Copyright 2023 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 TVLT model. """ + +import copy +import inspect +import unittest + +import numpy as np +from huggingface_hub import hf_hub_download + +from transformers import ( + TvltConfig, + is_datasets_available, + is_speech_available, + is_torch_available, + is_vision_available, +) +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + import torch.nn as nn + + from transformers import TvltForAudioVisualClassification, TvltForPreTraining, TvltModel + from transformers.models.tvlt.modeling_tvlt import TVLT_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_datasets_available(): + from datasets import load_dataset + +if is_vision_available(): + from transformers import TvltImageProcessor + +if is_speech_available(): + from transformers import TvltFeatureExtractor + + +class TvltModelTester: + def __init__( + self, + parent, + batch_size=2, + image_size=32, + spectrogram_length=32, + frequency_length=16, + image_patch_size=[2, 2], + audio_patch_size=[2, 2], + num_image_channels=3, + num_audio_channels=1, + num_frames=2, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=128, + hidden_act="gelu", + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + initializer_range=0.02, + layer_norm_eps=1e-12, + qkv_bias=True, + use_mean_pooling=True, + decoder_num_attention_heads=4, + decoder_hidden_size=32, + decoder_num_hidden_layers=2, + decoder_intermediate_size=128, + image_mask_ratio=0.75, + audio_mask_ratio=0.15, + audio_mask_type="frame-level", + task_matching=True, + task_mae=True, + num_labels=1, + is_training=True, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.spectrogram_length = spectrogram_length + self.frequency_length = frequency_length + self.image_patch_size = image_patch_size + self.audio_patch_size = audio_patch_size + self.num_image_channels = num_image_channels + self.num_audio_channels = num_audio_channels + self.num_frames = num_frames + + 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.initializer_range = initializer_range + self.layer_norm_eps = layer_norm_eps + self.qkv_bias = qkv_bias + self.use_mean_pooling = use_mean_pooling + + self.decoder_num_attention_heads = decoder_num_attention_heads + self.decoder_hidden_size = decoder_hidden_size + self.decoder_num_hidden_layers = decoder_num_hidden_layers + self.decoder_intermediate_size = decoder_intermediate_size + self.image_mask_ratio = image_mask_ratio + self.audio_mask_ratio = audio_mask_ratio + + self.task_matching = task_matching + self.task_mae = task_mae + self.num_labels = num_labels + + self.expected_pixel_seq_len = (self.image_size // self.image_patch_size[0]) ** 2 * self.num_frames + self.expected_audio_seq_len = (self.spectrogram_length // self.audio_patch_size[0]) * ( + self.frequency_length // self.audio_patch_size[1] + ) + # we set the expected sequence length (which is used in several tests) + # this is equal to the seq length of number of image/video patches + number of audio patches + self.expected_seq_len = self.expected_pixel_seq_len + self.expected_audio_seq_len + 1 + + self.image_mae_output_dim = image_patch_size[0] ** 2 * num_image_channels + self.audio_mae_output_dim = audio_patch_size[0] * audio_patch_size[1] * num_audio_channels + self.is_training = is_training + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor( + [self.batch_size, self.num_frames, self.num_image_channels, self.image_size, self.image_size] + ) + audio_values = floats_tensor( + [self.batch_size, self.num_audio_channels, self.spectrogram_length, self.frequency_length] + ) + + pixel_mask = floats_tensor([self.batch_size, self.expected_pixel_seq_len]) + audio_mask = floats_tensor([self.batch_size, self.expected_audio_seq_len]) + + config = self.get_config() + + return (config, pixel_values, audio_values, pixel_mask, audio_mask) + + def prepare_config_and_inputs_for_pretraining(self): + pixel_values = floats_tensor( + [self.batch_size, self.num_frames, self.num_image_channels, self.image_size, self.image_size] + ) + audio_values = floats_tensor( + [self.batch_size, self.num_audio_channels, self.spectrogram_length, self.frequency_length] + ) + + pixel_mask = floats_tensor([self.batch_size, self.expected_pixel_seq_len]) + audio_mask = floats_tensor([self.batch_size, self.expected_audio_seq_len]) + + pixel_values_mixed = floats_tensor( + [self.batch_size, self.num_frames, self.num_image_channels, self.image_size, self.image_size] + ) + pixel_mask_mixed = floats_tensor([self.batch_size, self.expected_pixel_seq_len]) + labels = floats_tensor([self.batch_size]) + config = self.get_config() + + return ( + config, + pixel_values, + audio_values, + pixel_mask, + audio_mask, + pixel_values_mixed, + pixel_mask_mixed, + labels, + ) + + def get_config(self): + return TvltConfig( + image_size=self.image_size, + spectrogram_length=self.spectrogram_length, + frequency_length=self.frequency_length, + image_patch_size=self.image_patch_size, + audio_patch_size=self.audio_patch_size, + num_image_channels=self.num_image_channels, + num_audio_channels=self.num_audio_channels, + num_frames=self.num_frames, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + layer_norm_eps=self.layer_norm_eps, + qkv_bias=self.qkv_bias, + use_mean_pooling=self.use_mean_pooling, + decoder_num_attention_heads=self.decoder_num_attention_heads, + decoder_hidden_size=self.decoder_hidden_size, + decoder_num_hidden_layers=self.decoder_num_hidden_layers, + decoder_intermediate_size=self.decoder_intermediate_size, + image_mask_ratio=self.image_mask_ratio, + audio_mask_ratio=self.audio_mask_ratio, + task_matching=self.task_matching, + task_mae=self.task_mae, + num_labels=self.num_labels, + ) + + def create_and_check_model(self, config, pixel_values, audio_values, pixel_mask, audio_mask): + model = TvltModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values, audio_values, pixel_mask=pixel_mask, audio_mask=audio_mask) + result = model(pixel_values, audio_values) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.expected_seq_len, self.hidden_size) + ) + + def create_and_check_for_audiovisual_classification( + self, config, pixel_values, audio_values, pixel_mask, audio_mask + ): + model = TvltForAudioVisualClassification(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values, audio_values, pixel_mask=pixel_mask, audio_mask=audio_mask) + result = model(pixel_values, audio_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_pretraining( + self, + config, + pixel_values, + audio_values, + pixel_mask, + audio_mask, + pixel_values_mixed, + pixel_mask_mixed, + labels, + ): + model = TvltForPreTraining(config=config) + model.to(torch_device) + model.train() + result = model( + pixel_values, + audio_values, + pixel_mask, + audio_mask, + pixel_values_mixed=pixel_values_mixed, + pixel_mask_mixed=pixel_mask_mixed, + labels=labels, + ) + self.parent.assertEqual( + result.pixel_logits.shape, (self.batch_size, self.expected_pixel_seq_len, self.image_mae_output_dim) + ) + self.parent.assertEqual( + result.audio_logits.shape, (self.batch_size, self.expected_audio_seq_len, self.audio_mae_output_dim) + ) + self.parent.assertEqual(result.matching_logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_pretraining_inference( + self, + config, + pixel_values, + audio_values, + pixel_mask, + audio_mask, + pixel_values_mixed, + pixel_mask_mixed, + labels, + ): + model = TvltForPreTraining(config=config) + model.to(torch_device) + model.eval() + result = model( + pixel_values, + audio_values, + pixel_mask, + audio_mask, + pixel_values_mixed=pixel_values_mixed, + pixel_mask_mixed=pixel_mask_mixed, + labels=labels, + ) + if result.pixel_logits is not None: + self.parent.assertEqual( + result.pixel_logits.shape, (self.batch_size, self.expected_pixel_seq_len, self.image_mae_output_dim) + ) + if result.audio_logits is not None: + self.parent.assertEqual( + result.audio_logits.shape, (self.batch_size, self.expected_audio_seq_len, self.audio_mae_output_dim) + ) + self.parent.assertEqual(result.matching_logits.shape, (self.batch_size, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + (config, pixel_values, audio_values, pixel_mask, audio_mask) = config_and_inputs + inputs_dict = { + "pixel_values": pixel_values, + "audio_values": audio_values, + "pixel_mask": pixel_mask, + "audio_mask": audio_mask, + } + return config, inputs_dict + + def prepare_pixel_values(self): + return floats_tensor( + [self.batch_size, self.num_frames, self.num_image_channels, self.image_size, self.image_size] + ) + + def prepare_audio_values(self): + return floats_tensor( + [self.batch_size, self.num_audio_channels, self.spectrogram_length, self.frequency_length] + ) + + +@require_torch +class TvltModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (TvltModel, TvltForPreTraining, TvltForAudioVisualClassification) if is_torch_available() else () + ) + pipeline_model_mapping = {"feature-extraction": TvltModel} if is_torch_available() else {} + + fx_compatible = False + test_pruning = False + test_headmasking = False + test_torchscript = False + test_resize_embeddings = False + main_input_name = "pixel_values" + + # TvltForAudioVisualClassification and TvltForPreTraining require special treatment + def _prepare_for_class(self, inputs_dict, model_class, return_labels=True): + inputs_dict = copy.deepcopy(inputs_dict) + + if return_labels: + if model_class.__name__ == "TvltForAudioVisualClassification": + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size,), dtype=torch.long, device=torch_device + ) + elif model_class.__name__ == "TvltForPreTraining": + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size,), dtype=torch.float, device=torch_device + ) + inputs_dict["pixel_values_mixed"] = torch.zeros( + ( + self.model_tester.batch_size, + self.model_tester.num_frames, + self.model_tester.num_image_channels, + self.model_tester.image_size, + self.model_tester.image_size, + ), + dtype=torch.float, + device=torch_device, + ) + inputs_dict["pixel_mask_mixed"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.expected_pixel_seq_len), + dtype=torch.float, + device=torch_device, + ) + + return inputs_dict + + def setUp(self): + self.model_tester = TvltModelTester(self) + self.config_tester = ConfigTester(self, config_class=TvltConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="TVLT does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + input_embeddings = model.get_input_embeddings() + self.assertIsInstance(input_embeddings, (tuple)) + for embedding in input_embeddings: + self.assertIsInstance(embedding, (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values", "audio_values"] + self.assertListEqual(arg_names[:2], expected_arg_names) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_audiovisual_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_audiovisual_classification(*config_and_inputs) + + def test_for_pretraining(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_pretraining() + self.model_tester.create_and_check_for_pretraining(*config_and_inputs) + self.model_tester.create_and_check_for_pretraining_inference(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in TVLT_PRETRAINED_MODEL_ARCHIVE_LIST: + model = TvltModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_training(self): + if not self.model_tester.is_training: + return + + for model_class in self.all_model_classes[1:]: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + model = model_class(config) + model.to(torch_device) + model.train() + inputs = self._prepare_for_class(inputs_dict, model_class) + for k, v in inputs.items(): + print(k, v.shape) + loss = model(**inputs).loss + loss.backward() + + def test_training_gradient_checkpointing(self): + if not self.model_tester.is_training: + return + + for model_class in self.all_model_classes[1:]: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.use_cache = False + config.return_dict = True + + model = model_class(config) + model.to(torch_device) + model.gradient_checkpointing_enable() + model.train() + inputs = self._prepare_for_class(inputs_dict, model_class) + loss = model(**inputs).loss + loss.backward() + + def test_attention_outputs(self): + if not self.has_attentions: + pass + + else: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes[2:]: + seq_len = self.model_tester.expected_seq_len + + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + expected_num_layers = self.model_tester.num_hidden_layers + 1 + self.assertEqual(len(hidden_states), expected_num_layers) + + seq_length = self.model_tester.expected_seq_len + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes[2:]: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + +# We will verify our results on a video of eating spaghetti +# Frame indices used: [164 168 172 176 181 185 189 193 198 202 206 210 215 219 223 227] +def prepare_video(num_frames=8): + file = hf_hub_download( + repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti.npy", repo_type="dataset" + ) + video = np.load(file)[:num_frames] + return list(video) + + +def prepare_audio(num_samples=1): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + return [x["array"] for x in speech_samples] + + +@require_torch +@require_vision +class TvltModelIntegrationTest(unittest.TestCase): + @cached_property + def default_processors(self): + # logits were tested with a different mean and std, so we use the same here + return ( + TvltImageProcessor() if is_vision_available() else None, + TvltFeatureExtractor(), + ) + + def test_inference_for_base_model(self): + model = TvltModel.from_pretrained("ZinengTang/tvlt-base").to(torch_device) + + image_processor, audio_feature_extractor = self.default_processors + video = prepare_video() + audio = prepare_audio() + video_inputs = image_processor(video, return_tensors="pt").to(torch_device) + audio_inputs = audio_feature_extractor(audio, return_tensors="pt").to(torch_device) + inputs = {} + inputs.update(video_inputs) + inputs.update(audio_inputs) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_last_hidden_state_slice = torch.tensor([[-0.0186, -0.0691], [0.0242, -0.0398]], device=torch_device) + self.assertTrue( + torch.allclose(outputs.last_hidden_state[:, :2, :2], expected_last_hidden_state_slice, atol=1e-4) + ) + + def test_inference_for_pretraining(self): + model = TvltForPreTraining.from_pretrained("ZinengTang/tvlt-base").to(torch_device) + + image_processor, audio_feature_extractor = self.default_processors + video = prepare_video() + video_mixed = prepare_video() + audio = prepare_audio() + video_inputs = image_processor(video, return_tensors="pt", mask_pixel=True).to(torch_device) + video_mixed_inputs = image_processor(video_mixed, is_mixed=True, return_tensors="pt").to(torch_device) + audio_inputs = audio_feature_extractor(audio, return_tensors="pt", mask_audio=True).to(torch_device) + labels = torch.tensor([[0.0]], device=torch_device) + inputs = {} + inputs.update(video_inputs) + inputs.update(video_mixed_inputs) + inputs.update(audio_inputs) + inputs.update({"labels": labels}) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_pixel_logits_shape = torch.Size([1, 1568, 768]) + expected_audio_logits_shape = torch.Size([1, 96, 256]) + expected_matching_logits_shape = torch.Size([1, 1]) + + if outputs.pixel_logits is not None: + self.assertEqual(outputs.pixel_logits.shape, expected_pixel_logits_shape) + if outputs.audio_logits is not None: + self.assertEqual(outputs.audio_logits.shape, expected_audio_logits_shape) + self.assertTrue(outputs.matching_logits.shape, expected_matching_logits_shape) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_processor_tvlt.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_processor_tvlt.py new file mode 100644 index 0000000000000000000000000000000000000000..83f59860fee4dad69a98853cb592bce9ff9d5dad --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvlt/test_processor_tvlt.py @@ -0,0 +1,116 @@ +# Copyright 2023 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 shutil +import tempfile +import unittest + +import numpy as np +import pytest + +from transformers import is_speech_available, is_vision_available +from transformers.testing_utils import require_torch + + +if is_vision_available(): + from transformers import TvltImageProcessor + +if is_speech_available(): + from transformers import TvltFeatureExtractor + +from transformers import TvltProcessor + + +@require_torch +class TvltProcessorTest(unittest.TestCase): + def setUp(self): + self.checkpoint = "ZinengTang/tvlt-base" + self.tmpdirname = tempfile.mkdtemp() + + def get_image_processor(self, **kwargs): + return TvltImageProcessor.from_pretrained(self.checkpoint, **kwargs) + + def get_feature_extractor(self, **kwargs): + return TvltFeatureExtractor.from_pretrained(self.checkpoint, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_save_load_pretrained_default(self): + image_processor = self.get_image_processor() + feature_extractor = self.get_feature_extractor() + + processor = TvltProcessor(image_processor=image_processor, feature_extractor=feature_extractor) + processor.save_pretrained(self.tmpdirname) + processor = TvltProcessor.from_pretrained(self.tmpdirname) + + self.assertIsInstance(processor.feature_extractor, TvltFeatureExtractor) + self.assertIsInstance(processor.image_processor, TvltImageProcessor) + + def test_feature_extractor(self): + image_processor = self.get_image_processor() + feature_extractor = self.get_feature_extractor() + + processor = TvltProcessor(image_processor=image_processor, feature_extractor=feature_extractor) + + audio = np.ones([12000]) + + audio_dict = feature_extractor(audio, return_tensors="np") + input_processor = processor(audio=audio, return_tensors="np") + + for key in audio_dict.keys(): + self.assertAlmostEqual(audio_dict[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_image_processor(self): + image_processor = self.get_image_processor() + feature_extractor = self.get_feature_extractor() + + processor = TvltProcessor(image_processor=image_processor, feature_extractor=feature_extractor) + + images = np.ones([3, 224, 224]) + + image_dict = image_processor(images, return_tensors="np") + input_processor = processor(images=images, return_tensors="np") + + for key in image_dict.keys(): + self.assertAlmostEqual(image_dict[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_processor(self): + image_processor = self.get_image_processor() + feature_extractor = self.get_feature_extractor() + + processor = TvltProcessor(image_processor=image_processor, feature_extractor=feature_extractor) + + audio = np.ones([12000]) + images = np.ones([3, 224, 224]) + + inputs = processor(audio=audio, images=images) + + self.assertListEqual(list(inputs.keys()), ["audio_values", "audio_mask", "pixel_values", "pixel_mask"]) + + # test if it raises when no input is passed + with pytest.raises(ValueError): + processor() + + def test_model_input_names(self): + image_processor = self.get_image_processor() + feature_extractor = self.get_feature_extractor() + + processor = TvltProcessor(image_processor=image_processor, feature_extractor=feature_extractor) + + self.assertListEqual( + processor.model_input_names, + image_processor.model_input_names + feature_extractor.model_input_names, + msg="`processor` and `image_processor`+`feature_extractor` model input names do not match", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvp/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvp/test_image_processing_tvp.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvp/test_image_processing_tvp.py new file mode 100644 index 0000000000000000000000000000000000000000..1c9a84beb8427b2fdaaf6f4f1a3ce974daa8e79f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvp/test_image_processing_tvp.py @@ -0,0 +1,306 @@ +# coding=utf-8 +# Copyright 2023 The Intel Team Authors, 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 unittest +from typing import Dict, List, Optional, Union + +import numpy as np + +from transformers.image_transforms import PaddingMode +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_video_inputs + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + from transformers import TvpImageProcessor + + +class TvpImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + do_resize: bool = True, + size: Dict[str, int] = {"longest_edge": 40}, + do_center_crop: bool = False, + crop_size: Dict[str, int] = None, + do_rescale: bool = False, + rescale_factor: Union[int, float] = 1 / 255, + do_pad: bool = True, + pad_size: Dict[str, int] = {"height": 80, "width": 80}, + fill: int = None, + pad_mode: PaddingMode = None, + do_normalize: bool = True, + image_mean: Optional[Union[float, List[float]]] = [0.48145466, 0.4578275, 0.40821073], + image_std: Optional[Union[float, List[float]]] = [0.26862954, 0.26130258, 0.27577711], + batch_size=2, + min_resolution=40, + max_resolution=80, + num_channels=3, + num_frames=2, + ): + self.do_resize = do_resize + self.size = size + self.do_center_crop = do_center_crop + self.crop_size = crop_size + self.do_rescale = do_rescale + self.rescale_factor = rescale_factor + self.do_pad = do_pad + self.pad_size = pad_size + self.fill = fill + self.pad_mode = pad_mode + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + self.batch_size = batch_size + self.num_channels = num_channels + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.num_frames = num_frames + + def prepare_image_processor_dict(self): + return { + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_normalize": self.do_normalize, + "do_resize": self.do_resize, + "size": self.size, + "do_rescale": self.do_rescale, + "do_center_crop": self.do_center_crop, + "do_pad": self.do_pad, + "pad_size": self.pad_size, + } + + def get_expected_values(self, image_inputs, batched=False): + """ + This function computes the expected height and width when providing images to TvpImageProcessor, + assuming do_resize is set to True with a scalar size. + """ + if not batched: + return (int(self.pad_size["height"]), int(self.pad_size["width"])) + + else: + expected_values = [] + for image in image_inputs: + expected_height, expected_width = self.get_expected_values([image]) + expected_values.append((expected_height, expected_width)) + expected_height = max(expected_values, key=lambda item: item[0])[0] + expected_width = max(expected_values, key=lambda item: item[1])[1] + + return expected_height, expected_width + + def prepare_video_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_video_inputs( + batch_size=self.batch_size, + num_frames=self.num_frames, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class TvpImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = TvpImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = TvpImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "do_center_crop")) + self.assertTrue(hasattr(image_processing, "size")) + self.assertTrue(hasattr(image_processing, "do_rescale")) + self.assertTrue(hasattr(image_processing, "do_pad")) + self.assertTrue(hasattr(image_processing, "pad_size")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"longest_edge": 40}) + + image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size={"longest_edge": 12}) + self.assertEqual(image_processor.size, {"longest_edge": 12}) + + def test_call_pil(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PIL videos + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], Image.Image) + + # Test not batched input + expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs) + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + 1, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + # Test batched + expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs, batched=True) + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + def test_call_numpy(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], np.ndarray) + + # Test not batched input + expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs) + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + 1, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + # Test batched + expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs, batched=True) + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + def test_call_numpy_4_channels(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], np.ndarray) + + # Test not batched input + expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs) + encoded_videos = image_processing( + video_inputs[0], return_tensors="pt", image_mean=0, image_std=1, input_data_format="channels_first" + ).pixel_values + self.assertEqual( + encoded_videos.shape, + ( + 1, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + # Test batched + expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs, batched=True) + encoded_videos = image_processing( + video_inputs, return_tensors="pt", image_mean=0, image_std=1, input_data_format="channels_first" + ).pixel_values + self.assertEqual( + encoded_videos.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + self.image_processor_tester.num_channels = 3 + + def test_call_pytorch(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, torchify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], torch.Tensor) + + # Test not batched input + expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs) + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + 1, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + # Test batched + expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs, batched=True) + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + self.assertEqual( + encoded_videos.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_frames, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvp/test_modeling_tvp.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvp/test_modeling_tvp.py new file mode 100644 index 0000000000000000000000000000000000000000..14ec02ed6fd9a91771347c4e95212c3058ded543 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/tvp/test_modeling_tvp.py @@ -0,0 +1,266 @@ +# coding=utf-8 +# Copyright 2023 The Intel Team Authors, 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 TVP model. """ + + +import unittest + +from transformers import ResNetConfig, TvpConfig +from transformers.testing_utils import require_torch, require_vision, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import TvpForVideoGrounding, TvpModel + +if is_vision_available(): + from PIL import Image + + from transformers import TvpImageProcessor + + +# Copied from test.models.videomae.test_modeling_videomae.VideoMAEModelTester with VideoMAE->TVP +class TVPModelTester: + def __init__( + self, + parent, + batch_size=1, + seq_length=2, + alpha=1.0, + beta=0.1, + visual_prompter_type="framepad", + visual_prompter_apply="replace", + num_frames=2, + max_img_size=448, + visual_prompt_size=96, + vocab_size=100, + hidden_size=32, + intermediate_size=32, + num_hidden_layers=2, + num_attention_heads=4, + max_position_embeddings=30, + max_grid_col_position_embeddings=30, + max_grid_row_position_embeddings=30, + hidden_dropout_prob=0.1, + hidden_act="gelu", + layer_norm_eps=1e-12, + initializer_range=0.02, + pad_token_id=0, + type_vocab_size=2, + attention_probs_dropout_prob=0.1, + ): + self.parent = parent + self.batch_size = batch_size + self.input_id_length = seq_length + self.seq_length = seq_length + 10 + 784 # include text prompt length and visual input length + self.alpha = alpha + self.beta = beta + self.visual_prompter_type = visual_prompter_type + self.visual_prompter_apply = visual_prompter_apply + self.num_frames = num_frames + self.max_img_size = max_img_size + self.visual_prompt_size = visual_prompt_size + 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.max_grid_col_position_embeddings = max_grid_col_position_embeddings + self.max_grid_row_position_embeddings = max_grid_row_position_embeddings + self.layer_norm_eps = layer_norm_eps + self.initializer_range = initializer_range + self.pad_token_id = pad_token_id + self.type_vocab_size = type_vocab_size + self.is_training = False + self.num_channels = 3 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.input_id_length], self.vocab_size) + attention_mask = random_attention_mask([self.batch_size, self.input_id_length]) + pixel_values = floats_tensor( + [self.batch_size, self.num_frames, self.num_channels, self.max_img_size, self.max_img_size] + ) + + config = self.get_config() + + return (config, input_ids, pixel_values, attention_mask) + + def get_config(self): + resnet_config = ResNetConfig( + num_channels=3, + embeddings_size=64, + hidden_sizes=[64, 128], + depths=[2, 2], + hidden_act="relu", + out_features=["stage2"], + out_indices=[2], + ) + return TvpConfig( + backbone_config=resnet_config, + alpha=self.alpha, + beta=self.beta, + visual_prompter_type=self.visual_prompter_type, + visual_prompter_apply=self.visual_prompter_apply, + num_frames=self.num_frames, + max_img_size=self.max_img_size, + visual_prompt_size=self.visual_prompt_size, + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + max_grid_col_position_embeddings=self.max_grid_col_position_embeddings, + max_grid_row_position_embeddings=self.max_grid_row_position_embeddings, + layer_norm_eps=self.layer_norm_eps, + initializer_range=self.initializer_range, + pad_token_id=self.pad_token_id, + type_vocab_size=self.type_vocab_size, + ) + + def create_and_check_model(self, config, input_ids, pixel_values, attention_mask): + model = TvpModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, pixel_values, attention_mask) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, pixel_values, attention_mask = config_and_inputs + inputs_dict = {"input_ids": input_ids, "pixel_values": pixel_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class TVPModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as TVP does not use, inputs_embeds. + The seq_length in TVP contain textual and visual inputs, and prompt. + """ + + all_model_classes = (TvpModel, TvpForVideoGrounding) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": TvpModel, "temporal-video-grounding": TvpForVideoGrounding} + if is_torch_available() + else {} + ) + + # TODO: Enable this once this model gets more usage + test_torchscript = False + + def setUp(self): + self.model_tester = TVPModelTester(self) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @unittest.skip(reason="TVP does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="TVPModel does not have input/output embeddings") + def test_model_common_attributes(self): + pass + + # override as the `logit_scale` parameter initilization is different for TVP + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if param.requires_grad: + # params are randomly initialized. + self.assertAlmostEqual( + param.data.mean().item(), + 0.0, + delta=1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_vision +@require_torch +class TvpModelIntegrationTests(unittest.TestCase): + @cached_property + def default_image_processor(self): + return TvpImageProcessor.from_pretrained("Jiqing/tiny-random-tvp") if is_vision_available() else None + + def test_inference_no_head(self): + model = TvpModel.from_pretrained("Jiqing/tiny-random-tvp").to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + encoding = image_processor(images=image, return_tensors="pt") + input_ids = torch.tensor([[1, 2]]) + attention_mask = torch.tensor([[1, 1]]) + encoding.update({"input_ids": input_ids, "attention_mask": attention_mask}) + encoding.to(torch_device) + + with torch.no_grad(): + outputs = model(**encoding) + + expected_shape = torch.Size((1, 796, 128)) + assert outputs.last_hidden_state.shape == expected_shape + expected_slice = torch.tensor( + [[-0.4902, -0.4121, -1.7872], [-0.2184, 2.1211, -0.9371], [0.1180, 0.5003, -0.1727]] + ).to(torch_device) + self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4)) + + def test_inference_with_head(self): + model = TvpForVideoGrounding.from_pretrained("Jiqing/tiny-random-tvp").to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + encoding = image_processor(images=image, return_tensors="pt") + input_ids = torch.tensor([[1, 2]]) + attention_mask = torch.tensor([[1, 1]]) + encoding.update({"input_ids": input_ids, "attention_mask": attention_mask}) + encoding.to(torch_device) + + with torch.no_grad(): + outputs = model(**encoding) + + expected_shape = torch.Size((1, 2)) + assert outputs.logits.shape == expected_shape + expected_slice = torch.tensor([[0.5061, 0.4988]]).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits, expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/umt5/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/umt5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/umt5/__init__.py @@ -0,0 +1 @@ + diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/umt5/test_modeling_umt5.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/umt5/test_modeling_umt5.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf9df9703fb78875932204f3db3bdd5f584d8c4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/umt5/test_modeling_umt5.py @@ -0,0 +1,604 @@ +# Copyright 2023 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 copy +import os +import pickle +import tempfile +import unittest + +from transformers import T5Config, is_torch_available +from transformers.models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES +from transformers.testing_utils import ( + require_sentencepiece, + require_tokenizers, + require_torch, + slow, + torch_device, +) +from transformers.utils import is_torch_fx_available + +from ...generation.test_utils import GenerationTesterMixin +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_fx_available(): + from transformers.utils.fx import symbolic_trace + + +if is_torch_available(): + import torch + + from transformers import ( + AutoTokenizer, + UMT5ForConditionalGeneration, + UMT5ForQuestionAnswering, + UMT5ForSequenceClassification, + UMT5Model, + ) + + +# Copied from test.models.t5.test_modeling_t5.T5ModelTester with T5->UMT5 +class UMT5ModelTester: + def __init__( + self, + parent, + vocab_size=99, + batch_size=13, + encoder_seq_length=7, + decoder_seq_length=7, + # For common tests + is_training=True, + use_attention_mask=True, + use_labels=False, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + d_ff=37, + relative_attention_num_buckets=8, + dropout_rate=0.1, + initializer_factor=0.002, + eos_token_id=1, + pad_token_id=0, + decoder_start_token_id=0, + scope=None, + decoder_layers=None, + ): + self.parent = parent + self.batch_size = batch_size + self.encoder_seq_length = encoder_seq_length + self.decoder_seq_length = decoder_seq_length + # For common tests + self.seq_length = self.decoder_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + 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.d_ff = d_ff + self.relative_attention_num_buckets = relative_attention_num_buckets + self.dropout_rate = dropout_rate + self.initializer_factor = initializer_factor + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.decoder_start_token_id = decoder_start_token_id + self.scope = None + self.decoder_layers = decoder_layers + + def get_large_model_config(self): + return T5Config.from_pretrained("google/umt5-base") + + def prepare_inputs_dict( + self, + config, + input_ids, + decoder_input_ids, + 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 = input_ids.ne(config.pad_token_id) + if decoder_attention_mask is None: + decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) + if head_mask is None: + head_mask = torch.ones(config.num_hidden_layers, config.num_attention_heads, device=torch_device) + if decoder_head_mask is None: + decoder_head_mask = torch.ones(config.num_decoder_layers, config.num_attention_heads, device=torch_device) + if cross_attn_head_mask is None: + cross_attn_head_mask = torch.ones( + config.num_decoder_layers, config.num_attention_heads, device=torch_device + ) + return { + "input_ids": input_ids, + "decoder_input_ids": decoder_input_ids, + "attention_mask": attention_mask, + "decoder_attention_mask": decoder_attention_mask, + "head_mask": head_mask, + "decoder_head_mask": decoder_head_mask, + "cross_attn_head_mask": cross_attn_head_mask, + } + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) + decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + + # we need to clamp the input ids here to avoid having pad token in between + # this is because for NllbMoe the position_ids are prepared such that + # all pad tokens have pos id = 2 and rest are between 2..seq_length + # and the seq_length here is seq_length - num_pad_tokens + # but when using past, there is no way of knowing if the past input ids had + # pad tokens in them, which results in incorrect seq_lenth and which in turn results in + # position_ids being off by num_pad_tokens in past input + input_ids = input_ids.clamp(self.pad_token_id + 2) + input_ids[:, -1] = self.eos_token_id # Eos Token + decoder_input_ids = decoder_input_ids.clamp(self.pad_token_id + 1) + + config = self.get_config() + config.encoder_attention_heads = config.num_attention_heads + input_dict = self.prepare_inputs_dict(config, input_ids, decoder_input_ids) + return config, input_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_pipeline_config(self): + return T5Config( + vocab_size=166, # t5 forces 100 extra tokens + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ) + + def get_config(self): + return T5Config( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + d_ff=self.d_ff, + d_kv=self.hidden_size // self.num_attention_heads, + num_layers=self.num_hidden_layers, + num_decoder_layers=self.decoder_layers, + num_heads=self.num_attention_heads, + relative_attention_num_buckets=self.relative_attention_num_buckets, + dropout_rate=self.dropout_rate, + initializer_factor=self.initializer_factor, + eos_token_id=self.eos_token_id, + bos_token_id=self.pad_token_id, + pad_token_id=self.pad_token_id, + decoder_start_token_id=self.decoder_start_token_id, + ) + + def create_and_check_model( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = UMT5Model(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + attention_mask=attention_mask, + decoder_attention_mask=decoder_attention_mask, + ) + result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) + decoder_output = result.last_hidden_state + decoder_past = result.past_key_values + encoder_output = result.encoder_last_hidden_state + + self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size)) + self.parent.assertEqual(decoder_output.size(), (self.batch_size, self.decoder_seq_length, self.hidden_size)) + # There should be `num_layers` key value embeddings stored in decoder_past + self.parent.assertEqual(len(decoder_past), config.num_layers) + # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple + self.parent.assertEqual(len(decoder_past[0]), 4) + + def create_and_check_decoder_model_past( + self, + config, + input_ids, + decoder_input_ids, + attention_mask, + decoder_attention_mask, + lm_labels, + ): + model = UMT5Model(config=config).get_decoder().to(torch_device).eval() + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_model_fp16_forward( + self, + config, + input_dict, + ): + model = UMT5Model(config=config).to(torch_device).half().eval() + output = model(**input_dict)["last_hidden_state"] + self.parent.assertFalse(torch.isnan(output).any().item()) + + def create_and_check_with_sequence_classification_head( + self, + config, + input_dict, + ): + labels = torch.tensor([1] * self.batch_size, dtype=torch.long, device=torch_device) + model = UMT5ForSequenceClassification(config=config).to(torch_device).eval() + outputs = model(**input_dict, labels=labels) + # self.parent.assertEqual(len(outputs), 4) + self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, config.num_labels)) + self.parent.assertEqual(outputs["loss"].size(), ()) + + +@require_torch +class UMT5ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (UMT5Model, UMT5ForConditionalGeneration, UMT5ForSequenceClassification, UMT5ForQuestionAnswering) + if is_torch_available() + else () + ) + all_generative_model_classes = (UMT5ForConditionalGeneration,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "conversational": UMT5ForConditionalGeneration, + "feature-extraction": UMT5Model, + "question-answering": UMT5ForQuestionAnswering, + "summarization": UMT5ForConditionalGeneration, + "text-classification": UMT5ForSequenceClassification, + "text2text-generation": UMT5ForConditionalGeneration, + "translation": UMT5ForConditionalGeneration, + "zero-shot": UMT5ForSequenceClassification, + } + if is_torch_available() + else {} + ) + is_encoder_decoder = True + fx_compatible = False + test_pruning = False + test_missing_keys = True + test_torchscript = True + # The small UMT5 model needs higher percentages for CPU/MP tests + model_split_percents = [0.8, 0.9] + + def setUp(self): + self.model_tester = UMT5ModelTester(self) + + # `QAPipelineTests` is not working well with slow tokenizers (for some models) and we don't want to touch the file + # `src/transformers/data/processors/squad.py` (where this test fails for this model) + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): + return True + + return False + + def _create_and_check_torch_fx_tracing(self, config, inputs_dict, output_loss=False): + if not is_torch_fx_available() or not self.fx_compatible: + return + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.return_dict = False + + for model_class in self.all_model_classes: + if model_class.__name__ == "UMT5ForSequenceClassification": + continue + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=output_loss) + + try: + if model.config.is_encoder_decoder: + model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward + labels = inputs.get("labels", None) + input_names = [ + "attention_mask", + "decoder_attention_mask", + "decoder_input_ids", + "input_features", + "input_ids", + "input_values", + ] + if labels is not None: + input_names.append("labels") + + filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names} + input_names = list(filtered_inputs.keys()) + + model_output = model(**filtered_inputs) + + traced_model = symbolic_trace(model, input_names) + traced_output = traced_model(**filtered_inputs) + else: + input_names = [ + "attention_mask", + "bbox", + "input_features", + "input_ids", + "input_values", + "pixel_values", + "token_type_ids", + "visual_feats", + "visual_pos", + ] + + labels = inputs.get("labels", None) + start_positions = inputs.get("start_positions", None) + end_positions = inputs.get("end_positions", None) + if labels is not None: + input_names.append("labels") + if start_positions is not None: + input_names.append("start_positions") + if end_positions is not None: + input_names.append("end_positions") + + filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names} + input_names = list(filtered_inputs.keys()) + + if model.__class__.__name__ in set(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values()) and ( + not hasattr(model.config, "problem_type") or model.config.problem_type is None + ): + model.config.problem_type = "single_label_classification" + + traced_model = symbolic_trace(model, input_names) + traced_output = traced_model(**filtered_inputs) + model_output = model(**filtered_inputs) + + except Exception as e: + self.fail(f"Couldn't trace module: {e}") + + def flatten_output(output): + flatten = [] + for x in output: + if isinstance(x, (tuple, list)): + flatten += flatten_output(x) + elif not isinstance(x, torch.Tensor): + continue + else: + flatten.append(x) + return flatten + + model_output = flatten_output(model_output) + traced_output = flatten_output(traced_output) + num_outputs = len(model_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], traced_output[i]), + f"traced {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Test that the model can be serialized and restored properly + with tempfile.TemporaryDirectory() as tmp_dir_name: + pkl_file_name = os.path.join(tmp_dir_name, "model.pkl") + try: + with open(pkl_file_name, "wb") as f: + pickle.dump(traced_model, f) + with open(pkl_file_name, "rb") as f: + loaded = pickle.load(f) + except Exception as e: + self.fail(f"Couldn't serialize / deserialize the traced model: {e}") + + loaded_output = loaded(**filtered_inputs) + loaded_output = flatten_output(loaded_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], loaded_output[i]), + f"serialized model {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Avoid memory leak. Without this, each call increase RAM usage by ~20MB. + # (Even with this call, there are still memory leak by ~0.04MB) + self.clear_torch_jit_class_registry() + + # UMT5ForSequenceClassification does not support inputs_embeds + def test_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in (UMT5Model, UMT5ForConditionalGeneration, UMT5ForQuestionAnswering): + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + del inputs["input_ids"] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + + wte = model.get_input_embeddings() + if not self.is_encoder_decoder: + inputs["inputs_embeds"] = wte(input_ids) + else: + inputs["inputs_embeds"] = wte(encoder_input_ids) + inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) + + with torch.no_grad(): + model(**inputs)[0] + + def test_with_sequence_classification_head(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_with_sequence_classification_head(*config_and_inputs) + + @unittest.skip("Test has a segmentation fault on torch 1.8.0") + def test_export_to_onnx(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + model = UMT5Model(config_and_inputs[0]).to(torch_device) + with tempfile.TemporaryDirectory() as tmpdirname: + torch.onnx.export( + model, + (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]), + f"{tmpdirname}/t5_test.onnx", + export_params=True, + opset_version=9, + input_names=["input_ids", "decoder_input_ids"], + ) + + @unittest.skipIf(torch_device == "cpu", "Cant do half precision") + def test_model_fp16_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs) + + def test_generate_with_head_masking(self): + attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"] + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config = config_and_inputs[0] + model = UMT5ForConditionalGeneration(config).eval() + model.to(torch_device) + + head_masking = { + "head_mask": torch.zeros(config.num_layers, config.num_heads, device=torch_device), + "decoder_head_mask": torch.zeros(config.num_decoder_layers, config.num_heads, device=torch_device), + "cross_attn_head_mask": torch.zeros(config.num_decoder_layers, config.num_heads, device=torch_device), + } + + for attn_name, (name, mask) in zip(attention_names, head_masking.items()): + head_masks = {name: mask} + # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified + if name == "head_mask": + head_masks["decoder_head_mask"] = torch.ones( + config.num_decoder_layers, config.num_heads, device=torch_device + ) + + out = model.generate( + config_and_inputs[1]["input_ids"], + num_beams=1, + max_length=3, + output_attentions=True, + return_dict_in_generate=True, + **head_masks, + ) + # We check the state of decoder_attentions and cross_attentions just from the last step + attn_weights = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] + self.assertEqual(sum([w.sum().item() for w in attn_weights]), 0.0) + + @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.") + def test_disk_offload(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + +@require_torch +@require_sentencepiece +@require_tokenizers +class Umt5IntegrationTest(unittest.TestCase): + @slow + @unittest.skip( + "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" + ) + def test_small_integration_test(self): + """ + For comparison run the kaggle notbook available here : https://www.kaggle.com/arthurzucker/umt5-inference + """ + + model = UMT5ForConditionalGeneration.from_pretrained("google/umt5-small", return_dict=True).to(torch_device) + tokenizer = AutoTokenizer.from_pretrained("google/umt5-small", use_fast=False, legacy=False) + input_text = [ + "Bonjour monsieur bien .", + "No se como puedo .", + "This is the reason why we them.", + "The walks in , seats", + "A walks into a bar and orders a with pinch of .", + ] + input_ids = tokenizer(input_text, return_tensors="pt", padding=True).input_ids + # fmt: off + EXPECTED_IDS = torch.tensor( + [ + [ 38530, 210703, 256299, 1410, 256298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], + [ 826, 321, 671, 25922, 256299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], + [ 1460, 339, 312, 19014, 10620, 758, 256299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], + [ 517, 256299, 14869, 281, 301, 256298, 275, 119983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], + [ 320, 256299, 14869, 281, 2234, 289, 2275, 333,61391, 289, 256298, 543, 256297, 168714, 329, 256296,274, 1], + ] + ) + # fmt: on + torch.testing.assert_allclose(input_ids, EXPECTED_IDS) + + generated_ids = model.generate(input_ids.to(torch_device)) + EXPECTED_FILLING = [ + " et [eod] .. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 ajšietostolleuxajšie", + "..,<0x0A>...spech <0x0A> ", + " are not going to be a part of the world. We are not going to be a part of and<0x0A>.", + " door, the door 피해[/", + "nyone who drink a alcohol A A. This I", + ] + filling = tokenizer.batch_decode(generated_ids) + self.assertEqual(filling, EXPECTED_FILLING) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech/test_modeling_unispeech.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech/test_modeling_unispeech.py new file mode 100644 index 0000000000000000000000000000000000000000..a286274828e26767db6a45a30fa4aa976ab03875 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech/test_modeling_unispeech.py @@ -0,0 +1,593 @@ +# coding=utf-8 +# 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 UniSpeech model. """ + +import math +import unittest + +import numpy as np +import pytest +from datasets import load_dataset + +from transformers import UniSpeechConfig, is_torch_available +from transformers.testing_utils import require_soundfile, require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + UniSpeechForCTC, + UniSpeechForPreTraining, + UniSpeechForSequenceClassification, + UniSpeechModel, + Wav2Vec2FeatureExtractor, + Wav2Vec2Processor, + ) + + +class UniSpeechModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=1024, # speech is longer + is_training=False, + hidden_size=16, + feat_extract_norm="group", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout_prob=0.1, # this is most likely not correctly set yet + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + vocab_size=32, + do_stable_layer_norm=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout_prob = hidden_dropout_prob + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.scope = scope + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + + return config, input_values, attention_mask + + def get_config(self): + return UniSpeechConfig( + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout_prob=self.hidden_dropout_prob, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + ) + + def create_and_check_model(self, config, input_values, attention_mask): + model = UniSpeechModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_batch_inference(self, config, input_values, *args): + # test does not pass for models making use of `group_norm` + # check: https://github.com/pytorch/fairseq/issues/3227 + model = UniSpeechModel(config=config) + model.to(torch_device) + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0.0 + + batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state + + for i in range(input_values.shape[0]): + input_slice = input_values[i : i + 1, : input_lengths[i]] + output = model(input_slice).last_hidden_state + + batch_output = batch_outputs[i : i + 1, : output.shape[1]] + self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) + + def check_ctc_loss(self, config, input_values, *args): + model = UniSpeechForCTC(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + model.config.ctc_loss_reduction = "sum" + sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + model.config.ctc_loss_reduction = "mean" + mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(sum_loss, float)) + self.parent.assertTrue(isinstance(mean_loss, float)) + + def check_seq_classifier_loss(self, config, input_values, *args): + model = UniSpeechForSequenceClassification(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + unmasked_loss = model(input_values, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(masked_loss, float)) + self.parent.assertTrue(isinstance(unmasked_loss, float)) + self.parent.assertTrue(masked_loss != unmasked_loss) + + def check_ctc_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = UniSpeechForCTC(config=config) + model.to(torch_device) + model.train() + + # freeze feature encoder + model.freeze_feature_encoder() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + if max_length_labels[i] < labels.shape[-1]: + # it's important that we make sure that target lengths are at least + # one shorter than logit lengths to prevent -inf + labels[i, max_length_labels[i] - 1 :] = -100 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_seq_classifier_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = UniSpeechForSequenceClassification(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_labels_out_of_vocab(self, config, input_values, *args): + model = UniSpeechForCTC(config) + model.to(torch_device) + model.train() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) + + with pytest.raises(ValueError): + model(input_values, labels=labels) + + def prepare_config_and_inputs_for_common(self): + config, input_values, attention_mask = self.prepare_config_and_inputs() + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class UniSpeechRobustModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (UniSpeechForCTC, UniSpeechModel, UniSpeechForSequenceClassification, UniSpeechForPreTraining) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + { + "audio-classification": UniSpeechForSequenceClassification, + "automatic-speech-recognition": UniSpeechForCTC, + "feature-extraction": UniSpeechModel, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_headmasking = False + + def setUp(self): + self.model_tester = UniSpeechModelTester( + self, conv_stride=(3, 3, 3), feat_extract_norm="layer", do_stable_layer_norm=True + ) + self.config_tester = ConfigTester(self, config_class=UniSpeechConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_batched_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_batch_inference(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_seq_classifier_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_seq_classifier_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # UniSpeech has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # UniSpeech cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # UniSpeech has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "codevectors") and module.codevectors is not None: + module.codevectors.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + def test_mask_feature_prob_ctc(self): + model = UniSpeechForCTC.from_pretrained( + "hf-internal-testing/tiny-random-unispeech", mask_feature_prob=0.2, mask_feature_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-unispeech", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_prob_ctc(self): + model = UniSpeechForCTC.from_pretrained( + "hf-internal-testing/tiny-random-unispeech", mask_time_prob=0.2, mask_time_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-unispeech", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_feature_prob_ctc_single_batch(self): + model = UniSpeechForCTC.from_pretrained( + "hf-internal-testing/tiny-random-unispeech", + mask_time_prob=0.2, + mask_feature_prob=0.2, + mask_time_length=2, + mask_feature_length=2, + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-unispeech", return_attention_mask=True + ) + + batch_duration_in_seconds = [6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (1, 1498, 32)) + + @unittest.skip(reason="Feed forward chunking is not implemented") + def test_feed_forward_chunking(self): + pass + + @slow + def test_model_from_pretrained(self): + model = UniSpeechModel.from_pretrained("microsoft/unispeech-large-1500h-cv") + self.assertIsNotNone(model) + + +@require_torch +@require_soundfile +@slow +class UniSpeechModelIntegrationTest(unittest.TestCase): + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter( + lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] + )[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def _load_superb(self, task, num_samples): + ds = load_dataset("anton-l/superb_dummy", task, split="test") + + return ds[:num_samples] + + def test_inference_pretraining(self): + model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv") + model.to(torch_device) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/wav2vec2-large-xlsr-53") + input_speech = self._load_datasamples(2) + + inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) + + with torch.no_grad(): + torch.manual_seed(0) + outputs = model( + inputs_dict.input_values.to(torch_device), + attention_mask=inputs_dict.attention_mask.to(torch_device), + ) + + # compute cosine similarity + cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1) + + # pretrained model should have learned a high cosine similarity + self.assertTrue(cosine_sim.mean() > 0.5) + + # fmt: off + expected_cosine_sim_slice = torch.tensor( + [[0.8290, 0.8335, 0.8815, 0.8580, 0.8249], + [0.8892, 0.9221, 0.8711, 0.8601, 0.8482]], + device=torch_device, + ) + # fmt: on + + self.assertTrue(torch.allclose(cosine_sim[:, :5], expected_cosine_sim_slice, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech_sat/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech_sat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech_sat/test_modeling_unispeech_sat.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech_sat/test_modeling_unispeech_sat.py new file mode 100644 index 0000000000000000000000000000000000000000..79fa54717378bbfa5fd8abd1fababadf713b8216 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/unispeech_sat/test_modeling_unispeech_sat.py @@ -0,0 +1,935 @@ +# coding=utf-8 +# 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 UniSpeechSat model. """ + +import math +import unittest + +import numpy as np +import pytest +from datasets import load_dataset + +from transformers import UniSpeechSatConfig, is_torch_available +from transformers.testing_utils import require_soundfile, require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + UniSpeechSatForAudioFrameClassification, + UniSpeechSatForCTC, + UniSpeechSatForPreTraining, + UniSpeechSatForSequenceClassification, + UniSpeechSatForXVector, + UniSpeechSatModel, + Wav2Vec2FeatureExtractor, + Wav2Vec2Processor, + ) + + +class UniSpeechSatModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=1024, # speech is longer + is_training=False, + hidden_size=16, + feat_extract_norm="group", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout_prob=0.1, # this is most likely not correctly set yet + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + mask_time_prob=0.5, + mask_time_length=2, + vocab_size=32, + do_stable_layer_norm=False, + tdnn_dim=(32, 32), + tdnn_kernel=(3, 3), + tdnn_dilation=(1, 1), + xvector_output_dim=32, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout_prob = hidden_dropout_prob + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.mask_time_prob = mask_time_prob + self.mask_time_length = mask_time_length + self.tdnn_dim = tdnn_dim + self.tdnn_kernel = tdnn_kernel + self.tdnn_dilation = tdnn_dilation + self.xvector_output_dim = xvector_output_dim + self.scope = scope + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + + return config, input_values, attention_mask + + def get_config(self): + return UniSpeechSatConfig( + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + mask_time_prob=self.mask_time_prob, + mask_time_length=self.mask_time_length, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout_prob=self.hidden_dropout_prob, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + tdnn_dim=self.tdnn_dim, + tdnn_kernel=self.tdnn_kernel, + tdnn_dilation=self.tdnn_dilation, + xvector_output_dim=self.xvector_output_dim, + ) + + def create_and_check_model(self, config, input_values, attention_mask): + model = UniSpeechSatModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_batch_inference(self, config, input_values, *args): + # test does not pass for models making use of `group_norm` + # check: https://github.com/pytorch/fairseq/issues/3227 + model = UniSpeechSatModel(config=config) + model.to(torch_device) + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0.0 + + batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state + + for i in range(input_values.shape[0]): + input_slice = input_values[i : i + 1, : input_lengths[i]] + output = model(input_slice).last_hidden_state + + batch_output = batch_outputs[i : i + 1, : output.shape[1]] + self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) + + def check_ctc_loss(self, config, input_values, *args): + model = UniSpeechSatForCTC(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + model.config.ctc_loss_reduction = "sum" + sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + model.config.ctc_loss_reduction = "mean" + mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(sum_loss, float)) + self.parent.assertTrue(isinstance(mean_loss, float)) + + def check_seq_classifier_loss(self, config, input_values, *args): + model = UniSpeechSatForSequenceClassification(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + unmasked_loss = model(input_values, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(masked_loss, float)) + self.parent.assertTrue(isinstance(unmasked_loss, float)) + self.parent.assertTrue(masked_loss != unmasked_loss) + + def check_ctc_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = UniSpeechSatForCTC(config=config) + model.to(torch_device) + model.train() + + # freeze feature encoder + model.freeze_feature_encoder() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + if max_length_labels[i] < labels.shape[-1]: + # it's important that we make sure that target lengths are at least + # one shorter than logit lengths to prevent -inf + labels[i, max_length_labels[i] - 1 :] = -100 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_seq_classifier_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = UniSpeechSatForSequenceClassification(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_xvector_training(self, config, *args): + config.ctc_zero_infinity = True + model = UniSpeechSatForXVector(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + # use a longer sequence length to account for TDNN temporal downsampling + input_values = floats_tensor([self.batch_size, self.seq_length * 2], scale=1.0) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_labels_out_of_vocab(self, config, input_values, *args): + model = UniSpeechSatForCTC(config) + model.to(torch_device) + model.train() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) + + with pytest.raises(ValueError): + model(input_values, labels=labels) + + def prepare_config_and_inputs_for_common(self): + config, input_values, attention_mask = self.prepare_config_and_inputs() + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class UniSpeechSatModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + UniSpeechSatForCTC, + UniSpeechSatForPreTraining, + UniSpeechSatModel, + UniSpeechSatForSequenceClassification, + UniSpeechSatForAudioFrameClassification, + UniSpeechSatForXVector, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + { + "audio-classification": UniSpeechSatForSequenceClassification, + "automatic-speech-recognition": UniSpeechSatForCTC, + "feature-extraction": UniSpeechSatModel, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_headmasking = False + test_torchscript = False + + def setUp(self): + self.model_tester = UniSpeechSatModelTester(self) + self.config_tester = ConfigTester(self, config_class=UniSpeechSatConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_seq_classifier_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_seq_classifier_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_training(*config_and_inputs) + + def test_xvector_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_xvector_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # UniSpeechSat has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # UniSpeechSat cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # UniSpeechSat has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "label_embeddings_concat", + "objective.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "codevectors") and module.codevectors is not None: + module.codevectors.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + def test_mask_feature_prob_ctc(self): + model = UniSpeechSatForCTC.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", mask_feature_prob=0.2, mask_feature_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_prob_ctc(self): + model = UniSpeechSatForCTC.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", mask_time_prob=0.2, mask_time_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + @unittest.skip(reason="Feed forward chunking is not implemented") + def test_feed_forward_chunking(self): + pass + + @slow + def test_model_from_pretrained(self): + model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-base-plus") + self.assertIsNotNone(model) + + +@require_torch +class UniSpeechSatRobustModelTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = ( + (UniSpeechSatForCTC, UniSpeechSatForPreTraining, UniSpeechSatModel, UniSpeechSatForSequenceClassification) + if is_torch_available() + else () + ) + test_pruning = False + test_headmasking = False + test_torchscript = False + + def setUp(self): + self.model_tester = UniSpeechSatModelTester( + self, conv_stride=(3, 3, 3), feat_extract_norm="layer", do_stable_layer_norm=True + ) + self.config_tester = ConfigTester(self, config_class=UniSpeechSatConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_batched_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_batch_inference(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_seq_classifier_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_seq_classifier_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # UniSpeechSat has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # UniSpeechSat cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # UniSpeechSat has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "label_embeddings_concat", + "objective.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "codevectors") and module.codevectors is not None: + module.codevectors.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + def test_mask_feature_prob_ctc(self): + model = UniSpeechSatForCTC.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", mask_feature_prob=0.2, mask_feature_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_prob_ctc(self): + model = UniSpeechSatForCTC.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", mask_time_prob=0.2, mask_time_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_feature_prob_ctc_single_batch(self): + model = UniSpeechSatForCTC.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", + mask_time_prob=0.2, + mask_feature_prob=0.2, + mask_time_length=2, + mask_feature_length=2, + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True + ) + + batch_duration_in_seconds = [6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (1, 1498, 32)) + + @unittest.skip(reason="Feed forward chunking is not implemented") + def test_feed_forward_chunking(self): + pass + + @slow + def test_model_from_pretrained(self): + model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-large") + self.assertIsNotNone(model) + + +@require_torch +@require_soundfile +@slow +class UniSpeechSatModelIntegrationTest(unittest.TestCase): + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter( + lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] + )[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def _load_superb(self, task, num_samples): + ds = load_dataset("anton-l/superb_dummy", task, split="test") + + return ds[:num_samples] + + def test_inference_encoder_base(self): + model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-base-plus") + model.to(torch_device) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( + "facebook/wav2vec2-base", return_attention_mask=True + ) + input_speech = self._load_datasamples(2) + + inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) + + with torch.no_grad(): + outputs = model( + inputs_dict.input_values.to(torch_device), + attention_mask=inputs_dict.attention_mask.to(torch_device), + ) + + # fmt: off + expected_hidden_states_slice = torch.tensor( + [[[-0.0743, 0.1384], + [-0.0845, 0.1704]], + [[-0.0954, 0.1936], + [-0.1123, 0.2095]]], + device=torch_device, + ) + # fmt: on + + self.assertTrue(torch.allclose(outputs.last_hidden_state[:, :2, -2:], expected_hidden_states_slice, atol=1e-3)) + + def test_inference_encoder_large(self): + model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-large") + model.to(torch_device) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/wav2vec2-large-xlsr-53") + input_speech = self._load_datasamples(2) + + inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) + + with torch.no_grad(): + outputs = model( + inputs_dict.input_values.to(torch_device), + attention_mask=inputs_dict.attention_mask.to(torch_device), + ) + + # fmt: off + expected_hidden_states_slice = torch.tensor( + [[[-0.1172, -0.0797], + [-0.0012, 0.0213]], + [[-0.1225, -0.1277], + [-0.0668, -0.0585]]], + device=torch_device, + ) + # fmt: on + + self.assertTrue(torch.allclose(outputs.last_hidden_state[:, :2, -2:], expected_hidden_states_slice, atol=1e-3)) + + def test_inference_diarization(self): + model = UniSpeechSatForAudioFrameClassification.from_pretrained("microsoft/unispeech-sat-base-plus-sd").to( + torch_device + ) + processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/unispeech-sat-base-plus-sd") + input_data = self._load_superb("sd", 4) + inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + with torch.no_grad(): + outputs = model(input_values, attention_mask=attention_mask) + # labels is a one-hot array of shape (num_frames, num_speakers) + labels = (outputs.logits > 0).long() + + # s3prl logits for the same batch + expected_logits = torch.tensor( + [ + [[-5.6119, -5.5845], [-3.7772, -5.4824], [-3.6914, -5.1619], [-4.7560, -5.0496]], + [[-6.3785, -4.8365], [-5.5863, -5.4149], [-5.5639, -4.8469], [-6.1511, -4.0052]], + [[-6.0355, -3.7414], [-5.5968, -4.8061], [-5.4620, -4.7310], [-5.5864, -4.6078]], + [[-5.9493, -4.8963], [-4.4050, -5.4476], [-4.1755, -5.1395], [-4.0272, -4.3705]], + ], + device=torch_device, + ) + self.assertEqual(labels[0, :, 0].sum(), 270) + self.assertEqual(labels[0, :, 1].sum(), 647) + # TODO: update the tolerance after the CI moves to torch 1.10 + self.assertTrue(torch.allclose(outputs.logits[:, :4], expected_logits, atol=1e-2)) + + def test_inference_speaker_verification(self): + model = UniSpeechSatForXVector.from_pretrained("microsoft/unispeech-sat-base-plus-sv").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/unispeech-sat-base-plus-sv") + input_data = self._load_superb("si", 4) + + inputs = processor(input_data["speech"], return_tensors="pt", padding=True) + labels = torch.tensor([5, 1, 1, 3], device=torch_device).T + + with torch.no_grad(): + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + outputs = model(input_values, attention_mask=attention_mask, labels=labels) + embeddings = torch.nn.functional.normalize(outputs.embeddings, dim=-1) + + cosine_sim = torch.nn.CosineSimilarity(dim=-1) + # id10002 vs id10002 + self.assertAlmostEqual(cosine_sim(embeddings[1], embeddings[2]).item(), 0.9671, 3) + # id10006 vs id10002 + self.assertAlmostEqual(cosine_sim(embeddings[0], embeddings[1]).item(), 0.4941, 3) + # id10002 vs id10004 + self.assertAlmostEqual(cosine_sim(embeddings[2], embeddings[3]).item(), 0.5616, 3) + + # TODO: update the tolerance after the CI moves to torch 1.10 + self.assertAlmostEqual(outputs.loss.item(), 18.5925, 2) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/univnet/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/univnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/univnet/test_feature_extraction_univnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/univnet/test_feature_extraction_univnet.py new file mode 100644 index 0000000000000000000000000000000000000000..dfa335d15383eecb56cced6861504a41b663f232 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/univnet/test_feature_extraction_univnet.py @@ -0,0 +1,365 @@ +# Copyright 2023 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 itertools +import os +import random +import tempfile +import unittest + +import numpy as np +from datasets import Audio, load_dataset + +from transformers import UnivNetFeatureExtractor +from transformers.testing_utils import check_json_file_has_correct_format, require_torch, slow +from transformers.utils.import_utils import is_torch_available + +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +if is_torch_available(): + import torch + + +global_rng = random.Random() + + +# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +class UnivNetFeatureExtractionTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + min_seq_length=400, + max_seq_length=2000, + feature_size=1, + sampling_rate=24000, + padding_value=0.0, + do_normalize=True, + num_mel_bins=100, + hop_length=256, + win_length=1024, + win_function="hann_window", + filter_length=1024, + max_length_s=10, + fmin=0.0, + fmax=12000, + mel_floor=1e-9, + center=False, + compression_factor=1.0, + compression_clip_val=1e-5, + normalize_min=-11.512925148010254, + normalize_max=2.3143386840820312, + model_in_channels=64, + pad_end_length=10, + ): + self.parent = parent + self.batch_size = batch_size + self.min_seq_length = min_seq_length + self.max_seq_length = max_seq_length + self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) + + self.feature_size = feature_size + self.sampling_rate = sampling_rate + self.padding_value = padding_value + self.do_normalize = do_normalize + self.num_mel_bins = num_mel_bins + self.hop_length = hop_length + self.win_length = win_length + self.win_function = win_function + self.filter_length = filter_length + self.max_length_s = max_length_s + self.fmin = fmin + self.fmax = fmax + self.mel_floor = mel_floor + self.center = center + self.compression_factor = compression_factor + self.compression_clip_val = compression_clip_val + self.normalize_min = normalize_min + self.normalize_max = normalize_max + self.model_in_channels = model_in_channels + self.pad_end_length = pad_end_length + + def prepare_feat_extract_dict(self): + return { + "feature_size": self.feature_size, + "sampling_rate": self.sampling_rate, + "padding_value": self.padding_value, + "do_normalize": self.do_normalize, + "num_mel_bins": self.num_mel_bins, + "hop_length": self.hop_length, + "win_length": self.win_length, + "win_function": self.win_function, + "filter_length": self.filter_length, + "max_length_s": self.max_length_s, + "fmin": self.fmin, + "fmax": self.fmax, + "mel_floor": self.mel_floor, + "center": self.center, + "compression_factor": self.compression_factor, + "compression_clip_val": self.compression_clip_val, + "normalize_min": self.normalize_min, + "normalize_max": self.normalize_max, + "model_in_channels": self.model_in_channels, + "pad_end_length": self.pad_end_length, + } + + def prepare_inputs_for_common(self, equal_length=False, numpify=False): + def _flatten(list_of_lists): + return list(itertools.chain(*list_of_lists)) + + if equal_length: + speech_inputs = floats_list((self.batch_size, self.max_seq_length)) + else: + # make sure that inputs increase in size + speech_inputs = [ + _flatten(floats_list((x, self.feature_size))) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + + return speech_inputs + + +class UnivNetFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = UnivNetFeatureExtractor + + def setUp(self): + self.feat_extract_tester = UnivNetFeatureExtractionTester(self) + + # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest.test_feat_extract_from_and_save_pretrained + def test_feat_extract_from_and_save_pretrained(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = feat_extract_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + mel_1 = feat_extract_first.mel_filters + mel_2 = feat_extract_second.mel_filters + self.assertTrue(np.allclose(mel_1, mel_2)) + self.assertEqual(dict_first, dict_second) + + # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest.test_feat_extract_to_json_file + def test_feat_extract_to_json_file(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "feat_extract.json") + feat_extract_first.to_json_file(json_file_path) + feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + mel_1 = feat_extract_first.mel_filters + mel_2 = feat_extract_second.mel_filters + self.assertTrue(np.allclose(mel_1, mel_2)) + self.assertEqual(dict_first, dict_second) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test feature size + input_features = feature_extractor( + np_speech_inputs, padding="max_length", max_length=1600, return_tensors="np" + ).input_features + self.assertTrue(input_features.ndim == 3) + # Note: for some reason I get a weird padding error when feature_size > 1 + # self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size) + # Note: we use the shape convention (batch_size, seq_len, num_mel_bins) + self.assertTrue(input_features.shape[-1] == feature_extractor.num_mel_bins) + + # Test not batched input + encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_features + self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) + + # Test batched + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test 2-D numpy arrays are batched. + speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] + np_speech_inputs = np.asarray(speech_inputs) + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test truncation required + speech_inputs = [ + floats_list((1, x))[0] + for x in range((feature_extractor.num_max_samples - 100), (feature_extractor.num_max_samples + 500), 200) + ] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + speech_inputs_truncated = [x[: feature_extractor.num_max_samples] for x in speech_inputs] + np_speech_inputs_truncated = [np.asarray(speech_input) for speech_input in speech_inputs_truncated] + + encoded_sequences_1 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs_truncated, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + def test_batched_unbatched_consistency(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = floats_list((1, 800))[0] + np_speech_inputs = np.asarray(speech_inputs) + + # Test unbatched vs batched list + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor([speech_inputs], return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test np.ndarray vs List[np.ndarray] + encoded_sequences_1 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor([np_speech_inputs], return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test unbatched np.ndarray vs batched np.ndarray + encoded_sequences_1 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor( + np.expand_dims(np_speech_inputs, axis=0), return_tensors="np" + ).input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + def test_generate_noise(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + features = feature_extractor(speech_inputs, return_noise=True) + input_features = features.input_features + noise_features = features.noise_sequence + + for spectrogram, noise in zip(input_features, noise_features): + self.assertEqual(spectrogram.shape[0], noise.shape[0]) + + def test_pad_end(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + input_features1 = feature_extractor(speech_inputs, padding=False, pad_end=False).input_features + input_features2 = feature_extractor(speech_inputs, padding=False, pad_end=True).input_features + + for spectrogram1, spectrogram2 in zip(input_features1, input_features2): + self.assertEqual(spectrogram1.shape[0] + self.feat_extract_tester.pad_end_length, spectrogram2.shape[0]) + + def test_generate_noise_and_pad_end(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + features = feature_extractor(speech_inputs, padding=False, return_noise=True, pad_end=True) + input_features = features.input_features + noise_features = features.noise_sequence + + for spectrogram, noise in zip(input_features, noise_features): + self.assertEqual(spectrogram.shape[0], noise.shape[0]) + + @require_torch + def test_batch_decode(self): + import torch + + feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) + input_lengths = list(range(800, 1400, 200)) + pad_samples = feature_extractor.pad_end_length * feature_extractor.hop_length + output_features = { + "waveforms": torch.tensor(floats_list((3, max(input_lengths) + pad_samples))), + "waveform_lengths": torch.tensor(input_lengths), + } + waveforms = feature_extractor.batch_decode(**output_features) + + for input_length, waveform in zip(input_lengths, waveforms): + self.assertTrue(len(waveform.shape) == 1, msg="Individual output waveforms should be 1D") + self.assertEqual(waveform.shape[0], input_length) + + @require_torch + # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest.test_double_precision_pad + def test_double_precision_pad(self): + import torch + + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + np_speech_inputs = np.random.rand(100, 32).astype(np.float64) + py_speech_inputs = np_speech_inputs.tolist() + + for inputs in [py_speech_inputs, np_speech_inputs]: + np_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="np") + self.assertTrue(np_processed.input_features.dtype == np.float32) + pt_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="pt") + self.assertTrue(pt_processed.input_features.dtype == torch.float32) + + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + ds = ds.cast_column("audio", Audio(sampling_rate=self.feat_extract_tester.sampling_rate)) + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples], [x["sampling_rate"] for x in speech_samples] + + @slow + @require_torch + def test_integration(self): + # fmt: off + EXPECTED_INPUT_FEATURES = torch.tensor( + [ + -5.0229, -6.1358, -5.8346, -5.4447, -5.6707, -5.8577, -5.0464, -5.0058, + -5.6015, -5.6410, -5.4325, -5.6116, -5.3700, -5.7956, -5.3196, -5.3274, + -5.9655, -5.6057, -5.8382, -5.9602, -5.9005, -5.9123, -5.7669, -6.1441, + -5.5168, -5.1405, -5.3927, -6.0032, -5.5784, -5.3728 + ], + ) + # fmt: on + + input_speech, sr = self._load_datasamples(1) + + feature_extractor = UnivNetFeatureExtractor() + input_features = feature_extractor(input_speech, sampling_rate=sr[0], return_tensors="pt").input_features + self.assertEqual(input_features.shape, (1, 548, 100)) + + input_features_mean = torch.mean(input_features) + input_features_stddev = torch.std(input_features) + + EXPECTED_MEAN = torch.tensor(-6.18862009) + EXPECTED_STDDEV = torch.tensor(2.80845642) + + torch.testing.assert_close(input_features_mean, EXPECTED_MEAN, atol=5e-5, rtol=5e-6) + torch.testing.assert_close(input_features_stddev, EXPECTED_STDDEV) + torch.testing.assert_close(input_features[0, :30, 0], EXPECTED_INPUT_FEATURES, atol=1e-4, rtol=1e-5) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/univnet/test_modeling_univnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/univnet/test_modeling_univnet.py new file mode 100644 index 0000000000000000000000000000000000000000..b1512af284ef015a8b38a07148d1fbd2c697c768 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/univnet/test_modeling_univnet.py @@ -0,0 +1,369 @@ +# Copyright 2023 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 gc +import inspect +import random +import unittest + +from datasets import Audio, load_dataset + +from transformers import UnivNetConfig, UnivNetFeatureExtractor +from transformers.testing_utils import ( + is_torch_available, + require_torch, + require_torch_gpu, + slow, + torch_device, +) + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + floats_tensor, +) + + +if is_torch_available(): + import torch + + from transformers import UnivNetModel + + +class UnivNetModelTester: + def __init__( + self, + parent, + batch_size=2, + seq_length=7, + in_channels=8, + hidden_channels=8, + num_mel_bins=20, + kernel_predictor_hidden_channels=8, + seed=0, + is_training=False, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.in_channels = in_channels + self.hidden_channels = hidden_channels + self.num_mel_bins = num_mel_bins + self.kernel_predictor_hidden_channels = kernel_predictor_hidden_channels + self.seed = seed + self.is_training = is_training + + def prepare_noise_sequence(self): + generator = torch.manual_seed(self.seed) + noise_shape = (self.seq_length, self.in_channels) + # Create noise on CPU for reproducibility + noise_sequence = torch.randn(noise_shape, generator=generator, dtype=torch.float) + return noise_sequence + + def prepare_config_and_inputs(self): + spectrogram = floats_tensor([self.seq_length, self.num_mel_bins], scale=1.0) + noise_sequence = self.prepare_noise_sequence() + noise_sequence = noise_sequence.to(spectrogram.device) + config = self.get_config() + return config, spectrogram, noise_sequence + + def get_config(self): + return UnivNetConfig( + model_in_channels=self.in_channels, + model_hidden_channels=self.hidden_channels, + num_mel_bins=self.num_mel_bins, + kernel_predictor_hidden_channels=self.kernel_predictor_hidden_channels, + ) + + def create_and_check_model(self, config, spectrogram, noise_sequence): + model = UnivNetModel(config=config).to(torch_device).eval() + result = model(spectrogram, noise_sequence)[0] + self.parent.assertEqual(result.shape, (1, self.seq_length * 256)) + + def prepare_config_and_inputs_for_common(self): + config, spectrogram, noise_sequence = self.prepare_config_and_inputs() + inputs_dict = {"input_features": spectrogram, "noise_sequence": noise_sequence} + return config, inputs_dict + + +@require_torch +class UnivNetModelTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (UnivNetModel,) if is_torch_available() else () + # UnivNetModel currently cannot be traced with torch.jit.trace. + test_torchscript = False + # The UnivNetModel is not a transformer and does not use any attention mechanisms, so skip transformer/attention + # related tests. + test_pruning = False + test_resize_embeddings = False + test_resize_position_embeddings = False + test_head_masking = False + # UnivNetModel is not a sequence classification model. + test_mismatched_shapes = False + # UnivNetModel does not have a base_model_prefix attribute. + test_missing_keys = False + # UnivNetModel does not implement a parallelize method. + test_model_parallel = False + is_encoder_decoder = False + has_attentions = False + + input_name = "input_features" + + def setUp(self): + self.model_tester = UnivNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=UnivNetConfig) + + @unittest.skip(reason="fix this once it gets more usage") + def test_multi_gpu_data_parallel_forward(self): + super().test_multi_gpu_data_parallel_forward() + + def test_config(self): + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_from_and_save_pretrained_subfolder() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_features", + ] + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + @unittest.skip(reason="UnivNetModel does not output hidden_states.") + def test_hidden_states_output(self): + pass + + @unittest.skip(reason="UnivNetModel.forward does not accept an inputs_embeds argument.") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="UnivNetModel does not use input embeddings and thus has no get_input_embeddings method.") + def test_model_common_attributes(self): + pass + + @unittest.skip(reason="UnivNetModel does not support all arguments tested, such as output_hidden_states.") + def test_model_outputs_equivalence(self): + pass + + @unittest.skip(reason="UnivNetModel does not output hidden_states.") + def test_retain_grad_hidden_states_attentions(self): + pass + + def test_batched_inputs_outputs(self): + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + batched_spectrogram = inputs["input_features"].unsqueeze(0).repeat(2, 1, 1) + batched_noise_sequence = inputs["noise_sequence"].unsqueeze(0).repeat(2, 1, 1) + with torch.no_grad(): + batched_outputs = model( + batched_spectrogram.to(torch_device), + batched_noise_sequence.to(torch_device), + )[0] + + self.assertEqual( + batched_spectrogram.shape[0], + batched_outputs.shape[0], + msg="Got different batch dims for input and output", + ) + + def test_unbatched_inputs_outputs(self): + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(inputs["input_features"].to(torch_device), inputs["noise_sequence"].to(torch_device))[ + 0 + ] + self.assertTrue(outputs.shape[0] == 1, msg="Unbatched input should create batched output with bsz = 1") + + def test_unbatched_batched_outputs_consistency(self): + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + unbatched_spectrogram = inputs["input_features"].detach().clone() + unbatched_noise_sequence = inputs["noise_sequence"].detach().clone() + batched_spectrogram = inputs["input_features"].unsqueeze(0) + batched_noise_sequence = inputs["noise_sequence"].unsqueeze(0) + + with torch.no_grad(): + unbatched_outputs = model( + unbatched_spectrogram.to(torch_device), + unbatched_noise_sequence.to(torch_device), + )[0] + + batched_outputs = model( + batched_spectrogram.to(torch_device), + batched_noise_sequence.to(torch_device), + )[0] + + torch.testing.assert_close(unbatched_outputs, batched_outputs) + + +@require_torch_gpu +@slow +class UnivNetModelIntegrationTests(unittest.TestCase): + def tearDown(self): + super().tearDown() + gc.collect() + torch.cuda.empty_cache() + + def _load_datasamples(self, num_samples, sampling_rate=24000): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + ds = ds.cast_column("audio", Audio(sampling_rate=sampling_rate)) + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples], [x["sampling_rate"] for x in speech_samples] + + def get_inputs(self, device, num_samples: int = 3, noise_length: int = 10, seed: int = 0): + generator = torch.manual_seed(seed) + # Note: hardcode model_in_channels -> 64 + if num_samples == 1: + noise_sequence_shape = (64, noise_length) + else: + noise_sequence_shape = (num_samples, 64, noise_length) + # Explicity generate noise_sequence on CPU for consistency. + noise_sequence = torch.randn(noise_sequence_shape, generator=generator, dtype=torch.float32, device="cpu") + # Put noise_sequence on the desired device. + noise_sequence = noise_sequence.to(device) + + # Note: hardcode num_mel_channels -> 100 + if num_samples == 1: + spectrogram_shape = [100, noise_length] + else: + spectrogram_shape = [num_samples, 100, noise_length] + spectrogram = floats_tensor(spectrogram_shape, scale=1.0, rng=random.Random(seed)) + # Note: spectrogram should already be on torch_device + + # Permute to match diffusers implementation + if num_samples == 1: + noise_sequence = noise_sequence.transpose(1, 0) + spectrogram = spectrogram.transpose(1, 0) + else: + noise_sequence = noise_sequence.transpose(2, 1) + spectrogram = spectrogram.transpose(2, 1) + + inputs = { + "input_features": spectrogram, + "noise_sequence": noise_sequence, + "generator": generator, + } + + return inputs + + def test_model_inference_batched(self): + # Load sample checkpoint from Tortoise TTS + model = UnivNetModel.from_pretrained("dg845/univnet-dev") + model.eval().to(torch_device) + + # Get batched noise and spectrogram inputs. + input_speech = self.get_inputs(torch_device, num_samples=3) + + with torch.no_grad(): + waveform = model(**input_speech)[0] + waveform = waveform.cpu() + + waveform_mean = torch.mean(waveform) + waveform_stddev = torch.std(waveform) + waveform_slice = waveform[-1, -9:].flatten() + + EXPECTED_MEAN = torch.tensor(-0.19989729) + EXPECTED_STDDEV = torch.tensor(0.35230172) + EXPECTED_SLICE = torch.tensor([-0.3408, -0.6045, -0.5052, 0.1160, -0.1556, -0.0405, -0.3024, -0.5290, -0.5019]) + + torch.testing.assert_close(waveform_mean, EXPECTED_MEAN, atol=1e-4, rtol=1e-5) + torch.testing.assert_close(waveform_stddev, EXPECTED_STDDEV, atol=1e-4, rtol=1e-5) + torch.testing.assert_close(waveform_slice, EXPECTED_SLICE, atol=5e-4, rtol=1e-5) + + def test_model_inference_unbatched(self): + # Load sample checkpoint from Tortoise TTS + model = UnivNetModel.from_pretrained("dg845/univnet-dev") + model.eval().to(torch_device) + + # Get unbatched noise and spectrogram inputs. + input_speech = self.get_inputs(torch_device, num_samples=1) + + with torch.no_grad(): + waveform = model(**input_speech)[0] + waveform = waveform.cpu() + + waveform_mean = torch.mean(waveform) + waveform_stddev = torch.std(waveform) + waveform_slice = waveform[-1, -9:].flatten() + + EXPECTED_MEAN = torch.tensor(-0.22895093) + EXPECTED_STDDEV = torch.tensor(0.33986747) + EXPECTED_SLICE = torch.tensor([-0.3276, -0.5504, -0.3484, 0.3574, -0.0373, -0.1826, -0.4880, -0.6431, -0.5162]) + + torch.testing.assert_close(waveform_mean, EXPECTED_MEAN, atol=1e-4, rtol=1e-5) + torch.testing.assert_close(waveform_stddev, EXPECTED_STDDEV, atol=1e-4, rtol=1e-5) + torch.testing.assert_close(waveform_slice, EXPECTED_SLICE, atol=1e-3, rtol=1e-5) + + def test_integration(self): + feature_extractor = UnivNetFeatureExtractor.from_pretrained("dg845/univnet-dev") + model = UnivNetModel.from_pretrained("dg845/univnet-dev") + model.eval().to(torch_device) + + audio, sr = self._load_datasamples(1, sampling_rate=feature_extractor.sampling_rate) + + input_features = feature_extractor(audio, sampling_rate=sr[0], return_tensors="pt").input_features + input_features = input_features.to(device=torch_device) + + input_speech = self.get_inputs(torch_device, num_samples=1, noise_length=input_features.shape[1]) + input_speech["input_features"] = input_features + + with torch.no_grad(): + waveform = model(**input_speech)[0] + waveform = waveform.cpu() + + waveform_mean = torch.mean(waveform) + waveform_stddev = torch.std(waveform) + waveform_slice = waveform[-1, -9:].flatten() + + EXPECTED_MEAN = torch.tensor(0.00051374) + EXPECTED_STDDEV = torch.tensor(0.058105603) + # fmt: off + EXPECTED_SLICE = torch.tensor([-4.3934e-04, -1.8203e-04, -3.3033e-04, -3.8716e-04, -1.6125e-04, 3.5389e-06, -3.3149e-04, -3.7613e-04, -2.3331e-04]) + # fmt: on + + torch.testing.assert_close(waveform_mean, EXPECTED_MEAN, atol=5e-6, rtol=1e-5) + torch.testing.assert_close(waveform_stddev, EXPECTED_STDDEV, atol=1e-4, rtol=1e-5) + torch.testing.assert_close(waveform_slice, EXPECTED_SLICE, atol=5e-6, rtol=1e-5) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/upernet/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/upernet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/upernet/test_modeling_upernet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/upernet/test_modeling_upernet.py new file mode 100644 index 0000000000000000000000000000000000000000..aeeba191b67af28b8a9c4365f282173ddbe93d90 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/upernet/test_modeling_upernet.py @@ -0,0 +1,302 @@ +# coding=utf-8 +# Copyright 2022 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 UperNet framework. """ + + +import unittest + +from huggingface_hub import hf_hub_download + +from transformers import ConvNextConfig, UperNetConfig +from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device +from transformers.utils import is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import UperNetForSemanticSegmentation + from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class UperNetModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=32, + num_channels=3, + num_stages=4, + hidden_sizes=[10, 20, 30, 40], + depths=[1, 1, 1, 1], + is_training=True, + use_labels=True, + intermediate_size=37, + hidden_act="gelu", + type_sequence_label_size=10, + initializer_range=0.02, + out_features=["stage2", "stage3", "stage4"], + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.num_stages = num_stages + self.hidden_sizes = hidden_sizes + self.depths = depths + self.is_training = is_training + self.use_labels = use_labels + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.out_features = out_features + self.num_labels = num_labels + self.scope = scope + self.num_hidden_layers = num_stages + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_backbone_config(self): + return ConvNextConfig( + num_channels=self.num_channels, + num_stages=self.num_stages, + hidden_sizes=self.hidden_sizes, + depths=self.depths, + is_training=self.is_training, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + out_features=self.out_features, + ) + + def get_config(self): + return UperNetConfig( + backbone_config=self.get_backbone_config(), + hidden_size=64, + pool_scales=[1, 2, 3, 6], + use_auxiliary_head=True, + auxiliary_loss_weight=0.4, + auxiliary_in_channels=40, + auxiliary_channels=32, + auxiliary_num_convs=1, + auxiliary_concat_input=False, + loss_ignore_index=255, + num_labels=self.num_labels, + ) + + def create_and_check_for_semantic_segmentation(self, config, pixel_values, labels): + model = UperNetForSemanticSegmentation(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.num_labels, self.image_size, self.image_size) + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + pixel_values, + labels, + ) = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class UperNetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as UperNet does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (UperNetForSemanticSegmentation,) if is_torch_available() else () + pipeline_model_mapping = {"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {} + fx_compatible = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + test_torchscript = False + has_attentions = False + + def setUp(self): + self.model_tester = UperNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=UperNetConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + def test_for_semantic_segmentation(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_semantic_segmentation(*config_and_inputs) + + @unittest.skip(reason="UperNet does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="UperNet does not support input and output embeddings") + def test_model_common_attributes(self): + pass + + @unittest.skip(reason="UperNet does not have a base model") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip(reason="UperNet does not have a base model") + def test_save_load_fast_init_to_base(self): + pass + + @require_torch_multi_gpu + @unittest.skip(reason="UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`") + def test_multi_gpu_data_parallel_forward(self): + pass + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_stages = self.model_tester.num_stages + self.assertEqual(len(hidden_states), expected_num_stages + 1) + + # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.image_size // 4, self.model_tester.image_size // 4], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + configs_no_init.backbone_config = _config_zero_init(configs_no_init.backbone_config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if param.requires_grad: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + @unittest.skip(reason="UperNet does not have tied weights") + def test_tied_model_weights_key_ignore(self): + pass + + @slow + def test_model_from_pretrained(self): + for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = UperNetForSemanticSegmentation.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of ADE20k +def prepare_img(): + filepath = hf_hub_download( + repo_id="hf-internal-testing/fixtures_ade20k", repo_type="dataset", filename="ADE_val_00000001.jpg" + ) + image = Image.open(filepath).convert("RGB") + return image + + +@require_torch +@require_vision +@slow +class UperNetModelIntegrationTest(unittest.TestCase): + def test_inference_swin_backbone(self): + processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny") + model = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny").to(torch_device) + + image = prepare_img() + inputs = processor(images=image, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + + expected_shape = torch.Size((1, model.config.num_labels, 512, 512)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor( + [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] + ).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3], expected_slice, atol=1e-4)) + + def test_inference_convnext_backbone(self): + processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny") + model = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny").to(torch_device) + + image = prepare_img() + inputs = processor(images=image, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + outputs = model(**inputs) + + expected_shape = torch.Size((1, model.config.num_labels, 512, 512)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor( + [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] + ).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/videomae/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/videomae/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/videomae/test_image_processing_videomae.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/videomae/test_image_processing_videomae.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6f0b93c4dde9684c582cbc0ac57b0b2fa80447 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/videomae/test_image_processing_videomae.py @@ -0,0 +1,214 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. +# +# 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 unittest + +import numpy as np + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_video_inputs + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + from transformers import VideoMAEImageProcessor + + +class VideoMAEImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + num_frames=10, + image_size=18, + min_resolution=30, + max_resolution=400, + do_resize=True, + size=None, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + crop_size=None, + ): + size = size if size is not None else {"shortest_edge": 18} + crop_size = crop_size if crop_size is not None else {"height": 18, "width": 18} + + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.num_frames = num_frames + self.image_size = image_size + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + self.crop_size = crop_size + + def prepare_image_processor_dict(self): + return { + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_normalize": self.do_normalize, + "do_resize": self.do_resize, + "size": self.size, + "crop_size": self.crop_size, + } + + def expected_output_image_shape(self, images): + return self.num_frames, self.num_channels, self.crop_size["height"], self.crop_size["width"] + + def prepare_video_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_video_inputs( + batch_size=self.batch_size, + num_frames=self.num_frames, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class VideoMAEImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = VideoMAEImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = VideoMAEImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "do_center_crop")) + self.assertTrue(hasattr(image_processing, "size")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"shortest_edge": 18}) + self.assertEqual(image_processor.crop_size, {"height": 18, "width": 18}) + + image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42, crop_size=84) + self.assertEqual(image_processor.size, {"shortest_edge": 42}) + self.assertEqual(image_processor.crop_size, {"height": 84, "width": 84}) + + def test_call_pil(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PIL videos + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], Image.Image) + + # Test not batched input + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos) + self.assertEqual( + tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape) + ) + + def test_call_numpy(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], np.ndarray) + + # Test not batched input + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos) + self.assertEqual( + tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape) + ) + + def test_call_numpy_4_channels(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + self.image_processor_tester.num_channels = 4 + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], np.ndarray) + + # Test not batched input + encoded_videos = image_processing( + video_inputs[0], return_tensors="pt", image_mean=0, image_std=1, input_data_format="channels_first" + ).pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = image_processing( + video_inputs, return_tensors="pt", image_mean=0, image_std=1, input_data_format="channels_first" + ).pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos) + self.assertEqual( + tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape) + ) + self.image_processor_tester.num_channels = 3 + + def test_call_pytorch(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, torchify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], torch.Tensor) + + # Test not batched input + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos) + self.assertEqual( + tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape) + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/videomae/test_modeling_videomae.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/videomae/test_modeling_videomae.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd9f90c308558147813f20e9aaf33f33c44567b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/videomae/test_modeling_videomae.py @@ -0,0 +1,420 @@ +# coding=utf-8 +# Copyright 2022 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 VideoMAE model. """ + + +import copy +import unittest + +import numpy as np +from huggingface_hub import hf_hub_download + +from transformers import VideoMAEConfig +from transformers.models.auto import get_values +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ( + MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, + VideoMAEForPreTraining, + VideoMAEForVideoClassification, + VideoMAEModel, + ) + from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from transformers import VideoMAEImageProcessor + + +class VideoMAEModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=10, + num_channels=3, + patch_size=2, + tubelet_size=2, + num_frames=2, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + mask_ratio=0.9, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.num_channels = num_channels + self.patch_size = patch_size + self.tubelet_size = tubelet_size + self.num_frames = num_frames + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.mask_ratio = mask_ratio + self.scope = scope + + # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame + self.num_patches_per_frame = (image_size // patch_size) ** 2 + self.seq_length = (num_frames // tubelet_size) * self.num_patches_per_frame + + # use this variable to define bool_masked_pos + self.num_masks = int(mask_ratio * self.seq_length) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor( + [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] + ) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return VideoMAEConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + num_frames=self.num_frames, + tubelet_size=self.tubelet_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + decoder_hidden_size=self.hidden_size, + decoder_intermediate_size=self.intermediate_size, + decoder_num_attention_heads=self.num_attention_heads, + decoder_num_hidden_layers=self.num_hidden_layers, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = VideoMAEModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_pretraining(self, config, pixel_values, labels): + model = VideoMAEForPreTraining(config) + model.to(torch_device) + model.eval() + # important: each video needs to have the same number of masked patches + # hence we define a single mask, which we then repeat for each example in the batch + mask = torch.ones((self.num_masks,)) + mask = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0))]) + bool_masked_pos = mask.expand(self.batch_size, -1).bool() + + result = model(pixel_values, bool_masked_pos) + # model only returns predictions for masked patches + num_masked_patches = mask.sum().item() + decoder_num_labels = 3 * self.tubelet_size * self.patch_size**2 + self.parent.assertEqual(result.logits.shape, (self.batch_size, num_masked_patches, decoder_num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class VideoMAEModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as VideoMAE does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = ( + (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () + ) + pipeline_model_mapping = ( + {"feature-extraction": VideoMAEModel, "video-classification": VideoMAEForVideoClassification} + if is_torch_available() + else {} + ) + + test_pruning = False + test_torchscript = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = VideoMAEModelTester(self) + self.config_tester = ConfigTester(self, config_class=VideoMAEConfig, has_text_modality=False, hidden_size=37) + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = copy.deepcopy(inputs_dict) + + if model_class == VideoMAEForPreTraining: + # important: each video needs to have the same number of masked patches + # hence we define a single mask, which we then repeat for each example in the batch + mask = torch.ones((self.model_tester.num_masks,)) + mask = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0))]) + bool_masked_pos = mask.expand(self.model_tester.batch_size, -1).bool() + inputs_dict["bool_masked_pos"] = bool_masked_pos.to(torch_device) + + if return_labels: + if model_class in [ + *get_values(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING), + ]: + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + + return inputs_dict + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="VideoMAE does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_pretraining(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_pretraining(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = VideoMAEModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_attention_outputs(self): + if not self.has_attentions: + pass + + else: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + num_visible_patches = self.model_tester.seq_length - self.model_tester.num_masks + seq_len = ( + num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length + ) + + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + expected_num_layers = self.model_tester.num_hidden_layers + 1 + self.assertEqual(len(hidden_states), expected_num_layers) + + num_visible_patches = self.model_tester.seq_length - self.model_tester.num_masks + seq_length = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + +# We will verify our results on a video of eating spaghetti +# Frame indices used: [164 168 172 176 181 185 189 193 198 202 206 210 215 219 223 227] +def prepare_video(): + file = hf_hub_download( + repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti.npy", repo_type="dataset" + ) + video = np.load(file) + return list(video) + + +@require_torch +@require_vision +class VideoMAEModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + # logits were tested with a different mean and std, so we use the same here + return ( + VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]) + if is_vision_available() + else None + ) + + @slow + def test_inference_for_video_classification(self): + model = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics").to( + torch_device + ) + + image_processor = self.default_image_processor + video = prepare_video() + inputs = image_processor(video, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 400)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([0.3669, -0.0688, -0.2421]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_for_pretraining(self): + model = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short").to(torch_device) + + image_processor = self.default_image_processor + video = prepare_video() + inputs = image_processor(video, return_tensors="pt").to(torch_device) + + # add boolean mask, indicating which patches to mask + local_path = hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos", filename="bool_masked_pos.pt") + inputs["bool_masked_pos"] = torch.load(local_path) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size([1, 1408, 1536]) + expected_slice = torch.tensor( + [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]], device=torch_device + ) + self.assertEqual(outputs.logits.shape, expected_shape) + self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_slice, atol=1e-4)) + + # verify the loss (`config.norm_pix_loss` = `True`) + expected_loss = torch.tensor([0.5142], device=torch_device) + self.assertTrue(torch.allclose(outputs.loss, expected_loss, atol=1e-4)) + + # verify the loss (`config.norm_pix_loss` = `False`) + model = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base-short", norm_pix_loss=False).to( + torch_device + ) + + with torch.no_grad(): + outputs = model(**inputs) + + expected_loss = torch.tensor(torch.tensor([0.6469]), device=torch_device) + self.assertTrue(torch.allclose(outputs.loss, expected_loss, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vilt/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vilt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vilt/test_image_processing_vilt.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vilt/test_image_processing_vilt.py new file mode 100644 index 0000000000000000000000000000000000000000..607a8b929d1f8b24ac4cdfceaa3654bb63d05336 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vilt/test_image_processing_vilt.py @@ -0,0 +1,153 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 unittest + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs + + +if is_vision_available(): + from PIL import Image + + from transformers import ViltImageProcessor + + +class ViltImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + image_size=18, + min_resolution=30, + max_resolution=400, + do_resize=True, + size=None, + size_divisor=2, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + ): + size = size if size is not None else {"shortest_edge": 30} + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.image_size = image_size + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = size + self.size_divisor = size_divisor + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + + def prepare_image_processor_dict(self): + return { + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_normalize": self.do_normalize, + "do_resize": self.do_resize, + "size": self.size, + "size_divisor": self.size_divisor, + } + + def get_expected_values(self, image_inputs, batched=False): + """ + This function computes the expected height and width when providing images to ViltImageProcessor, + assuming do_resize is set to True with a scalar size and size_divisor. + """ + if not batched: + size = self.size["shortest_edge"] + image = image_inputs[0] + if isinstance(image, Image.Image): + w, h = image.size + else: + h, w = image.shape[1], image.shape[2] + scale = size / min(w, h) + if h < w: + newh, neww = size, scale * w + else: + newh, neww = scale * h, size + + max_size = int((1333 / 800) * size) + if max(newh, neww) > max_size: + scale = max_size / max(newh, neww) + newh = newh * scale + neww = neww * scale + + newh, neww = int(newh + 0.5), int(neww + 0.5) + expected_height, expected_width = ( + newh // self.size_divisor * self.size_divisor, + neww // self.size_divisor * self.size_divisor, + ) + + else: + expected_values = [] + for image in image_inputs: + expected_height, expected_width = self.get_expected_values([image]) + expected_values.append((expected_height, expected_width)) + expected_height = max(expected_values, key=lambda item: item[0])[0] + expected_width = max(expected_values, key=lambda item: item[1])[1] + + return expected_height, expected_width + + def expected_output_image_shape(self, images): + height, width = self.get_expected_values(images, batched=True) + return (self.num_channels, height, width) + + def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_image_inputs( + batch_size=self.batch_size, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class ViltImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = ViltImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = ViltImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "size")) + self.assertTrue(hasattr(image_processing, "size_divisor")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"shortest_edge": 30}) + + image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42) + self.assertEqual(image_processor.size, {"shortest_edge": 42}) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vilt/test_modeling_vilt.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vilt/test_modeling_vilt.py new file mode 100644 index 0000000000000000000000000000000000000000..853701e3a8ea78da81dda344aa031338a88d9e9e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vilt/test_modeling_vilt.py @@ -0,0 +1,665 @@ +# coding=utf-8 +# Copyright 2022 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 ViLT model. """ + +import unittest + +from datasets import load_dataset +from packaging import version + +from transformers import ViltConfig, is_torch_available, is_vision_available +from transformers.models.auto import get_values +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + MODEL_MAPPING, + ViltForImageAndTextRetrieval, + ViltForImagesAndTextClassification, + ViltForMaskedLM, + ViltForQuestionAnswering, + ViltForTokenClassification, + ViltModel, + ) + from transformers.models.vilt.modeling_vilt import VILT_PRETRAINED_MODEL_ARCHIVE_LIST + +if is_vision_available(): + import PIL + from PIL import Image + + from transformers import ViltProcessor + + +class ViltModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + image_size=30, + patch_size=2, + num_channels=3, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + scope=None, + modality_type_vocab_size=2, + add_multiple_images=False, + num_images=-1, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.scope = scope + self.modality_type_vocab_size = modality_type_vocab_size + self.add_multiple_images = add_multiple_images + self.num_images = num_images + # we set the expected sequence length (which is used in several tests) + # this is equal to the seq length of the text tokens + number of image patches + 1 for the CLS token + self.expected_seq_len = self.seq_length + (self.image_size // self.patch_size) ** 2 + 1 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + if self.add_multiple_images: + pixel_values = floats_tensor([self.batch_size, 2, self.num_channels, self.image_size, self.image_size]) + else: + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + if self.use_labels: + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + + config = self.get_config() + + return (config, input_ids, token_type_ids, input_mask, pixel_values, token_labels) + + def get_config(self): + return ViltConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + num_labels=self.num_labels, + modality_type_vocab_size=self.modality_type_vocab_size, + num_images=self.num_images, + ) + + def create_and_check_model( + self, + config, + input_ids, + token_type_ids, + input_mask, + pixel_values, + token_labels, + ): + model = ViltModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, pixel_values=pixel_values) + result = model(input_ids, token_type_ids=token_type_ids, pixel_values=pixel_values) + result = model(input_ids, pixel_values=pixel_values) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.expected_seq_len, self.hidden_size) + ) + + def create_and_check_for_token_classification( + self, + config, + input_ids, + token_type_ids, + input_mask, + pixel_values, + token_labels, + ): + model = ViltForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, pixel_values=pixel_values) + result = model(input_ids, token_type_ids=token_type_ids, pixel_values=pixel_values) + result = model(input_ids, pixel_values=pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + pixel_values, + token_labels, + ) = config_and_inputs + inputs_dict = { + "input_ids": input_ids, + "token_type_ids": token_type_ids, + "attention_mask": input_mask, + "pixel_values": pixel_values, + } + return config, inputs_dict + + def prepare_pixel_values(self): + return floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + +@require_torch +class ViltModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + ViltModel, + ViltForQuestionAnswering, + ViltForImageAndTextRetrieval, + ViltForMaskedLM, + ViltForTokenClassification, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + {"feature-extraction": ViltModel, "visual-question-answering": ViltForQuestionAnswering} + if is_torch_available() + else {} + ) + test_pruning = False + test_headmasking = False + test_torchscript = False + model_split_percents = [0.5, 0.8, 0.9] + + # ViltForMaskedLM, ViltForQuestionAnswering and ViltForImagesAndTextClassification require special treatment + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) + + if return_labels: + if model_class.__name__ == "ViltForQuestionAnswering": + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, self.model_tester.num_labels, device=torch_device + ) + elif model_class.__name__ in ["ViltForMaskedLM", "ViltForTokenClassification"]: + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + elif model_class.__name__ == "ViltForImagesAndTextClassification": + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + + return inputs_dict + + def setUp(self): + self.model_tester = ViltModelTester(self) + self.config_tester = ConfigTester(self, config_class=ViltConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_training(self): + if not self.model_tester.is_training: + return + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + if model_class.__name__ == "ViltForImagesAndTextClassification": + config.modality_type_vocab_size = 3 + + # ViltForImageAndTextRetrieval doesn't support training for now + if model_class in [*get_values(MODEL_MAPPING), ViltForImageAndTextRetrieval]: + continue + + model = model_class(config) + model.to(torch_device) + model.train() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + for k, v in inputs.items(): + print(k, v.shape) + loss = model(**inputs).loss + loss.backward() + + def test_training_gradient_checkpointing(self): + if not self.model_tester.is_training: + return + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.use_cache = False + config.return_dict = True + + # ViltForImageAndTextRetrieval doesn't support training for now + if ( + model_class in [*get_values(MODEL_MAPPING), ViltForImageAndTextRetrieval] + or not model_class.supports_gradient_checkpointing + ): + continue + + model = model_class(config) + model.to(torch_device) + model.gradient_checkpointing_enable() + model.train() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + loss = model(**inputs).loss + loss.backward() + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + @unittest.skip( + reason="""VilT samples image tokens from a multinomial distribution, resulting in not deterministic + hidden states""" + ) + def test_save_load(self): + pass + + @unittest.skip( + reason="""VilT samples image tokens from a multinomial distribution, resulting in not deterministic + hidden states""" + ) + def test_determinism(self): + pass + + @unittest.skip( + reason="""VilT samples image tokens from a multinomial distribution, resulting in not deterministic + hidden states""" + ) + def test_model_outputs_equivalence(self): + pass + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "expected_seq_len", None) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + if model_class.__name__ == "ViltForImagesAndTextClassification": + # attentions are a list of length num_images + # each element contains the attentions of a particular image index + self.assertEqual(len(attentions), self.model_tester.num_images) + self.assertEqual(len(attentions[0]), self.model_tester.num_hidden_layers) + else: + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + if model_class.__name__ == "ViltForImagesAndTextClassification": + # attentions are a list of length num_images + # each element contains the attentions of a particular image index + self.assertEqual(len(attentions), self.model_tester.num_images) + self.assertEqual(len(attentions[0]), self.model_tester.num_hidden_layers) + else: + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + if model_class.__name__ == "ViltForImagesAndTextClassification": + self.assertListEqual( + list(attentions[0][0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + else: + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + if model_class.__name__ == "ViltForImagesAndTextClassification": + self.assertEqual(len(self_attentions), self.model_tester.num_images) + self.assertEqual(len(self_attentions[0]), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0][0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + else: + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + if model_class.__name__ == "ViltForImagesAndTextClassification": + # hidden_states are a list of length num_images + # each element contains the hidden states of a particular image index + self.assertEqual(len(hidden_states), self.model_tester.num_images) + self.assertEqual(len(hidden_states[0]), expected_num_layers) + else: + self.assertEqual(len(hidden_states), expected_num_layers) + + seq_length = self.model_tester.expected_seq_len + + if model_class.__name__ == "ViltForImagesAndTextClassification": + self.assertListEqual( + list(hidden_states[0][0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + else: + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + print("Model class:", model_class) + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs = model(**inputs) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + if model_class.__name__ == "ViltForImagesAndTextClassification": + # hidden_states are a list of length num_images + # each element contains the hidden states of a particular image index + hidden_states[0].retain_grad() + attentions[0].retain_grad() + else: + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + if model_class.__name__ == "ViltForImagesAndTextClassification": + # hidden_states are a list of length num_images + # each element contains the hidden states of a particular image index + self.assertIsNotNone(hidden_states[0].grad) + self.assertIsNotNone(attentions[0].grad) + else: + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + @slow + def test_model_from_pretrained(self): + for model_name in VILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = ViltModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_torch +class ViltForImagesAndTextClassificationModelTest(ViltModelTest, unittest.TestCase): + all_model_classes = (ViltForImagesAndTextClassification,) if is_torch_available() else () + + def setUp(self): + self.model_tester = ViltModelTester(self, modality_type_vocab_size=3, add_multiple_images=True, num_images=2) + self.config_tester = ConfigTester(self, config_class=ViltConfig, hidden_size=37) + + @unittest.skip("We only test the model that takes in multiple images") + def test_model(self): + pass + + @unittest.skip("We only test the model that takes in multiple images") + def test_for_token_classification(self): + pass + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class ViltModelIntegrationTest(unittest.TestCase): + @cached_property + def default_processor(self): + return ViltProcessor.from_pretrained("dandelin/vilt-b32-finetuned-vqa") if is_vision_available() else None + + @slow + def test_inference_masked_lm(self): + model = ViltForMaskedLM.from_pretrained("dandelin/vilt-b32-mlm").to(torch_device) + + processor = self.default_processor + image = prepare_img() + text = "a bunch of [MASK] laying on a [MASK]." + inputs = processor(image, text, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size([1, 11, 30522]) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-12.5061, -12.5123, -12.5174]).to(torch_device) + self.assertTrue(torch.allclose(outputs.logits[0, 0, :3], expected_slice, atol=1e-4)) + + # verify masked token prediction equals "cats" + predicted_id = outputs.logits[0, 4, :].argmax(-1).item() + assert processor.decode([predicted_id]) == "cats" + + @slow + def test_inference_visual_question_answering(self): + model = ViltForQuestionAnswering.from_pretrained("dandelin/vilt-b32-finetuned-vqa").to(torch_device) + + processor = self.default_processor + image = prepare_img() + text = "How many cats are there?" + inputs = processor(image, text, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 3129)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-15.9495, -18.1472, -10.3041]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) + + # compute loss + vqa_labels = [[2, 3, 155, 800]] + vqa_scores = [[1.0, 0.3, 0.3, 0.3]] + labels = torch.zeros(1, model.config.num_labels).to(torch_device) + + for i, (labels_example, scores_example) in enumerate(zip(vqa_labels, vqa_scores)): + for l, s in zip(labels_example, scores_example): + labels[i, l] = s + + # forward pass + outputs = model(**inputs, labels=labels) + + # verify we have a positive loss + self.assertTrue(outputs.loss > 0) + + @slow + def test_inference_natural_language_visual_reasoning(self): + model = ViltForImagesAndTextClassification.from_pretrained("dandelin/vilt-b32-finetuned-nlvr2").to( + torch_device + ) + + processor = self.default_processor + + dataset = load_dataset("hf-internal-testing/fixtures_nlvr2", split="test") + image1 = Image.open(dataset[0]["file"]).convert("RGB") + image2 = Image.open(dataset[1]["file"]).convert("RGB") + + text = ( + "The left image contains twice the number of dogs as the right image, and at least two dogs in total are" + " standing." + ) + encoding_1 = processor(image1, text, return_tensors="pt") + encoding_2 = processor(image2, text, return_tensors="pt") + + pixel_values = torch.stack([encoding_1.pixel_values, encoding_2.pixel_values], dim=1) + + # forward pass + outputs = model( + input_ids=encoding_1.input_ids.to(torch_device), + pixel_values=pixel_values.to(torch_device), + ) + + # verify the logits + expected_shape = torch.Size([1, 2]) + self.assertEqual(outputs.logits.shape, expected_shape) + + is_pillow_less_than_9 = version.parse(PIL.__version__) < version.parse("9.0.0") + + if is_pillow_less_than_9: + expected_slice = torch.tensor( + [-2.4013, 2.9342], + device=torch_device, + ) + else: + expected_slice = torch.tensor( + [-2.3713, 2.9168], + device=torch_device, + ) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vipllava/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vipllava/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vipllava/test_modeling_vipllava.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vipllava/test_modeling_vipllava.py new file mode 100644 index 0000000000000000000000000000000000000000..e09527343e24faf043b7b254b97074c903260a1d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vipllava/test_modeling_vipllava.py @@ -0,0 +1,216 @@ +# coding=utf-8 +# Copyright 2023 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 VipLlava model. """ + +import gc +import unittest + +import requests + +from transformers import ( + AutoProcessor, + VipLlavaConfig, + VipLlavaForConditionalGeneration, + is_torch_available, + is_vision_available, +) +from transformers.testing_utils import require_bitsandbytes, require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor + + +if is_torch_available(): + import torch +else: + is_torch_greater_or_equal_than_2_0 = False + +if is_vision_available(): + from PIL import Image + + +# Copied from transformers.tests.models.llava.test_modeling_llava.LlavaVisionText2TextModelTester with Llava->VipLlava +class VipLlavaVisionText2TextModelTester: + # Ignore copy + def __init__( + self, + parent, + ignore_index=-100, + image_token_index=0, + projector_hidden_act="gelu", + seq_length=7, + vision_feature_layers=[0, 0, 1, 1, 0], + text_config={ + "model_type": "llama", + "seq_length": 7, + "is_training": True, + "use_input_mask": True, + "use_token_type_ids": False, + "use_labels": True, + "vocab_size": 99, + "hidden_size": 32, + "num_hidden_layers": 2, + "num_attention_heads": 4, + "intermediate_size": 37, + "hidden_act": "gelu", + "hidden_dropout_prob": 0.1, + "attention_probs_dropout_prob": 0.1, + "max_position_embeddings": 512, + "type_vocab_size": 16, + "type_sequence_label_size": 2, + "initializer_range": 0.02, + "num_labels": 3, + "num_choices": 4, + "pad_token_id": 0, + }, + is_training=True, + vision_config={ + "batch_size": 12, + "image_size": 30, + "patch_size": 2, + "num_channels": 3, + "is_training": True, + "hidden_size": 32, + "projection_dim": 32, + "num_hidden_layers": 2, + "num_attention_heads": 4, + "intermediate_size": 37, + "dropout": 0.1, + "attention_dropout": 0.1, + "initializer_range": 0.02, + }, + ): + self.parent = parent + self.ignore_index = ignore_index + self.image_token_index = image_token_index + self.projector_hidden_act = projector_hidden_act + self.vision_feature_layers = vision_feature_layers + self.text_config = text_config + self.vision_config = vision_config + self.seq_length = seq_length + + self.num_hidden_layers = text_config["num_hidden_layers"] + self.vocab_size = text_config["vocab_size"] + self.hidden_size = text_config["hidden_size"] + self.num_attention_heads = text_config["num_attention_heads"] + self.is_training = is_training + + self.batch_size = 3 + self.num_channels = 3 + self.image_size = 336 + self.encoder_seq_length = 231 + + def get_config(self): + return VipLlavaConfig( + text_config=self.text_config, + vision_config=self.vision_config, + ignore_index=self.ignore_index, + image_token_index=self.image_token_index, + projector_hidden_act=self.projector_hidden_act, + vision_feature_layers=self.vision_feature_layers, + ) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor( + [ + self.batch_size, + self.vision_config["num_channels"], + self.vision_config["image_size"], + self.vision_config["image_size"], + ] + ) + config = self.get_config() + + return config, pixel_values + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values = config_and_inputs + input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 1) + 1 + attention_mask = input_ids.ne(1).to(torch_device) + # we are giving 3 images let's make sure we pass in 3 image tokens + input_ids[:, 1] = config.image_token_index + inputs_dict = { + "pixel_values": pixel_values, + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + +@require_torch +# Copied from transformers.tests.models.llava.test_modeling_llava.LlavaForConditionalGenerationModelTest with Llava->VipLlava +class VipLlavaForConditionalGenerationModelTest(ModelTesterMixin, unittest.TestCase): + """ + Model tester for `VipLlavaForConditionalGeneration`. + """ + + all_model_classes = (VipLlavaForConditionalGeneration,) if is_torch_available() else () + fx_compatible = False + test_pruning = False + test_resize_embeddings = True + test_head_masking = False + + def setUp(self): + self.model_tester = VipLlavaVisionText2TextModelTester(self) + self.config_tester = ConfigTester(self, config_class=VipLlavaConfig, has_text_modality=False) + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + +@require_torch +class VipLlavaForConditionalGenerationIntegrationTest(unittest.TestCase): + def setUp(self): + self.processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf") + + def tearDown(self): + gc.collect() + torch.cuda.empty_cache() + + @slow + @require_bitsandbytes + def test_small_model_integration_test(self): + model_id = "llava-hf/vip-llava-7b-hf" + + model = VipLlavaForConditionalGeneration.from_pretrained(model_id, load_in_4bit=True) + processor = AutoProcessor.from_pretrained(model_id) + + url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/compel-neg.png" + + image = Image.open(requests.get(url, stream=True).raw) + prompt = "USER: \nCan you please describe this image?\nASSISTANT:" + + inputs = processor(prompt, image, return_tensors="pt").to(torch_device, torch.float16) + + outputs = model.generate(**inputs, max_new_tokens=10) + + EXPECTED_OUTPUT = "USER: \nCan you please describe this image?\nASSISTANT: The image features a brown and white cat sitting on" + self.assertEqual(processor.decode(outputs[0], skip_special_tokens=True), EXPECTED_OUTPUT) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_flax_vision_encoder_decoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_flax_vision_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..c6926e002a9b6383beb1fadab8802e2bbe444482 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_flax_vision_encoder_decoder.py @@ -0,0 +1,514 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. team. +# +# 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 tempfile +import unittest + +import numpy as np + +from transformers import is_flax_available, is_torch_available, is_vision_available +from transformers.testing_utils import is_pt_flax_cross_test, require_flax, require_vision, slow, torch_device + +from ...test_modeling_flax_common import floats_tensor, ids_tensor +from ..gpt2.test_modeling_flax_gpt2 import FlaxGPT2ModelTester +from ..vit.test_modeling_flax_vit import FlaxViTModelTester + + +if is_flax_available(): + from transformers import ( + AutoTokenizer, + FlaxGPT2LMHeadModel, + FlaxVisionEncoderDecoderModel, + FlaxViTModel, + VisionEncoderDecoderConfig, + ) + from transformers.modeling_flax_pytorch_utils import ( + convert_pytorch_state_dict_to_flax, + load_flax_weights_in_pytorch_model, + ) + +if is_torch_available(): + import torch + + from transformers import VisionEncoderDecoderModel + +if is_vision_available(): + from PIL import Image + + from transformers import ViTImageProcessor + + +@require_flax +class FlaxEncoderDecoderMixin: + def get_encoder_decoder_model(self, config, decoder_config): + raise NotImplementedError + + def prepare_config_and_inputs(self): + raise NotImplementedError + + def get_pretrained_model(self): + raise NotImplementedError + + def check_encoder_decoder_model_from_pretrained_configs( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_decoder_config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + self.assertTrue(encoder_decoder_config.decoder.is_decoder) + + enc_dec_model = FlaxVisionEncoderDecoderModel(encoder_decoder_config) + + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[0], pixel_values.shape[0]) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[-1], config.hidden_size) + + def check_encoder_decoder_model_from_pretrained( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + return_dict, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model, "return_dict": return_dict} + enc_dec_model = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + return_dict=True, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[0], pixel_values.shape[0]) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[-1], config.hidden_size) + + def check_save_and_load( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} + enc_dec_model = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + + outputs = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + out_2 = np.array(outputs[0]) + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmpdirname: + enc_dec_model.save_pretrained(tmpdirname) + FlaxVisionEncoderDecoderModel.from_pretrained(tmpdirname) + + after_outputs = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + out_1 = np.array(after_outputs[0]) + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + def check_encoder_decoder_model_output_attentions( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + # make the decoder inputs a different shape from the encoder inputs to harden the test + decoder_input_ids = decoder_input_ids[:, :-1] + decoder_attention_mask = decoder_attention_mask[:, :-1] + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} + enc_dec_model = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_attentions=True, + ) + + encoder_attentions = outputs_encoder_decoder["encoder_attentions"] + self.assertEqual(len(encoder_attentions), config.num_hidden_layers) + + self.assertEqual(encoder_attentions[0].shape[-3:-2], (config.num_attention_heads,)) + + decoder_attentions = outputs_encoder_decoder["decoder_attentions"] + num_decoder_layers = ( + decoder_config.num_decoder_layers + if hasattr(decoder_config, "num_decoder_layers") + else decoder_config.num_hidden_layers + ) + self.assertEqual(len(decoder_attentions), num_decoder_layers) + + self.assertEqual( + decoder_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), + ) + + cross_attentions = outputs_encoder_decoder["cross_attentions"] + self.assertEqual(len(cross_attentions), num_decoder_layers) + + cross_attention_input_seq_len = decoder_input_ids.shape[-1] * ( + 1 + (decoder_config.ngram if hasattr(decoder_config, "ngram") else 0) + ) + self.assertEqual( + cross_attentions[0].shape[-3:-1], + (decoder_config.num_attention_heads, cross_attention_input_seq_len), + ) + + def check_encoder_decoder_model_generate(self, pixel_values, config, decoder_config, **kwargs): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model} + enc_dec_model = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + + pad_token_id = enc_dec_model.config.decoder.pad_token_id + eos_token_id = enc_dec_model.config.decoder.eos_token_id + decoder_start_token_id = enc_dec_model.config.decoder.decoder_start_token_id + + # Copied from generation.utils (GPT2 doesn't have `pad_token_id`) + if pad_token_id is None and eos_token_id is not None: + pad_token_id = eos_token_id + if decoder_start_token_id is None: + decoder_start_token_id = enc_dec_model.config.decoder.bos_token_id + + # Bert does not have a bos token id, so use pad_token_id instead + # Copied from `test_modeling_encoder_decoder.py` + if decoder_start_token_id is None: + decoder_start_token_id = pad_token_id + + generated_output = enc_dec_model.generate( + pixel_values, + pad_token_id=pad_token_id, + eos_token_id=eos_token_id, + decoder_start_token_id=decoder_start_token_id, + ) + generated_sequences = generated_output.sequences + self.assertEqual(generated_sequences.shape, (pixel_values.shape[0],) + (decoder_config.max_length,)) + + def check_pt_flax_equivalence(self, pt_model, fx_model, inputs_dict): + pt_model.to(torch_device) + pt_model.eval() + + # prepare inputs + flax_inputs = inputs_dict + pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs).to_tuple() + + fx_outputs = fx_model(**inputs_dict).to_tuple() + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output in zip(fx_outputs, pt_outputs): + self.assert_almost_equals(fx_output, pt_output.numpy(), 1e-5) + + # PT -> Flax + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = FlaxVisionEncoderDecoderModel.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**inputs_dict).to_tuple() + self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output_loaded, pt_output in zip(fx_outputs_loaded, pt_outputs): + self.assert_almost_equals(fx_output_loaded, pt_output.numpy(), 1e-5) + + # Flax -> PT + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = VisionEncoderDecoderModel.from_pretrained(tmpdirname, from_flax=True) + + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs).to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output_loaded in zip(fx_outputs, pt_outputs_loaded): + self.assert_almost_equals(fx_output, pt_output_loaded.numpy(), 1e-5) + + def check_equivalence_pt_to_flax(self, config, decoder_config, inputs_dict): + encoder_decoder_config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + + pt_model = VisionEncoderDecoderModel(encoder_decoder_config) + fx_model = FlaxVisionEncoderDecoderModel(encoder_decoder_config) + + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + self.check_pt_flax_equivalence(pt_model, fx_model, inputs_dict) + + def check_equivalence_flax_to_pt(self, config, decoder_config, inputs_dict): + encoder_decoder_config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + + pt_model = VisionEncoderDecoderModel(encoder_decoder_config) + fx_model = FlaxVisionEncoderDecoderModel(encoder_decoder_config) + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + + self.check_pt_flax_equivalence(pt_model, fx_model, inputs_dict) + + def test_encoder_decoder_model_from_pretrained_configs(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained_configs(**config_inputs_dict) + + def test_encoder_decoder_model_from_pretrained(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**config_inputs_dict, return_dict=False) + + def test_encoder_decoder_model_from_pretrained_return_dict(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**config_inputs_dict, return_dict=True) + + def test_save_and_load_from_pretrained(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_save_and_load(**config_inputs_dict) + + def test_encoder_decoder_model_output_attentions(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_output_attentions(**config_inputs_dict) + + def test_encoder_decoder_model_generate(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_generate(**config_inputs_dict) + + def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): + diff = np.abs((a - b)).max() + self.assertLessEqual(diff, tol, f"Difference between torch and flax is {diff} (>= {tol}).") + + @is_pt_flax_cross_test + def test_pt_flax_equivalence(self): + config_inputs_dict = self.prepare_config_and_inputs() + config = config_inputs_dict.pop("config") + decoder_config = config_inputs_dict.pop("decoder_config") + + inputs_dict = config_inputs_dict + # `encoder_hidden_states` is not used in model call/forward + del inputs_dict["encoder_hidden_states"] + + # Avoid the case where a sequence has no place to attend (after combined with the causal attention mask) + batch_size = inputs_dict["decoder_attention_mask"].shape[0] + inputs_dict["decoder_attention_mask"] = np.concatenate( + [np.ones(shape=(batch_size, 1)), inputs_dict["decoder_attention_mask"][:, 1:]], axis=1 + ) + + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + decoder_config.use_cache = False + + self.assertTrue(decoder_config.cross_attention_hidden_size is None) + + # check without `enc_to_dec_proj` projection + self.assertTrue(config.hidden_size == decoder_config.hidden_size) + self.check_equivalence_pt_to_flax(config, decoder_config, inputs_dict) + self.check_equivalence_flax_to_pt(config, decoder_config, inputs_dict) + + # check `enc_to_dec_proj` work as expected + decoder_config.hidden_size = decoder_config.hidden_size * 2 + self.assertTrue(config.hidden_size != decoder_config.hidden_size) + self.check_equivalence_pt_to_flax(config, decoder_config, inputs_dict) + self.check_equivalence_flax_to_pt(config, decoder_config, inputs_dict) + + @slow + def test_real_model_save_load_from_pretrained(self): + model_2 = self.get_pretrained_model() + pixel_values = floats_tensor( + [ + 13, + model_2.config.encoder.num_channels, + model_2.config.encoder.image_size, + model_2.config.encoder.image_size, + ] + ) + decoder_input_ids = ids_tensor([13, 1], model_2.config.decoder.vocab_size) + + outputs = model_2( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + ) + out_2 = np.array(outputs[0]) + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmp_dirname: + model_2.save_pretrained(tmp_dirname) + model_1 = FlaxVisionEncoderDecoderModel.from_pretrained(tmp_dirname) + + after_outputs = model_1( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + ) + out_1 = np.array(after_outputs[0]) + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + +@require_flax +class FlaxViT2GPT2EncoderDecoderModelTest(FlaxEncoderDecoderMixin, unittest.TestCase): + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = FlaxViTModel(config) + decoder_model = FlaxGPT2LMHeadModel(decoder_config) + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + model_tester_encoder = FlaxViTModelTester(self, batch_size=13) + model_tester_decoder = FlaxGPT2ModelTester(self, batch_size=13) + encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() + decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder() + (config, pixel_values) = encoder_config_and_inputs + ( + decoder_config, + decoder_input_ids, + decoder_attention_mask, + encoder_hidden_states, + encoder_attention_mask, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + return { + "config": config, + "pixel_values": pixel_values, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "encoder_hidden_states": encoder_hidden_states, # This is not used in the tests. + } + + def get_pretrained_model(self): + return FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( + "google/vit-base-patch16-224-in21k", "gpt2" + ) + + +@require_flax +class FlaxVisionEncoderDecoderModelTest(unittest.TestCase): + def get_from_encoderdecoder_pretrained_model(self): + return FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( + "google/vit-base-patch16-224-in21k", "gpt2" + ) + + def _check_configuration_tie(self, model): + module = model.module.bind(model.params) + + assert id(module.decoder.config) == id(model.config.decoder) + assert id(module.encoder.config) == id(model.config.encoder) + + @slow + def test_configuration_tie(self): + model = self.get_from_encoderdecoder_pretrained_model() + self._check_configuration_tie(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_vision +@require_flax +class FlaxViT2GPT2ModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_coco_en(self): + loc = "ydshieh/vit-gpt2-coco-en" + + image_processor = ViTImageProcessor.from_pretrained(loc) + tokenizer = AutoTokenizer.from_pretrained(loc) + model = FlaxVisionEncoderDecoderModel.from_pretrained(loc) + + img = prepare_img() + pixel_values = image_processor(images=img, return_tensors="np").pixel_values + + decoder_input_ids = np.array([[model.config.decoder_start_token_id]]) + logits = model(pixel_values, decoder_input_ids)[0] + logits = np.array(logits) + + # verify the logits + expected_shape = (1, 1, model.config.decoder.vocab_size) + self.assertEqual(logits.shape, expected_shape) + + EXPECTED_LOGIT_SLICE = np.array( + [ + -38.705837, + -30.639936, + -31.41905, + -39.01204, + -38.38698, + -34.887215, + -33.29087, + -35.684475, + -38.50852, + -36.124676, + ] + ) + max_diff = np.amax(np.abs(logits[0, 0, :10] - EXPECTED_LOGIT_SLICE)) + self.assertLessEqual(max_diff, 1e-4) + + def generate_step(pixel_values): + outputs = model.generate(pixel_values, max_length=16, num_beams=4) + output_ids = outputs.sequences + preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + preds = [pred.strip() for pred in preds] + + return preds, outputs.scores + + preds, scores = generate_step(pixel_values) + + EXPECTED_SCORES = np.array([-0.59563464]) + scores = np.array(scores) + max_diff = np.amax(np.abs(scores - EXPECTED_SCORES)) + self.assertLessEqual(max_diff, 1e-4) + + # should produce + # ["a cat laying on top of a couch next to another cat"] + self.assertEqual(preds, ["a cat laying on top of a couch next to another cat"]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_tf_vision_encoder_decoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_tf_vision_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..db38e4a9899298497bb7e3d3c6b8c5dbde0a2a63 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_tf_vision_encoder_decoder.py @@ -0,0 +1,941 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. team. +# +# 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 TensorFlow VisionEncoderDecoder model. """ + + +from __future__ import annotations + +import copy +import os +import tempfile +import unittest + +import numpy as np + +from transformers import is_tf_available, is_torch_available, is_vision_available +from transformers.testing_utils import ( + is_pt_tf_cross_test, + require_tf, + require_torch, + require_vision, + slow, + torch_device, +) +from transformers.utils.generic import ModelOutput + +from ...test_modeling_tf_common import floats_tensor, ids_tensor +from ..gpt2.test_modeling_tf_gpt2 import TFGPT2ModelTester +from ..vit.test_modeling_tf_vit import TFViTModelTester + + +if is_tf_available(): + import tensorflow as tf + + from transformers import ( + AutoConfig, + AutoImageProcessor, + AutoTokenizer, + TFAutoModel, + TFAutoModelForCausalLM, + TFGPT2LMHeadModel, + TFVisionEncoderDecoderModel, + TFViTModel, + VisionEncoderDecoderConfig, + ) + from transformers.modeling_tf_outputs import TFBaseModelOutput + +if is_torch_available(): + import torch + + from transformers import GPT2LMHeadModel, VisionEncoderDecoderModel, ViTModel + +if is_vision_available(): + from PIL import Image + + from transformers import ViTImageProcessor + + +@require_tf +class TFVisionEncoderDecoderMixin: + def get_encoder_decoder_model(self, config, decoder_config): + raise NotImplementedError + + def prepare_config_and_inputs(self): + raise NotImplementedError + + def get_pretrained_model(self): + raise NotImplementedError + + def check_encoder_decoder_model_from_pretrained_configs( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_decoder_config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + self.assertTrue(encoder_decoder_config.decoder.is_decoder) + + enc_dec_model = TFVisionEncoderDecoderModel(encoder_decoder_config) + + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + kwargs=kwargs, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[0], pixel_values.shape[0]) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[-1], config.hidden_size) + + def check_encoder_decoder_model( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = TFVisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + self.assertTrue(enc_dec_model.config.decoder.is_decoder) + self.assertTrue(enc_dec_model.config.decoder.add_cross_attention) + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + kwargs=kwargs, + ) + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[0], pixel_values.shape[0]) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[-1], config.hidden_size) + + encoder_outputs = TFBaseModelOutput(last_hidden_state=encoder_hidden_states) + outputs_encoder_decoder = enc_dec_model( + pixel_values=None, + encoder_outputs=encoder_outputs, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + kwargs=kwargs, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[0], pixel_values.shape[0]) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[-1], config.hidden_size) + + def check_encoder_decoder_model_from_pretrained( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + return_dict, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model, "return_dict": return_dict} + enc_dec_model = TFVisionEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + return_dict=True, + kwargs=kwargs, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[0], pixel_values.shape[0]) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[-1], config.hidden_size) + + def check_save_and_load( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = TFVisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + + outputs = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + kwargs=kwargs, + ) + out_2 = np.array(outputs[0]) + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmpdirname: + enc_dec_model.save_pretrained(tmpdirname) + enc_dec_model = TFVisionEncoderDecoderModel.from_pretrained(tmpdirname) + + after_outputs = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + kwargs=kwargs, + ) + out_1 = np.array(after_outputs[0]) + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + def check_encoder_decoder_model_labels( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + labels, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = TFVisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + labels=labels, + kwargs=kwargs, + ) + + # Make sure `loss` exist + self.assertIn("loss", outputs_encoder_decoder) + + batch_size, seq_len = decoder_input_ids.shape + expected_shape = (batch_size, seq_len, decoder_config.vocab_size) + self.assertEqual(outputs_encoder_decoder["logits"].shape, expected_shape) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[0], pixel_values.shape[0]) + self.assertEqual(outputs_encoder_decoder["encoder_last_hidden_state"].shape[-1], config.hidden_size) + + def check_encoder_decoder_model_output_attentions( + self, + config, + pixel_values, + encoder_hidden_states, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + **kwargs, + ): + # make the decoder inputs a different shape from the encoder inputs to harden the test + decoder_input_ids = decoder_input_ids[:, :-1] + decoder_attention_mask = decoder_attention_mask[:, :-1] + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = TFVisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_attentions=True, + kwargs=kwargs, + ) + + encoder_attentions = outputs_encoder_decoder["encoder_attentions"] + self.assertEqual(len(encoder_attentions), config.num_hidden_layers) + + self.assertEqual(encoder_attentions[0].shape[-3:-2], (config.num_attention_heads,)) + + decoder_attentions = outputs_encoder_decoder["decoder_attentions"] + num_decoder_layers = ( + decoder_config.num_decoder_layers + if hasattr(decoder_config, "num_decoder_layers") + else decoder_config.num_hidden_layers + ) + self.assertEqual(len(decoder_attentions), num_decoder_layers) + + self.assertEqual( + decoder_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), + ) + + cross_attentions = outputs_encoder_decoder["cross_attentions"] + self.assertEqual(len(cross_attentions), num_decoder_layers) + + cross_attention_input_seq_len = decoder_input_ids.shape[-1] * ( + 1 + (decoder_config.ngram if hasattr(decoder_config, "ngram") else 0) + ) + self.assertEqual( + cross_attentions[0].shape[-3:-1], + (decoder_config.num_attention_heads, cross_attention_input_seq_len), + ) + + def check_encoder_decoder_model_generate(self, pixel_values, config, decoder_config, **kwargs): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = TFVisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + + # Generate until max length + if hasattr(enc_dec_model.config, "eos_token_id"): + enc_dec_model.config.eos_token_id = None + if hasattr(enc_dec_model.config, "decoder") and hasattr(enc_dec_model.config.decoder, "eos_token_id"): + enc_dec_model.config.decoder.eos_token_id = None + + # Bert does not have a bos token id, so use pad_token_id instead + generated_output = enc_dec_model.generate( + pixel_values, decoder_start_token_id=enc_dec_model.config.decoder.pad_token_id + ) + self.assertEqual( + tuple(generated_output.shape.as_list()), (pixel_values.shape[0],) + (decoder_config.max_length,) + ) + + def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None): + """Check the outputs from PyTorch and TensorFlow models are close enough. Checks are done in a recursive way. + + Args: + model_class: The class of the model that is currently testing. For example, `TFBertModel`, + TFBertForMaskedLM`, `TFBertForSequenceClassification`, etc. Mainly used for providing more informative + error messages. + name (`str`): The name of the output. For example, `output.hidden_states`, `output.attentions`, etc. + attributes (`Tuple[str]`): The names of the output's element if the output is a tuple/list with each element + being a named field in the output. + """ + + self.assertEqual(type(name), str) + if attributes is not None: + self.assertEqual(type(attributes), tuple, f"{name}: The argument `attributes` should be a `tuple`") + + # Allow `ModelOutput` (e.g. `CLIPOutput` has `text_model_output` and `vision_model_output`). + if isinstance(tf_outputs, ModelOutput): + self.assertTrue( + isinstance(pt_outputs, ModelOutput), + f"{name}: `pt_outputs` should an instance of `ModelOutput` when `tf_outputs` is", + ) + + tf_keys = [k for k, v in tf_outputs.items() if v is not None] + pt_keys = [k for k, v in pt_outputs.items() if v is not None] + + self.assertEqual(tf_keys, pt_keys, f"{name}: Output keys differ between TF and PyTorch") + + # convert to the case of `tuple` + # appending each key to the current (string) `names` + attributes = tuple([f"{name}.{k}" for k in tf_keys]) + self.check_pt_tf_outputs( + tf_outputs.to_tuple(), pt_outputs.to_tuple(), model_class, tol=tol, name=name, attributes=attributes + ) + + # Allow `list` (e.g. `TransfoXLModelOutput.mems` is a list of tensors.) + elif type(tf_outputs) in [tuple, list]: + self.assertEqual(type(tf_outputs), type(pt_outputs), f"{name}: Output types differ between TF and PyTorch") + self.assertEqual(len(tf_outputs), len(pt_outputs), f"{name}: Output lengths differ between TF and PyTorch") + + if attributes is not None: + # case 1: each output has assigned name (e.g. a tuple form of a `ModelOutput`) + self.assertEqual( + len(attributes), + len(tf_outputs), + f"{name}: The tuple `names` should have the same length as `tf_outputs`", + ) + else: + # case 2: each output has no assigned name (e.g. hidden states of each layer) -> add an index to `names` + attributes = tuple([f"{name}_{idx}" for idx in range(len(tf_outputs))]) + + for tf_output, pt_output, attr in zip(tf_outputs, pt_outputs, attributes): + self.check_pt_tf_outputs(tf_output, pt_output, model_class, tol=tol, name=attr) + + elif isinstance(tf_outputs, tf.Tensor): + self.assertTrue( + isinstance(pt_outputs, torch.Tensor), f"{name}: `pt_outputs` should a tensor when `tf_outputs` is" + ) + + tf_outputs = tf_outputs.numpy() + pt_outputs = pt_outputs.detach().to("cpu").numpy() + + self.assertEqual( + tf_outputs.shape, pt_outputs.shape, f"{name}: Output shapes differ between TF and PyTorch" + ) + + # deal with NumPy's scalars to make replacing nan values by 0 work. + if np.isscalar(tf_outputs): + tf_outputs = np.array([tf_outputs]) + pt_outputs = np.array([pt_outputs]) + + tf_nans = np.isnan(tf_outputs) + pt_nans = np.isnan(pt_outputs) + + pt_outputs[tf_nans] = 0 + tf_outputs[tf_nans] = 0 + pt_outputs[pt_nans] = 0 + tf_outputs[pt_nans] = 0 + + max_diff = np.amax(np.abs(tf_outputs - pt_outputs)) + self.assertLessEqual(max_diff, tol, f"{name}: Difference between torch and tf is {max_diff} (>= {tol}).") + else: + raise ValueError( + "`tf_outputs` should be an instance of `tf.Tensor`, a `tuple`, or an instance of `tf.Tensor`. Got" + f" {type(tf_outputs)} instead." + ) + + def prepare_pt_inputs_from_tf_inputs(self, tf_inputs_dict): + pt_inputs_dict = {} + for name, key in tf_inputs_dict.items(): + if isinstance(key, bool): + pt_inputs_dict[name] = key + elif name == "input_values": + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.float32) + elif name == "pixel_values": + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.float32) + elif name == "input_features": + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.float32) + # other general float inputs + elif tf_inputs_dict[name].dtype.is_floating: + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.float32) + else: + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.long) + + return pt_inputs_dict + + def check_pt_tf_models(self, tf_model, pt_model, tf_inputs_dict): + pt_inputs_dict = self.prepare_pt_inputs_from_tf_inputs(tf_inputs_dict) + + # send pytorch inputs to the correct device + pt_inputs_dict = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs_dict.items() + } + + # send pytorch model to the correct device + pt_model.to(torch_device) + + # Check predictions on first output (logits/hidden-states) are close enough given low-level computational differences + pt_model.eval() + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs_dict) + tf_outputs = tf_model(tf_inputs_dict) + + # tf models returned loss is usually a tensor rather than a scalar. + # (see `hf_compute_loss`: it uses `tf.keras.losses.Reduction.NONE`) + # Change it here to a scalar to match PyTorch models' loss + tf_loss = getattr(tf_outputs, "loss", None) + if tf_loss is not None: + tf_outputs.loss = tf.math.reduce_mean(tf_loss) + + self.check_pt_tf_outputs(tf_outputs, pt_outputs, type(tf_model)) + + def check_pt_tf_equivalence(self, tf_model, pt_model, tf_inputs_dict): + """Wrap `check_pt_tf_models` to further check PT -> TF again""" + + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + + # PT -> TF + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + tf_model = TFVisionEncoderDecoderModel.from_pretrained(tmpdirname) + + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + + def check_pt_to_tf_equivalence(self, config, decoder_config, tf_inputs_dict): + encoder_decoder_config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + # Output all for aggressive testing + encoder_decoder_config.output_hidden_states = True + # All models tested in this file have attentions + encoder_decoder_config.output_attentions = True + + pt_model = VisionEncoderDecoderModel(encoder_decoder_config) + + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + tf_model = TFVisionEncoderDecoderModel.from_pretrained(tmpdirname) + + self.check_pt_tf_equivalence(tf_model, pt_model, tf_inputs_dict) + + def check_tf_to_pt_equivalence(self, config, decoder_config, tf_inputs_dict): + encoder_decoder_config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + # Output all for aggressive testing + encoder_decoder_config.output_hidden_states = True + # TODO: A generalizable way to determine this attribute + encoder_decoder_config.output_attentions = True + + tf_model = TFVisionEncoderDecoderModel(encoder_decoder_config) + # Make sure model is built before saving + tf_model(**tf_inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + tf_model.save_pretrained(tmpdirname, safe_serialization=False) + pt_model = VisionEncoderDecoderModel.from_pretrained(tmpdirname, from_tf=True) + + self.check_pt_tf_equivalence(tf_model, pt_model, tf_inputs_dict) + + def test_encoder_decoder_model(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model(**config_inputs_dict) + + def test_encoder_decoder_model_from_pretrained_configs(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained_configs(**config_inputs_dict) + + def test_encoder_decoder_model_from_pretrained(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**config_inputs_dict, return_dict=False) + + def test_encoder_decoder_model_from_pretrained_return_dict(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**config_inputs_dict, return_dict=True) + + def test_save_and_load_from_pretrained(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_save_and_load(**config_inputs_dict) + + def test_encoder_decoder_model_labels(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_labels(**config_inputs_dict) + + def test_encoder_decoder_model_output_attentions(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_output_attentions(**config_inputs_dict) + + def test_encoder_decoder_model_generate(self): + config_inputs_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_generate(**config_inputs_dict) + + def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): + diff = np.abs((a - b)).max() + self.assertLessEqual(diff, tol, f"Difference between torch and tf is {diff} (>= {tol}).") + + @is_pt_tf_cross_test + def test_pt_tf_model_equivalence(self): + config_inputs_dict = self.prepare_config_and_inputs() + labels = config_inputs_dict.pop("decoder_token_labels") + + # Keep only common arguments + arg_names = [ + "config", + "pixel_values", + "decoder_config", + "decoder_input_ids", + "decoder_attention_mask", + "encoder_hidden_states", + ] + config_inputs_dict = {k: v for k, v in config_inputs_dict.items() if k in arg_names} + + config = config_inputs_dict.pop("config") + decoder_config = config_inputs_dict.pop("decoder_config") + + # Output all for aggressive testing + config.output_hidden_states = True + decoder_config.output_hidden_states = True + # All models tested in this file have attentions + config.output_attentions = True + decoder_config.output_attentions = True + + tf_inputs_dict = config_inputs_dict + # `encoder_hidden_states` is not used in model call/forward + del tf_inputs_dict["encoder_hidden_states"] + + # Make sure no sequence has all zeros as attention mask, otherwise some tests fail due to the inconsistency + # of the usage `1e-4`, `1e-9`, `1e-30`, `-inf`. + for k in ["decoder_attention_mask"]: + attention_mask = tf_inputs_dict[k] + + # Make sure no all 0s attention masks - to avoid failure at this moment. + # Put `1` at the beginning of sequences to make it still work when combining causal attention masks. + # TODO: remove this line once a fix regarding large negative values for attention mask is done. + attention_mask = tf.concat( + [tf.ones_like(attention_mask[:, :1], dtype=attention_mask.dtype), attention_mask[:, 1:]], axis=-1 + ) + tf_inputs_dict[k] = attention_mask + + tf_inputs_dict_with_labels = copy.copy(tf_inputs_dict) + tf_inputs_dict_with_labels["labels"] = labels + + self.assertTrue(decoder_config.cross_attention_hidden_size is None) + + # Original test: check without `labels` and without `enc_to_dec_proj` projection + self.assertTrue(config.hidden_size == decoder_config.hidden_size) + self.check_pt_to_tf_equivalence(config, decoder_config, tf_inputs_dict) + self.check_tf_to_pt_equivalence(config, decoder_config, tf_inputs_dict) + + # check with `labels` + self.check_pt_to_tf_equivalence(config, decoder_config, tf_inputs_dict_with_labels) + self.check_tf_to_pt_equivalence(config, decoder_config, tf_inputs_dict_with_labels) + + # check `enc_to_dec_proj` work as expected + decoder_config.hidden_size = decoder_config.hidden_size * 2 + self.assertTrue(config.hidden_size != decoder_config.hidden_size) + self.check_pt_to_tf_equivalence(config, decoder_config, tf_inputs_dict) + self.check_tf_to_pt_equivalence(config, decoder_config, tf_inputs_dict) + + @slow + def test_real_model_save_load_from_pretrained(self): + model_2 = self.get_pretrained_model() + pixel_values = floats_tensor( + [ + 13, + model_2.config.encoder.num_channels, + model_2.config.encoder.image_size, + model_2.config.encoder.image_size, + ] + ) + decoder_input_ids = ids_tensor([13, 1], model_2.config.decoder.vocab_size) + + outputs = model_2( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + ) + out_2 = np.array(outputs[0]) + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmp_dirname: + model_2.save_pretrained(tmp_dirname) + model_1 = TFVisionEncoderDecoderModel.from_pretrained(tmp_dirname) + + after_outputs = model_1(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids) + out_1 = np.array(after_outputs[0]) + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + +@require_tf +class TFViT2GPT2EncoderDecoderModelTest(TFVisionEncoderDecoderMixin, unittest.TestCase): + def get_pretrained_model(self): + return TFVisionEncoderDecoderModel.from_encoder_decoder_pretrained("google/vit-base-patch16-224-in21k", "gpt2") + + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = TFViTModel(config, name="encoder") + decoder_model = TFGPT2LMHeadModel(decoder_config, name="decoder") + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + model_tester_encoder = TFViTModelTester(self, batch_size=13) + model_tester_decoder = TFGPT2ModelTester(self) + encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() + decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs_for_decoder() + (config, pixel_values, labels) = encoder_config_and_inputs + ( + decoder_config, + decoder_input_ids, + decoder_attention_mask, + decoder_head_mask, + decoder_token_type_ids, + decoder_sequence_labels, + decoder_token_labels, + decoder_choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + # disable cache for now + decoder_config.use_cache = False + return { + "config": config, + "pixel_values": pixel_values, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "decoder_token_labels": decoder_token_labels, + "encoder_hidden_states": encoder_hidden_states, # This is not used in the tests. + "labels": decoder_token_labels, + } + + +@require_tf +class TFVisionEncoderDecoderModelTest(unittest.TestCase): + def get_from_encoderdecoder_pretrained_model(self): + return TFVisionEncoderDecoderModel.from_encoder_decoder_pretrained("google/vit-base-patch16-224-in21k", "gpt2") + + def get_decoder_config(self): + config = AutoConfig.from_pretrained("gpt2") + config.is_decoder = True + config.add_cross_attention = True + return config + + def get_encoderdecoder_model(self): + return TFVisionEncoderDecoderModel.from_pretrained("ydshieh/vit-gpt2-coco-en") + + def get_encoder_decoder_models(self): + encoder_model = TFViTModel.from_pretrained("google/vit-base-patch16-224-in21k", name="encoder") + decoder_model = TFGPT2LMHeadModel.from_pretrained("gpt2", config=self.get_decoder_config(), name="decoder") + return {"encoder": encoder_model, "decoder": decoder_model} + + def _check_configuration_tie(self, model): + assert id(model.decoder.config) == id(model.config.decoder) + assert id(model.encoder.config) == id(model.config.encoder) + + @slow + def test_configuration_tie(self): + model = self.get_from_encoderdecoder_pretrained_model() + self._check_configuration_tie(model) + + model = TFVisionEncoderDecoderModel(**self.get_encoder_decoder_models()) + self._check_configuration_tie(model) + + model = self.get_encoderdecoder_model() + self._check_configuration_tie(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_tf +class TFVisionEncoderDecoderModelSaveLoadTests(unittest.TestCase): + def get_encoder_decoder_config(self): + encoder_config = AutoConfig.from_pretrained("google/vit-base-patch16-224-in21k") + decoder_config = AutoConfig.from_pretrained("gpt2", is_decoder=True, add_cross_attention=True) + return VisionEncoderDecoderConfig.from_encoder_decoder_configs(encoder_config, decoder_config) + + def get_encoder_decoder_config_small(self): + encoder_config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-vit") + decoder_config = AutoConfig.from_pretrained( + "hf-internal-testing/tiny-random-gpt2", is_decoder=True, add_cross_attention=True + ) + return VisionEncoderDecoderConfig.from_encoder_decoder_configs(encoder_config, decoder_config) + + def test_encoder_decoder_save_load_from_encoder_decoder(self): + config = self.get_encoder_decoder_config_small() + + # create two random ViT/GPT2 models for vit-gpt2 & initialize weights (+cross_attention weights) + encoder = TFViTModel(config.encoder) + encoder.build() + decoder = TFGPT2LMHeadModel(config.decoder) + decoder.build() + + encoder_decoder_orig = TFVisionEncoderDecoderModel(encoder=encoder, decoder=decoder) + + pixel_values = floats_tensor( + [ + 13, + encoder.config.num_channels, + encoder.config.image_size, + encoder.config.image_size, + ] + ) + decoder_input_ids = ids_tensor([13, 1], decoder.config.vocab_size) + + logits_orig = encoder_decoder_orig(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids).logits + + with tempfile.TemporaryDirectory() as tmp_dirname: + encoder_path = os.path.join(tmp_dirname, "encoder") + decoder_path = os.path.join(tmp_dirname, "decoder") + + encoder.save_pretrained(encoder_path) + decoder.save_pretrained(decoder_path) + + encoder_decoder = TFVisionEncoderDecoderModel.from_encoder_decoder_pretrained(encoder_path, decoder_path) + + logits_1 = encoder_decoder(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids).logits + + self.assertTrue(logits_orig.numpy().sum() - logits_1.numpy().sum() < 1e-3) + + max_diff = np.max(np.abs(logits_1.numpy() - logits_orig.numpy())) + self.assertAlmostEqual(max_diff, 0.0, places=4) + + with tempfile.TemporaryDirectory() as tmp_dirname: + encoder_decoder.save_pretrained(tmp_dirname) + encoder_decoder = TFVisionEncoderDecoderModel.from_pretrained(tmp_dirname) + + logits_2 = encoder_decoder(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids).logits + + max_diff = np.max(np.abs(logits_2.numpy() - logits_orig.numpy())) + self.assertAlmostEqual(max_diff, 0.0, places=4) + + @require_torch + @is_pt_tf_cross_test + def test_encoder_decoder_save_load_from_encoder_decoder_from_pt(self): + config = self.get_encoder_decoder_config_small() + + # create two random ViT/GPT2 models for vit-gpt2 & initialize weights (+cross_attention weights) + encoder_pt = ViTModel(config.encoder).to(torch_device).eval() + decoder_pt = GPT2LMHeadModel(config.decoder).to(torch_device).eval() + + encoder_decoder_pt = VisionEncoderDecoderModel(encoder=encoder_pt, decoder=decoder_pt).to(torch_device).eval() + + pixel_values = floats_tensor( + [ + 13, + encoder_pt.config.num_channels, + encoder_pt.config.image_size, + encoder_pt.config.image_size, + ] + ) + decoder_input_ids = ids_tensor([13, 1], decoder_pt.config.vocab_size) + + pt_pixel_values = torch.tensor(pixel_values.numpy(), device=torch_device, dtype=torch.float) + pt_decoder_input_ids = torch.tensor(decoder_input_ids.numpy(), device=torch_device, dtype=torch.long) + + logits_pt = encoder_decoder_pt(pixel_values=pt_pixel_values, decoder_input_ids=pt_decoder_input_ids).logits + + # PyTorch => TensorFlow + with tempfile.TemporaryDirectory() as tmp_dirname_1, tempfile.TemporaryDirectory() as tmp_dirname_2: + encoder_decoder_pt.encoder.save_pretrained(tmp_dirname_1) + encoder_decoder_pt.decoder.save_pretrained(tmp_dirname_2) + encoder_decoder_tf = TFVisionEncoderDecoderModel.from_encoder_decoder_pretrained( + tmp_dirname_1, tmp_dirname_2 + ) + + logits_tf = encoder_decoder_tf(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids).logits + + max_diff = np.max(np.abs(logits_pt.detach().cpu().numpy() - logits_tf.numpy())) + self.assertAlmostEqual(max_diff, 0.0, places=3) + + # Make sure `from_pretrained` following `save_pretrained` work and give the same result + # (See https://github.com/huggingface/transformers/pull/14016) + with tempfile.TemporaryDirectory() as tmp_dirname: + encoder_decoder_tf.save_pretrained(tmp_dirname, safe_serialization=False) + encoder_decoder_tf = TFVisionEncoderDecoderModel.from_pretrained(tmp_dirname) + + logits_tf_2 = encoder_decoder_tf(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids).logits + + max_diff = np.max(np.abs(logits_tf_2.numpy() - logits_tf.numpy())) + self.assertAlmostEqual(max_diff, 0.0, places=3) + + @require_vision + @slow + def test_encoder_decoder_from_pretrained(self): + load_weight_prefix = TFVisionEncoderDecoderModel.load_weight_prefix + + config = self.get_encoder_decoder_config() + image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k") + decoder_tokenizer = AutoTokenizer.from_pretrained("gpt2") + + img = prepare_img() + pixel_values = image_processor(images=img, return_tensors="tf").pixel_values + decoder_input_ids = decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids + + with tempfile.TemporaryDirectory() as tmp_dirname: + # Since most of HF's models don't have pretrained cross-attention layers, they are randomly + # initialized even if we create models using `from_pretrained` method. + # For the tests, the decoder need to be a model with pretrained cross-attention layers. + # So we create pretrained models (without `load_weight_prefix`), save them, and later, + # we load them using `from_pretrained`. + # (we don't need to do this for encoder, but let's make the code more similar between encoder/decoder) + encoder = TFAutoModel.from_pretrained("google/vit-base-patch16-224-in21k", name="encoder") + # It's necessary to specify `add_cross_attention=True` here. + decoder = TFAutoModelForCausalLM.from_pretrained( + "gpt2", is_decoder=True, add_cross_attention=True, name="decoder" + ) + pretrained_encoder_dir = os.path.join(tmp_dirname, "pretrained_encoder") + pretrained_decoder_dir = os.path.join(tmp_dirname, "pretrained_decoder") + encoder.save_pretrained(pretrained_encoder_dir) + decoder.save_pretrained(pretrained_decoder_dir) + del encoder + del decoder + + enc_dec_model = TFVisionEncoderDecoderModel.from_encoder_decoder_pretrained( + pretrained_encoder_dir, + pretrained_decoder_dir, + ) + # check that the from pretrained methods work + enc_dec_model.save_pretrained(tmp_dirname) + enc_dec_model = TFVisionEncoderDecoderModel.from_pretrained(tmp_dirname) + + output = enc_dec_model(pixel_values, decoder_input_ids=decoder_input_ids, labels=decoder_input_ids) + + loss_pretrained = output.loss + del enc_dec_model + + # Create the model using `__init__` with loaded ``pretrained`` encoder / decoder + encoder = TFAutoModel.from_pretrained( + pretrained_encoder_dir, load_weight_prefix=load_weight_prefix, name="encoder" + ) + decoder = TFAutoModelForCausalLM.from_pretrained( + pretrained_decoder_dir, load_weight_prefix=load_weight_prefix, name="decoder" + ) + enc_dec_model = TFVisionEncoderDecoderModel(config=config, encoder=encoder, decoder=decoder) + + output = enc_dec_model(pixel_values, decoder_input_ids=decoder_input_ids, labels=decoder_input_ids) + + loss_init = output.loss + + max_diff = np.max(np.abs(loss_pretrained - loss_init)) + expected_diff = 0.0 + + self.assertAlmostEqual(max_diff, expected_diff, places=4) + + +@require_vision +@require_tf +class TFViT2GPT2ModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_coco_en(self): + loc = "ydshieh/vit-gpt2-coco-en" + + image_processor = ViTImageProcessor.from_pretrained(loc) + tokenizer = AutoTokenizer.from_pretrained(loc) + model = TFVisionEncoderDecoderModel.from_pretrained(loc) + + # We will verify our results on an image of cute cats + img = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + pixel_values = image_processor(images=img, return_tensors="tf").pixel_values + + decoder_input_ids = tf.constant([[model.config.decoder_start_token_id]]) + + logits = model(pixel_values, decoder_input_ids)[0].numpy() + + # verify the logits + expected_shape = (1, 1, model.config.decoder.vocab_size) + self.assertEqual(logits.shape, expected_shape) + + EXPECTED_LOGIT_SLICE = np.array( + [ + -38.705807, + -30.639929, + -31.41903, + -39.012012, + -38.38696, + -34.887207, + -33.290855, + -35.68447, + -38.508484, + -36.124645, + ] + ) + max_diff = np.amax(np.abs(logits[0, 0, :10] - EXPECTED_LOGIT_SLICE)) + self.assertLessEqual(max_diff, 1e-4) + + def generate_step(pixel_values): + outputs = model.generate(pixel_values, max_length=16, num_beams=4, return_dict_in_generate=True) + output_ids = outputs.sequences + preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + preds = [pred.strip() for pred in preds] + + return preds + + preds = generate_step(pixel_values) + + # should produce + # ["a cat laying on top of a couch next to another cat"] + self.assertEqual(preds, ["a cat laying on top of a couch next to another cat"]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..71b1ff710679449406aabb72737e4e8d2d8828ca --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py @@ -0,0 +1,1077 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. team. +# +# 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 re +import tempfile +import unittest + +from datasets import load_dataset +from huggingface_hub import hf_hub_download +from packaging import version + +from transformers import DonutProcessor, NougatProcessor, TrOCRProcessor +from transformers.testing_utils import ( + require_levenshtein, + require_nltk, + require_sentencepiece, + require_torch, + require_vision, + slow, + to_2tuple, + torch_device, +) +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_modeling_common import floats_tensor, ids_tensor, random_attention_mask +from ..bart.test_modeling_bart import BartModelTester +from ..bert.test_modeling_bert import BertModelTester +from ..deit.test_modeling_deit import DeiTModelTester +from ..swin.test_modeling_swin import SwinModelTester +from ..trocr.test_modeling_trocr import TrOCRStandaloneDecoderModelTester +from ..vit.test_modeling_vit import ViTModelTester + + +if is_torch_available(): + import numpy as np + import torch + + from transformers import ( + AutoTokenizer, + BartForCausalLM, + BertLMHeadModel, + DeiTModel, + SwinModel, + TrOCRForCausalLM, + VisionEncoderDecoderConfig, + VisionEncoderDecoderModel, + ViTModel, + ) + from transformers.modeling_outputs import BaseModelOutput + + +if is_vision_available(): + import PIL + from PIL import Image + + from transformers import ViTImageProcessor + + +@require_torch +class EncoderDecoderMixin: + def get_encoder_decoder_model(self, config, decoder_config): + pass + + def prepare_config_and_inputs(self): + pass + + def get_pretrained_model_and_inputs(self): + pass + + def check_encoder_decoder_model_from_pretrained_configs( + self, config, decoder_config, decoder_input_ids, decoder_attention_mask, pixel_values=None, **kwargs + ): + encoder_decoder_config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) + self.assertTrue(encoder_decoder_config.decoder.is_decoder) + + enc_dec_model = VisionEncoderDecoderModel(encoder_decoder_config) + enc_dec_model.to(torch_device) + enc_dec_model.eval() + + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_encoder_decoder_model( + self, config, decoder_config, decoder_input_ids, decoder_attention_mask, pixel_values=None, **kwargs + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + self.assertTrue(enc_dec_model.config.decoder.is_decoder) + self.assertTrue(enc_dec_model.config.decoder.add_cross_attention) + self.assertTrue(enc_dec_model.config.is_encoder_decoder) + enc_dec_model.to(torch_device) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_hidden_states=True, + ) + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + encoder_outputs = BaseModelOutput(last_hidden_state=outputs_encoder_decoder.encoder_hidden_states[-1]) + outputs_encoder_decoder = enc_dec_model( + encoder_outputs=encoder_outputs, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_encoder_decoder_model_from_pretrained( + self, + config, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + return_dict, + pixel_values=None, + **kwargs, + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model, "return_dict": return_dict} + enc_dec_model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) + enc_dec_model.to(torch_device) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_hidden_states=True, + return_dict=True, + ) + + self.assertEqual( + outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) + ) + + def check_save_and_load( + self, config, decoder_config, decoder_input_ids, decoder_attention_mask, pixel_values=None, **kwargs + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + enc_dec_model.eval() + with torch.no_grad(): + outputs = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + out_2 = outputs[0].cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmpdirname: + enc_dec_model.save_pretrained(tmpdirname) + enc_dec_model = VisionEncoderDecoderModel.from_pretrained(tmpdirname) + enc_dec_model.to(torch_device) + + after_outputs = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + out_1 = after_outputs[0].cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + def check_save_and_load_encoder_decoder_model( + self, config, decoder_config, decoder_input_ids, decoder_attention_mask, pixel_values=None, **kwargs + ): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + enc_dec_model.eval() + with torch.no_grad(): + outputs = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + out_2 = outputs[0].cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as encoder_tmp_dirname, tempfile.TemporaryDirectory() as decoder_tmp_dirname: + enc_dec_model.encoder.save_pretrained(encoder_tmp_dirname) + enc_dec_model.decoder.save_pretrained(decoder_tmp_dirname) + VisionEncoderDecoderModel.from_encoder_decoder_pretrained( + encoder_pretrained_model_name_or_path=encoder_tmp_dirname, + decoder_pretrained_model_name_or_path=decoder_tmp_dirname, + ) + + after_outputs = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + ) + out_1 = after_outputs[0].cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + def check_encoder_decoder_model_output_attentions( + self, + config, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + labels=None, + pixel_values=None, + **kwargs, + ): + # make the decoder inputs a different shape from the encoder inputs to harden the test + decoder_input_ids = decoder_input_ids[:, :-1] + decoder_attention_mask = decoder_attention_mask[:, :-1] + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_attentions=True, + ) + + encoder_attentions = outputs_encoder_decoder["encoder_attentions"] + self.assertEqual(len(encoder_attentions), config.num_hidden_layers) + + # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) + image_size = to_2tuple(encoder_model.config.image_size) + patch_size = to_2tuple(encoder_model.config.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + seq_len = num_patches + 1 + self.assertEqual(encoder_attentions[0].shape[-3:], (config.num_attention_heads, seq_len, seq_len)) + + decoder_attentions = outputs_encoder_decoder["decoder_attentions"] + num_decoder_layers = ( + decoder_config.num_decoder_layers + if hasattr(decoder_config, "num_decoder_layers") + else decoder_config.num_hidden_layers + ) + self.assertEqual(len(decoder_attentions), num_decoder_layers) + + self.assertEqual( + decoder_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), + ) + + cross_attentions = outputs_encoder_decoder["cross_attentions"] + self.assertEqual(len(cross_attentions), num_decoder_layers) + + cross_attention_input_seq_len = decoder_input_ids.shape[-1] + self.assertEqual( + cross_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, cross_attention_input_seq_len, seq_len), + ) + + def check_encoder_decoder_model_generate(self, config, decoder_config, pixel_values=None, **kwargs): + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + + # Generate until max length + if hasattr(enc_dec_model.config, "eos_token_id"): + enc_dec_model.config.eos_token_id = None + if hasattr(enc_dec_model.config, "decoder") and hasattr(enc_dec_model.config.decoder, "eos_token_id"): + enc_dec_model.config.decoder.eos_token_id = None + enc_dec_model.to(torch_device) + + inputs = pixel_values + + # Bert does not have a bos token id, so use pad_token_id instead + generated_output = enc_dec_model.generate( + inputs, decoder_start_token_id=enc_dec_model.config.decoder.pad_token_id + ) + self.assertEqual(generated_output.shape, (inputs.shape[0],) + (decoder_config.max_length,)) + + def test_encoder_decoder_model(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model(**input_ids_dict) + + def test_encoder_decoder_model_from_pretrained_configs(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained_configs(**input_ids_dict) + + def test_encoder_decoder_model_from_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=False) + + def test_encoder_decoder_model_from_pretrained_return_dict(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=True) + + def test_save_and_load_from_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_save_and_load(**input_ids_dict) + + def test_save_and_load_from_encoder_decoder_pretrained(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_save_and_load_encoder_decoder_model(**input_ids_dict) + + def test_encoder_decoder_model_output_attentions(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_output_attentions(**input_ids_dict) + + def test_encoder_decoder_model_generate(self): + input_ids_dict = self.prepare_config_and_inputs() + self.check_encoder_decoder_model_generate(**input_ids_dict) + + def test_training_gradient_checkpointing(self): + inputs_dict = self.prepare_config_and_inputs() + encoder_model, decoder_model = self.get_encoder_decoder_model( + inputs_dict["config"], inputs_dict["decoder_config"] + ) + + model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + model.to(torch_device) + model.train() + model.gradient_checkpointing_enable() + model.config.decoder_start_token_id = 0 + model.config.pad_token_id = 0 + + model_inputs = { + "pixel_values": inputs_dict["pixel_values"], + "labels": inputs_dict["labels"], + "decoder_input_ids": inputs_dict["decoder_input_ids"], + } + + loss = model(**model_inputs).loss + loss.backward() + + @slow + def test_real_model_save_load_from_pretrained(self): + model_2, inputs = self.get_pretrained_model_and_inputs() + model_2.to(torch_device) + + with torch.no_grad(): + outputs = model_2(**inputs) + out_2 = outputs[0].cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmp_dirname: + model_2.save_pretrained(tmp_dirname) + model_1 = VisionEncoderDecoderModel.from_pretrained(tmp_dirname) + model_1.to(torch_device) + + after_outputs = model_1(**inputs) + out_1 = after_outputs[0].cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + +@require_torch +class DeiT2RobertaModelTest(EncoderDecoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained( + "hf-internal-testing/tiny-random-deit", "hf-internal-testing/tiny-random-roberta" + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.encoder.config.num_channels, + model.encoder.config.image_size, + model.encoder.config.image_size, + ] + ) + # for DEiT, the sequence length is equal to the number of patches + 2 (for the [CLS] and distillation tokens) + decoder_input_ids = ids_tensor([batch_size, 4], model.decoder.config.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs = { + "pixel_values": pixel_values, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + return model, inputs + + def check_encoder_decoder_model_output_attentions( + self, + config, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + labels=None, + pixel_values=None, + **kwargs, + ): + # make the decoder inputs a different shape from the encoder inputs to harden the test + decoder_input_ids = decoder_input_ids[:, :-1] + decoder_attention_mask = decoder_attention_mask[:, :-1] + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_attentions=True, + ) + + encoder_attentions = outputs_encoder_decoder["encoder_attentions"] + self.assertEqual(len(encoder_attentions), config.num_hidden_layers) + + # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) + image_size = to_2tuple(encoder_model.config.image_size) + patch_size = to_2tuple(encoder_model.config.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + seq_len = num_patches + 2 + self.assertEqual(encoder_attentions[0].shape[-3:], (config.num_attention_heads, seq_len, seq_len)) + + decoder_attentions = outputs_encoder_decoder["decoder_attentions"] + num_decoder_layers = ( + decoder_config.num_decoder_layers + if hasattr(decoder_config, "num_decoder_layers") + else decoder_config.num_hidden_layers + ) + self.assertEqual(len(decoder_attentions), num_decoder_layers) + + self.assertEqual( + decoder_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), + ) + + cross_attentions = outputs_encoder_decoder["cross_attentions"] + self.assertEqual(len(cross_attentions), num_decoder_layers) + + cross_attention_input_seq_len = decoder_input_ids.shape[-1] + self.assertEqual( + cross_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, cross_attention_input_seq_len, seq_len), + ) + + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = DeiTModel(config).eval() + decoder_model = BertLMHeadModel(decoder_config).eval() + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + bert_model_tester = BertModelTester(self) + deit_model_tester = DeiTModelTester(self) + encoder_config_and_inputs = deit_model_tester.prepare_config_and_inputs() + decoder_config_and_inputs = bert_model_tester.prepare_config_and_inputs_for_decoder() + config, pixel_values, _ = encoder_config_and_inputs + ( + decoder_config, + decoder_input_ids, + decoder_token_type_ids, + decoder_input_mask, + decoder_sequence_labels, + decoder_token_labels, + decoder_choice_labels, + encoder_attention_mask, + _, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + return { + "config": config, + "pixel_values": pixel_values, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_token_type_ids": decoder_token_type_ids, + "decoder_attention_mask": decoder_input_mask, + "decoder_sequence_labels": decoder_sequence_labels, + "decoder_token_labels": decoder_token_labels, + "decoder_choice_labels": decoder_choice_labels, + "labels": decoder_token_labels, + } + + +@require_torch +class ViT2BertModelTest(EncoderDecoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained( + "hf-internal-testing/tiny-random-vit", "hf-internal-testing/tiny-bert" + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.encoder.config.num_channels, + model.encoder.config.image_size, + model.encoder.config.image_size, + ] + ) + # for ViT, the sequence length is equal to the number of patches + 1 (for the [CLS] token) + decoder_input_ids = ids_tensor([batch_size, 4], model.decoder.config.vocab_size) + decoder_attention_mask = random_attention_mask([batch_size, 4]) + inputs = { + "pixel_values": pixel_values, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + return model, inputs + + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = ViTModel(config).eval() + decoder_model = BertLMHeadModel(decoder_config).eval() + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + vit_model_tester = ViTModelTester(self) + bert_model_tester = BertModelTester(self) + encoder_config_and_inputs = vit_model_tester.prepare_config_and_inputs() + decoder_config_and_inputs = bert_model_tester.prepare_config_and_inputs_for_decoder() + + config, pixel_values, _ = encoder_config_and_inputs + + ( + decoder_config, + decoder_input_ids, + decoder_token_type_ids, + decoder_input_mask, + decoder_sequence_labels, + decoder_token_labels, + decoder_choice_labels, + encoder_attention_mask, + _, + ) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + return { + "config": config, + "pixel_values": pixel_values, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_token_type_ids": decoder_token_type_ids, + "decoder_attention_mask": decoder_input_mask, + "decoder_sequence_labels": decoder_sequence_labels, + "decoder_token_labels": decoder_token_labels, + "decoder_choice_labels": decoder_choice_labels, + "labels": decoder_token_labels, + } + + +@require_torch +class Swin2BartModelTest(EncoderDecoderMixin, unittest.TestCase): + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = SwinModel(config).eval() + decoder_model = BartForCausalLM(decoder_config).eval() + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + model_tester_encoder = SwinModelTester(self, batch_size=13, embed_dim=32) + model_tester_decoder = BartModelTester(self, batch_size=13, hidden_size=32, max_position_embeddings=512) + encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() + decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs() + config, pixel_values, _ = encoder_config_and_inputs + decoder_config, decoder_inputs_dict = decoder_config_and_inputs + decoder_inputs_dict["labels"] = decoder_inputs_dict["decoder_input_ids"] + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + # disable cache for now + decoder_config.use_cache = False + return { + "config": config, + "pixel_values": pixel_values, + "decoder_config": decoder_config, + **decoder_inputs_dict, + } + + def check_encoder_decoder_model_output_attentions( + self, + config, + decoder_config, + decoder_input_ids, + decoder_attention_mask, + labels=None, + pixel_values=None, + **kwargs, + ): + # make the decoder inputs a different shape from the encoder inputs to harden the test + decoder_input_ids = decoder_input_ids[:, :-1] + decoder_attention_mask = decoder_attention_mask[:, :-1] + encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) + enc_dec_model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) + enc_dec_model.to(torch_device) + outputs_encoder_decoder = enc_dec_model( + pixel_values=pixel_values, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + output_attentions=True, + ) + + encoder_attentions = outputs_encoder_decoder["encoder_attentions"] + self.assertEqual(len(encoder_attentions), config.num_hidden_layers) + + # in Swin, the seq_len equals: + seq_len = encoder_model.config.window_size**2 + self.assertEqual(encoder_attentions[0].shape[-3:], (config.num_attention_heads[0], seq_len, seq_len)) + + decoder_attentions = outputs_encoder_decoder["decoder_attentions"] + num_decoder_layers = ( + decoder_config.num_decoder_layers + if hasattr(decoder_config, "num_decoder_layers") + else decoder_config.num_hidden_layers + ) + self.assertEqual(len(decoder_attentions), num_decoder_layers) + + self.assertEqual( + decoder_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), + ) + + cross_attentions = outputs_encoder_decoder["cross_attentions"] + self.assertEqual(len(cross_attentions), num_decoder_layers) + + encoder_seq_len = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) + cross_attention_input_seq_len = decoder_input_ids.shape[-1] + self.assertEqual( + cross_attentions[0].shape[-3:], + (decoder_config.num_attention_heads, cross_attention_input_seq_len, encoder_seq_len), + ) + + # there are no published pretrained BART-causal checkpoints for now + def test_real_model_save_load_from_pretrained(self): + pass + + +@require_torch +class ViT2TrOCR(EncoderDecoderMixin, unittest.TestCase): + def get_encoder_decoder_model(self, config, decoder_config): + encoder_model = ViTModel(config).eval() + decoder_model = TrOCRForCausalLM(decoder_config).eval() + return encoder_model, decoder_model + + def prepare_config_and_inputs(self): + model_tester_encoder = ViTModelTester(self, batch_size=13) + model_tester_decoder = TrOCRStandaloneDecoderModelTester( + self, batch_size=13, d_model=32, max_position_embeddings=512 + ) + encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs() + decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs() + config, pixel_values, _ = encoder_config_and_inputs + (decoder_config, decoder_input_ids, decoder_attention_mask, _) = decoder_config_and_inputs + + # make sure that cross attention layers are added + decoder_config.add_cross_attention = True + # disable cache for now + decoder_config.use_cache = False + return { + "config": config, + "pixel_values": pixel_values, + "decoder_config": decoder_config, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "labels": decoder_input_ids, + } + + # there are no published pretrained TrOCR checkpoints for now + def test_real_model_save_load_from_pretrained(self): + pass + + +@require_vision +@require_torch +class TrOCRModelIntegrationTest(unittest.TestCase): + @cached_property + def default_processor(self): + return TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten") if is_vision_available() else None + + @slow + def test_inference_handwritten(self): + model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten").to(torch_device) + + dataset = load_dataset("hf-internal-testing/fixtures_ocr", split="test") + image = Image.open(dataset[0]["file"]).convert("RGB") + + processor = self.default_processor + pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(torch_device) + + # forward pass + decoder_input_ids = torch.tensor([[model.config.decoder.decoder_start_token_id]]).to(torch_device) + outputs = model(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids) + logits = outputs.logits + + # verify the logits + expected_shape = torch.Size((1, 1, model.decoder.config.vocab_size)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor( + [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311] + ).to(torch_device) + + self.assertTrue(torch.allclose(logits[0, 0, :10], expected_slice, atol=1e-4)) + + @slow + def test_inference_printed(self): + model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed").to(torch_device) + + dataset = load_dataset("hf-internal-testing/fixtures_ocr", split="test") + image = Image.open(dataset[1]["file"]).convert("RGB") + + processor = self.default_processor + pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(torch_device) + + # forward pass + decoder_input_ids = torch.tensor([[model.config.decoder.decoder_start_token_id]]).to(torch_device) + outputs = model(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids) + logits = outputs.logits + + # verify the logits + expected_shape = torch.Size((1, 1, model.decoder.config.vocab_size)) + self.assertEqual(outputs.logits.shape, expected_shape) + + is_pillow_less_than_9 = version.parse(PIL.__version__) < version.parse("9.0.0") + + if is_pillow_less_than_9: + expected_slice = torch.tensor( + [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210], + device=torch_device, + ) + else: + expected_slice = torch.tensor( + [-5.6844, -5.8372, 1.1518, -6.8984, 6.8587, -2.4453, 1.2347, -1.0241, -1.9649, -3.9109], + device=torch_device, + ) + + self.assertTrue(torch.allclose(logits[0, 0, :10], expected_slice, atol=1e-4)) + + +@require_vision +@require_torch +class ViT2GPT2ModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_coco_en(self): + loc = "ydshieh/vit-gpt2-coco-en" + + image_processor = ViTImageProcessor.from_pretrained(loc) + tokenizer = AutoTokenizer.from_pretrained(loc) + model = VisionEncoderDecoderModel.from_pretrained(loc) + model.to(torch_device) + model.eval() + + # We will verify our results on an image of cute cats + img = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + pixel_values = image_processor(images=img, return_tensors="pt").pixel_values.to(torch_device) + + decoder_input_ids = torch.tensor([[model.config.decoder_start_token_id]]).to(torch_device) + + with torch.no_grad(): + logits = model(pixel_values, decoder_input_ids)[0].detach().cpu().numpy() + + # verify the logits + expected_shape = (1, 1, model.config.decoder.vocab_size) + self.assertEqual(logits.shape, expected_shape) + + EXPECTED_LOGIT_SLICE = np.array( + [ + -38.705807, + -30.639929, + -31.41903, + -39.012012, + -38.38696, + -34.887207, + -33.290855, + -35.68447, + -38.508484, + -36.124645, + ] + ) + max_diff = np.amax(np.abs(logits[0, 0, :10] - EXPECTED_LOGIT_SLICE)) + self.assertLessEqual(max_diff, 1e-4) + + def generate_step(pixel_values): + outputs = model.generate( + pixel_values, max_length=16, num_beams=4, return_dict_in_generate=True, output_scores=True + ) + output_ids = outputs.sequences + preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True) + preds = [pred.strip() for pred in preds] + + return preds, outputs.sequences_scores.detach().cpu().numpy() + + preds, scores = generate_step(pixel_values) + + EXPECTED_SCORES = np.array([-0.5956343]) + max_diff = np.amax(np.abs(scores - EXPECTED_SCORES)) + self.assertLessEqual(max_diff, 1e-4) + + # should produce + # ["a cat laying on top of a couch next to another cat"] + self.assertEqual(preds, ["a cat laying on top of a couch next to another cat"]) + + +@require_vision +@require_torch +@require_sentencepiece +class DonutModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_docvqa(self): + processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa") + model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa").to( + torch_device + ) + + dataset = load_dataset("hf-internal-testing/example-documents", split="test") + image = dataset[0]["image"] + + pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(torch_device) + decoder_input_ids = processor.tokenizer( + "", add_special_tokens=False, return_tensors="pt" + ).input_ids.to(torch_device) + + # step 1: single forward pass + with torch.no_grad(): + outputs = model(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids) + logits = outputs.logits + + # verify the logits + expected_shape = torch.Size([1, 1, 57532]) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([24.3873, -6.4491, 32.5394]).to(torch_device) + self.assertTrue(torch.allclose(logits[0, 0, :3], expected_slice, atol=1e-4)) + + # step 2: generation + task_prompt = "{user_input}" + question = "When is the coffee break?" + prompt = task_prompt.replace("{user_input}", question) + decoder_input_ids = processor.tokenizer(prompt, add_special_tokens=False, return_tensors="pt").input_ids + decoder_input_ids = decoder_input_ids.to(torch_device) + + outputs = model.generate( + pixel_values, + decoder_input_ids=decoder_input_ids, + max_length=model.decoder.config.max_position_embeddings, + early_stopping=True, + pad_token_id=processor.tokenizer.pad_token_id, + eos_token_id=processor.tokenizer.eos_token_id, + use_cache=True, + num_beams=1, + bad_words_ids=[[processor.tokenizer.unk_token_id]], + output_scores=True, + return_dict_in_generate=True, + ) + sequence = processor.batch_decode(outputs.sequences)[0] + sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "") + sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token + + # verify generated sequence + self.assertEqual( + sequence, " When is the coffee break? 11-14 to 11:39 a.m." + ) + + # verify scores + self.assertEqual(len(outputs.scores), 11) + self.assertTrue( + torch.allclose( + outputs.scores[0][0, :3], torch.tensor([5.6019, -3.5070, 13.7123], device=torch_device), atol=1e-4 + ) + ) + + @slow + def test_inference_cordv2(self): + processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2") + model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2").to( + torch_device + ) + + dataset = load_dataset("hf-internal-testing/example-documents", split="test") + image = dataset[2]["image"] + + pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(torch_device) + decoder_input_ids = processor.tokenizer( + "", add_special_tokens=False, return_tensors="pt" + ).input_ids.to(torch_device) + + # step 1: single forward pass + with torch.no_grad(): + outputs = model(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids) + logits = outputs.logits + + # verify the logits + expected_shape = torch.Size((1, 1, model.decoder.config.vocab_size)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-27.4344, -3.2686, -19.3524], device=torch_device) + self.assertTrue(torch.allclose(logits[0, 0, :3], expected_slice, atol=1e-4)) + + # step 2: generation + task_prompt = "" + decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids + decoder_input_ids = decoder_input_ids.to(torch_device) + + outputs = model.generate( + pixel_values, + decoder_input_ids=decoder_input_ids, + max_length=model.decoder.config.max_position_embeddings, + early_stopping=True, + pad_token_id=processor.tokenizer.pad_token_id, + eos_token_id=processor.tokenizer.eos_token_id, + use_cache=True, + num_beams=1, + bad_words_ids=[[processor.tokenizer.unk_token_id]], + output_scores=True, + return_dict_in_generate=True, + ) + + sequence = processor.batch_decode(outputs.sequences)[0] + sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "") + sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token + + # verify generated sequence + expected_sequence = " CINNAMON SUGAR 17,000 1 x 17,000 17,000 17,000 20,000 3,000" # noqa: E231 # fmt: skip + self.assertEqual(sequence, expected_sequence) + + # verify scores + self.assertEqual(len(outputs.scores), 43) + self.assertTrue( + torch.allclose( + outputs.scores[0][0, :3], torch.tensor([-27.4344, -3.2686, -19.3524], device=torch_device), atol=1e-4 + ) + ) + + @slow + def test_inference_rvlcdip(self): + processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-rvlcdip") + model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-rvlcdip").to( + torch_device + ) + + dataset = load_dataset("hf-internal-testing/example-documents", split="test") + image = dataset[1]["image"] + + pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(torch_device) + + # step 1: single forward pass + decoder_input_ids = processor.tokenizer( + "", add_special_tokens=False, return_tensors="pt" + ).input_ids.to(torch_device) + with torch.no_grad(): + outputs = model(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids) + logits = outputs.logits + + # verify the logits + expected_shape = torch.Size((1, 1, model.decoder.config.vocab_size)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-17.6490, -4.8381, -15.7577], device=torch_device) + self.assertTrue(torch.allclose(logits[0, 0, :3], expected_slice, atol=1e-4)) + + # step 2: generation + task_prompt = "" + decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids + decoder_input_ids = decoder_input_ids.to(torch_device) + + outputs = model.generate( + pixel_values, + decoder_input_ids=decoder_input_ids, + max_length=model.decoder.config.max_position_embeddings, + early_stopping=True, + pad_token_id=processor.tokenizer.pad_token_id, + eos_token_id=processor.tokenizer.eos_token_id, + use_cache=True, + num_beams=1, + bad_words_ids=[[processor.tokenizer.unk_token_id]], + output_scores=True, + return_dict_in_generate=True, + ) + + sequence = processor.batch_decode(outputs.sequences)[0] + sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "") + sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token + + # verify generated sequence + self.assertEqual(sequence, "") + + # verify scores + self.assertEqual(len(outputs.scores), 4) + self.assertTrue( + torch.allclose( + outputs.scores[0][0, :3], torch.tensor([-17.6490, -4.8381, -15.7577], device=torch_device), atol=1e-4 + ) + ) + + +@require_levenshtein +@require_nltk +@require_torch +@require_vision +@slow +class NougatModelIntegrationTest(unittest.TestCase): + @cached_property + def default_processor(self): + return NougatProcessor.from_pretrained("facebook/nougat-base") if is_vision_available() else None + + @cached_property + def default_model(self): + return VisionEncoderDecoderModel.from_pretrained("facebook/nougat-base").to(torch_device) + + @cached_property + def default_image(self): + filepath = hf_hub_download( + repo_id="hf-internal-testing/fixtures_docvqa", filename="nougat_pdf.png", repo_type="dataset" + ) + image = Image.open(filepath).convert("RGB") + return image + + def test_forward_pass(self): + processor = self.default_processor + model = self.default_model + image = self.default_image + pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(torch_device) + + decoder_input_ids = torch.tensor([[0]]).to(torch_device) + outputs = model(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids) + logits = outputs.logits + + # verify the logits + expected_shape = torch.Size((1, 1, model.decoder.config.vocab_size)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor( + [1.6253, -4.2179, 5.8532, -2.7911, -5.0609, -4.7397, -4.2890, -5.1073, -4.8908, -4.9729] + ).to(torch_device) + + self.assertTrue(torch.allclose(logits[0, 0, :10], expected_slice, atol=1e-4)) + + def test_generation(self): + processor = self.default_processor + model = self.default_model + image = self.default_image + pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(torch_device) + + outputs = model.generate( + pixel_values, + min_length=1, + max_length=3584, + bad_words_ids=[[processor.tokenizer.unk_token_id]], + return_dict_in_generate=True, + output_scores=True, + ) + + # verify generated sequence + generated = processor.batch_decode(outputs.sequences, skip_special_tokens=True)[0] + expected_raw_generation = "# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@meta.com\n\nGuillem Cucurull\n\nThomas Scialom\n\nRobert Stojnic\n\nMeta AI\n\nThe paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\n###### Abstract\n\nScientific knowledge is predominantly stored in books and scientific journals, often in the form of PDFs. However, the PDF format leads to a loss of semantic information, particularly for mathematical expressions. We propose Nougat (**N**eural **O**ptical **U**nderstanding for **A**cademic Documents), a Visual Transformer model that performs an _Optical Character Recognition_ (OCR) task for processing scientific documents into a markup language, and demonstrate the effectiveness of our model on a new dataset of scientific documents. The proposed approach offers a promising solution to enhance the accessibility of scientific knowledge in the digital age, by bridging the gap between human-readable documents and machine-readable text. We release the models and code to accelerate future work on scientific text recognition.\n\n## 1 Introduction\n\nThe majority of scientific knowledge is stored in books or published in scientific journals, most commonly in the Portable Document Format (PDF). Next to HTML, PDFs are the second most prominent data format on the internet, making up 2.4% of common crawl [1]. However, the information stored in these files is very difficult to extract into any other formats. This is especially true for highly specialized documents, such as scientific research papers, where the semantic information of mathematical expressions is lost.\n\nExisting Optical Character Recognition (OCR) engines, such as Tesseract OCR [2], excel at detecting and classifying individual characters and words in an image, but fail to understand the relationship between them due to their line-by-line approach. This means that they treat superscripts and subscripts in the same way as the surrounding text, which is a significant drawback for mathematical expressions. In mathematical notations like fractions, exponents, and matrices, relative positions of characters are crucial.\n\nConverting academic research papers into machine-readable text also enables accessibility and searchability of science as a whole. The information of millions of academic papers can not be fully accessed because they are locked behind an unreadable format. Existing corpora, such as the S2ORC dataset [3], capture the text of 12M2 papers using GROBID [4], but are missing meaningful representations of the mathematical equations.\n\nFootnote 2: The paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\nTo this end, we introduce Nougat, a transformer based model that can convert images of document pages to formatted markup text.\n\nThe primary contributions in this paper are\n\n* Release of a pre-trained model capable of converting a PDF to a lightweight markup language. We release the code and the model on GitHub3 Footnote 3: https://github.com/facebookresearch/nougat\n* We introduce a pipeline to create dataset for pairing PDFs to source code\n* Our method is only dependent on the image of a page, allowing access to scanned papers and books" + self.assertTrue(generated == expected_raw_generation) + + # verify postprocessed sequence + generated = processor.post_process_generation(generated, fix_markdown=False) + expected_generation = "\n\n# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@meta.com\n\nGuillem Cucurull\n\nThomas Scialom\n\nRobert Stojnic\n\nMeta AI\n\nThe paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\n###### Abstract\n\nScientific knowledge is predominantly stored in books and scientific journals, often in the form of PDFs. However, the PDF format leads to a loss of semantic information, particularly for mathematical expressions. We propose Nougat (**N**eural **O**ptical **U**nderstanding for **A**cademic Documents), a Visual Transformer model that performs an _Optical Character Recognition_ (OCR) task for processing scientific documents into a markup language, and demonstrate the effectiveness of our model on a new dataset of scientific documents. The proposed approach offers a promising solution to enhance the accessibility of scientific knowledge in the digital age, by bridging the gap between human-readable documents and machine-readable text. We release the models and code to accelerate future work on scientific text recognition.\n\n## 1 Introduction\n\nThe majority of scientific knowledge is stored in books or published in scientific journals, most commonly in the Portable Document Format (PDF). Next to HTML, PDFs are the second most prominent data format on the internet, making up 2.4% of common crawl [1]. However, the information stored in these files is very difficult to extract into any other formats. This is especially true for highly specialized documents, such as scientific research papers, where the semantic information of mathematical expressions is lost.\n\nExisting Optical Character Recognition (OCR) engines, such as Tesseract OCR [2], excel at detecting and classifying individual characters and words in an image, but fail to understand the relationship between them due to their line-by-line approach. This means that they treat superscripts and subscripts in the same way as the surrounding text, which is a significant drawback for mathematical expressions. In mathematical notations like fractions, exponents, and matrices, relative positions of characters are crucial.\n\nConverting academic research papers into machine-readable text also enables accessibility and searchability of science as a whole. The information of millions of academic papers can not be fully accessed because they are locked behind an unreadable format. Existing corpora, such as the S2ORC dataset [3], capture the text of 12M2 papers using GROBID [4], but are missing meaningful representations of the mathematical equations.\n\nFootnote 2: The paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\nTo this end, we introduce Nougat, a transformer based model that can convert images of document pages to formatted markup text.\n\nThe primary contributions in this paper are\n\n* Release of a pre-trained model capable of converting a PDF to a lightweight markup language. We release the code and the model on GitHub3 Footnote 3: https://github.com/facebookresearch/nougat\n* We introduce a pipeline to create dataset for pairing PDFs to source code\n* Our method is only dependent on the image of a page, allowing access to scanned papers and books" + self.assertTrue(generated == expected_generation) + + # verify scores + self.assertEqual(len(outputs.scores), 741) + self.assertTrue( + torch.allclose( + outputs.scores[0][0, :3], torch.tensor([1.6253, -4.2179, 5.8532], device=torch_device), atol=1e-4 + ) + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_flax_vision_text_dual_encoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_flax_vision_text_dual_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf8b4335f5de84751192478622f2cfd37814914 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_flax_vision_text_dual_encoder.py @@ -0,0 +1,388 @@ +# coding=utf-8 +# 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 VisionTextDualEncoder model. """ + + +import collections +import tempfile +import unittest + +import numpy as np + +from transformers.testing_utils import ( + is_pt_flax_cross_test, + require_flax, + require_torch, + require_vision, + slow, + torch_device, +) +from transformers.utils import is_flax_available, is_torch_available, is_vision_available + +from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask +from ..bert.test_modeling_flax_bert import FlaxBertModelTester +from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester +from ..vit.test_modeling_flax_vit import FlaxViTModelTester + + +if is_flax_available(): + from transformers import ( + FlaxBertModel, + FlaxCLIPVisionModel, + FlaxVisionTextDualEncoderModel, + FlaxViTModel, + VisionTextDualEncoderConfig, + VisionTextDualEncoderProcessor, + ) + from transformers.modeling_flax_pytorch_utils import ( + convert_pytorch_state_dict_to_flax, + load_flax_weights_in_pytorch_model, + ) + + +if is_torch_available(): + import torch + + from transformers import VisionTextDualEncoderModel + +if is_vision_available(): + from PIL import Image + + +# Inspired by +# https://github.com/rwightman/pytorch-image-models/blob/b9bd960a032c75ca6b808ddeed76bee5f3ed4972/timm/models/layers/helpers.py +# From PyTorch internals +def to_2tuple(x): + if isinstance(x, collections.abc.Iterable): + return x + return (x, x) + + +@require_flax +class VisionTextDualEncoderMixin: + def get_vision_text_model(self, config, text_config): + pass + + def prepare_config_and_inputs(self): + pass + + def get_pretrained_model_and_inputs(self): + pass + + def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): + diff = np.abs((a - b)).max() + self.assertLessEqual(diff, tol, f"Difference between torch and flax is {diff} (>= {tol}).") + + def check_model_from_pretrained_configs( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + config = VisionTextDualEncoderConfig.from_vision_text_configs(vision_config, text_config) + + model = FlaxVisionTextDualEncoderModel(config) + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + + self.assertEqual(output["text_embeds"].shape, (input_ids.shape[0], config.projection_dim)) + self.assertEqual(output["image_embeds"].shape, (pixel_values.shape[0], config.projection_dim)) + + def check_vision_text_dual_encoder_from_pretrained( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + kwargs = {"vision_model": vision_model, "text_model": text_model} + model = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**kwargs) + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + + self.assertEqual(output["text_embeds"].shape, (input_ids.shape[0], model.config.projection_dim)) + self.assertEqual(output["image_embeds"].shape, (pixel_values.shape[0], model.config.projection_dim)) + + def check_save_load(self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + kwargs = {"vision_model": vision_model, "text_model": text_model} + model = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**kwargs) + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + out_1 = output[0] + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = FlaxVisionTextDualEncoderModel.from_pretrained(tmpdirname) + + after_output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + out_2 = after_output[0] + max_diff = np.amax(np.abs(out_2 - out_1)) + self.assertLessEqual(max_diff, 1e-3) + + def check_vision_text_output_attention( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + kwargs = {"vision_model": vision_model, "text_model": text_model} + model = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**kwargs) + + output = model( + input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask, output_attentions=True + ) + + vision_attentions = output.vision_model_output.attentions + self.assertEqual(len(vision_attentions), vision_config.num_hidden_layers) + + # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) + image_size = to_2tuple(vision_model.config.image_size) + patch_size = to_2tuple(vision_model.config.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + seq_len = num_patches + 1 + self.assertEqual(vision_attentions[0].shape[-3:], (vision_config.num_attention_heads, seq_len, seq_len)) + + text_attentions = output.text_model_output.attentions + self.assertEqual(len(text_attentions), text_config.num_hidden_layers) + + self.assertEqual( + text_attentions[0].shape[-3:], + (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]), + ) + + def check_pt_flax_equivalence(self, pt_model, fx_model, inputs_dict): + pt_model.to(torch_device) + pt_model.eval() + + # prepare inputs + flax_inputs = inputs_dict + pt_inputs = {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()} + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs).to_tuple() + + fx_outputs = fx_model(**inputs_dict).to_tuple() + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output in zip(fx_outputs[:4], pt_outputs[:4]): + self.assert_almost_equals(fx_output, pt_output.numpy(), 4e-2) + + # PT -> Flax + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = FlaxVisionTextDualEncoderModel.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**inputs_dict).to_tuple() + self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4], pt_outputs[:4]): + self.assert_almost_equals(fx_output_loaded, pt_output.numpy(), 4e-2) + + # Flax -> PT + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = VisionTextDualEncoderModel.from_pretrained(tmpdirname, from_flax=True) + + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs).to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output_loaded in zip(fx_outputs[:4], pt_outputs_loaded[:4]): + self.assert_almost_equals(fx_output, pt_output_loaded.numpy(), 4e-2) + + def check_equivalence_pt_to_flax(self, vision_config, text_config, inputs_dict): + config = VisionTextDualEncoderConfig.from_vision_text_configs(vision_config, text_config) + + pt_model = VisionTextDualEncoderModel(config) + fx_model = FlaxVisionTextDualEncoderModel(config) + + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + self.check_pt_flax_equivalence(pt_model, fx_model, inputs_dict) + + def check_equivalence_flax_to_pt(self, vision_config, text_config, inputs_dict): + config = VisionTextDualEncoderConfig.from_vision_text_configs(vision_config, text_config) + + pt_model = VisionTextDualEncoderModel(config) + fx_model = FlaxVisionTextDualEncoderModel(config) + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + + self.check_pt_flax_equivalence(pt_model, fx_model, inputs_dict) + + def test_model_from_pretrained_configs(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_model_from_pretrained_configs(**inputs_dict) + + def test_vision_text_dual_encoder_from_pretrained(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_vision_text_dual_encoder_from_pretrained(**inputs_dict) + + def test_save_load(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_save_load(**inputs_dict) + + def test_vision_text_output_attention(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_vision_text_output_attention(**inputs_dict) + + @is_pt_flax_cross_test + def test_pt_flax_equivalence(self): + config_inputs_dict = self.prepare_config_and_inputs() + vision_config = config_inputs_dict.pop("vision_config") + text_config = config_inputs_dict.pop("text_config") + + inputs_dict = config_inputs_dict + + self.check_equivalence_pt_to_flax(vision_config, text_config, inputs_dict) + self.check_equivalence_flax_to_pt(vision_config, text_config, inputs_dict) + + @slow + def test_real_model_save_load_from_pretrained(self): + model_2, inputs = self.get_pretrained_model_and_inputs() + + outputs = model_2(**inputs) + out_2 = outputs[0] + + with tempfile.TemporaryDirectory() as tmp_dirname: + model_2.save_pretrained(tmp_dirname) + model_1 = FlaxVisionTextDualEncoderModel.from_pretrained(tmp_dirname) + + after_outputs = model_1(**inputs) + out_1 = after_outputs[0] + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + +@require_flax +class FlaxViTBertModelTest(VisionTextDualEncoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( + "hf-internal-testing/tiny-random-vit", + "hf-internal-testing/tiny-bert", + vision_from_pt=True, + text_from_pt=True, + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.config.vision_config.num_channels, + model.config.vision_config.image_size, + model.config.vision_config.image_size, + ] + ) + input_ids = ids_tensor([batch_size, 4], model.config.text_config.vocab_size) + attention_mask = random_attention_mask([batch_size, 4]) + inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} + + return model, inputs + + def get_vision_text_model(self, vision_config, text_config): + vision_model = FlaxViTModel(vision_config) + text_model = FlaxBertModel(text_config) + return vision_model, text_model + + def prepare_config_and_inputs(self): + vit_model_tester = FlaxViTModelTester(self) + bert_model_tester = FlaxBertModelTester(self) + vision_config_and_inputs = vit_model_tester.prepare_config_and_inputs() + text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() + + vision_config, pixel_values = vision_config_and_inputs + + text_config, input_ids, token_type_ids, attention_mask = text_config_and_inputs + + # make sure that cross attention layers are added + return { + "text_config": text_config, + "vision_config": vision_config, + "pixel_values": pixel_values, + "attention_mask": attention_mask, + "input_ids": input_ids, + "token_type_ids": token_type_ids, + } + + +@require_torch +class FlaxCLIPVisionBertModelTest(VisionTextDualEncoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( + "hf-internal-testing/tiny-random-clip", + "hf-internal-testing/tiny-bert", + vision_from_pt=True, + text_from_pt=True, + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.config.vision_config.num_channels, + model.config.vision_config.image_size, + model.config.vision_config.image_size, + ] + ) + input_ids = ids_tensor([batch_size, 4], model.config.text_config.vocab_size) + attention_mask = random_attention_mask([batch_size, 4]) + inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} + + return model, inputs + + def get_vision_text_model(self, vision_config, text_config): + vision_model = FlaxCLIPVisionModel(vision_config) + text_model = FlaxBertModel(text_config) + return vision_model, text_model + + def prepare_config_and_inputs(self): + clip_model_tester = FlaxCLIPVisionModelTester(self) + bert_model_tester = FlaxBertModelTester(self) + vision_config_and_inputs = clip_model_tester.prepare_config_and_inputs() + text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() + + vision_config, pixel_values = vision_config_and_inputs + + text_config, input_ids, token_type_ids, attention_mask = text_config_and_inputs + + # make sure that cross attention layers are added + return { + "text_config": text_config, + "vision_config": vision_config, + "pixel_values": pixel_values, + "attention_mask": attention_mask, + "input_ids": input_ids, + "token_type_ids": token_type_ids, + } + + +@require_flax +@require_vision +class FlaxVisionTextDualEncoderIntegrationTest(unittest.TestCase): + @slow + def test_inference(self): + model = FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian", logit_scale_init_value=1.0) + processor = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian") + + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + inputs = processor( + text=["una foto di un gatto", "una foto di un cane"], images=image, padding=True, return_tensors="np" + ) + + outputs = model(**inputs) + + # verify the logits + self.assertEqual(outputs.logits_per_image.shape, (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])) + self.assertEqual( + outputs.logits_per_text.shape, + (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]), + ) + + expected_logits = np.array([[1.2284727, 0.3104122]]) + + self.assertTrue(np.allclose(outputs.logits_per_image, expected_logits, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_tf_vision_text_dual_encoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_tf_vision_text_dual_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..10baef00594f22819354f5d67abedfa840782568 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_tf_vision_text_dual_encoder.py @@ -0,0 +1,421 @@ +# coding=utf-8 +# 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 VisionTextDualEncoder model. """ + + +from __future__ import annotations + +import collections +import tempfile +import unittest + +import numpy as np + +from transformers.testing_utils import require_tf, require_vision, slow +from transformers.utils import is_tf_available, is_vision_available + +from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask +from ..bert.test_modeling_tf_bert import TFBertModelTester +from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester +from ..deit.test_modeling_tf_deit import TFDeiTModelTester +from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester +from ..vit.test_modeling_tf_vit import TFViTModelTester + + +if is_tf_available(): + from transformers import ( + TFBertModel, + TFCLIPVisionModel, + TFDeiTModel, + TFRobertaModel, + TFVisionTextDualEncoderModel, + TFViTModel, + VisionTextDualEncoderConfig, + ) + +if is_vision_available(): + from PIL import Image + + from transformers import VisionTextDualEncoderProcessor + + +# Inspired by +# https://github.com/rwightman/pytorch-image-models/blob/b9bd960a032c75ca6b808ddeed76bee5f3ed4972/timm/models/layers/helpers.py +# From PyTorch internals +def to_2tuple(x): + if isinstance(x, collections.abc.Iterable): + return x + return (x, x) + + +@require_tf +class TFVisionTextDualEncoderMixin: + def get_vision_text_model(self, config, text_config): + pass + + def prepare_config_and_inputs(self): + pass + + def get_pretrained_model_and_inputs(self): + pass + + def check_model_from_pretrained_configs( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + config = VisionTextDualEncoderConfig.from_vision_text_configs(vision_config, text_config) + + model = TFVisionTextDualEncoderModel(config) + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + + self.assertEqual(output["text_embeds"].shape, (input_ids.shape[0], config.projection_dim)) + self.assertEqual(output["image_embeds"].shape, (pixel_values.shape[0], config.projection_dim)) + + def check_vision_text_dual_encoder_model( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + model = TFVisionTextDualEncoderModel(vision_model=vision_model, text_model=text_model) + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + + self.assertEqual(output["text_embeds"].shape, (input_ids.shape[0], model.config.projection_dim)) + self.assertEqual(output["image_embeds"].shape, (pixel_values.shape[0], model.config.projection_dim)) + + def check_vision_text_dual_encoder_from_pretrained( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + kwargs = {"vision_model": vision_model, "text_model": text_model} + model = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**kwargs) + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + + self.assertEqual(output["text_embeds"].shape, (input_ids.shape[0], model.config.projection_dim)) + self.assertEqual(output["image_embeds"].shape, (pixel_values.shape[0], model.config.projection_dim)) + + def check_save_load(self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + model = TFVisionTextDualEncoderModel(vision_model=vision_model, text_model=text_model) + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + out_1 = output[0].numpy() + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = TFVisionTextDualEncoderModel.from_pretrained(tmpdirname) + + after_output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + out_2 = after_output[0].numpy() + max_diff = np.amax(np.abs(out_2 - out_1)) + self.assertLessEqual(max_diff, 1e-5) + + def check_vision_text_output_attention( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + model = TFVisionTextDualEncoderModel(vision_model=vision_model, text_model=text_model) + + output = model( + input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask, output_attentions=True + ) + + vision_attentions = output.vision_model_output.attentions + self.assertEqual(len(vision_attentions), vision_config.num_hidden_layers) + + # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) + image_size = to_2tuple(vision_model.config.image_size) + patch_size = to_2tuple(vision_model.config.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + seq_len = num_patches + 1 + self.assertEqual(vision_attentions[0].shape[-3:], (vision_config.num_attention_heads, seq_len, seq_len)) + + text_attentions = output.text_model_output.attentions + self.assertEqual(len(text_attentions), text_config.num_hidden_layers) + + self.assertEqual( + text_attentions[0].shape[-3:], + (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]), + ) + + def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): + diff = np.abs((a - b)).max() + self.assertLessEqual(diff, tol, f"Difference between torch and flax is {diff} (>= {tol}).") + + def test_vision_text_dual_encoder_model(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_vision_text_dual_encoder_model(**inputs_dict) + + def test_model_from_pretrained_configs(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_model_from_pretrained_configs(**inputs_dict) + + def test_vision_text_dual_encoder_from_pretrained(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_vision_text_dual_encoder_from_pretrained(**inputs_dict) + + def test_save_load(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_save_load(**inputs_dict) + + def test_vision_text_output_attention(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_vision_text_output_attention(**inputs_dict) + + @slow + def test_real_model_save_load_from_pretrained(self): + model_2, inputs = self.get_pretrained_model_and_inputs() + + outputs = model_2(**inputs) + out_2 = outputs[0].numpy() + + with tempfile.TemporaryDirectory() as tmp_dirname: + model_2.save_pretrained(tmp_dirname) + model_1 = TFVisionTextDualEncoderModel.from_pretrained(tmp_dirname) + + after_outputs = model_1(**inputs) + out_1 = after_outputs[0].numpy() + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + +@require_tf +class TFViTBertModelTest(TFVisionTextDualEncoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = TFVisionTextDualEncoderModel.from_vision_text_pretrained( + "hf-internal-testing/tiny-random-vit", "hf-internal-testing/tiny-random-bert" + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.vision_model.config.num_channels, + model.vision_model.config.image_size, + model.vision_model.config.image_size, + ] + ) + input_ids = ids_tensor([batch_size, 4], model.text_model.config.vocab_size) + attention_mask = random_attention_mask([batch_size, 4]) + inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} + + return model, inputs + + def get_vision_text_model(self, vision_config, text_config): + vision_model = TFViTModel(vision_config, name="vision_model") + text_model = TFBertModel(text_config, name="text_model") + return vision_model, text_model + + def prepare_config_and_inputs(self): + vit_model_tester = TFViTModelTester(self) + bert_model_tester = TFBertModelTester(self) + vision_config_and_inputs = vit_model_tester.prepare_config_and_inputs() + text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() + + vision_config, pixel_values, _ = vision_config_and_inputs + + ( + text_config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = text_config_and_inputs + + return { + "text_config": text_config, + "vision_config": vision_config, + "pixel_values": pixel_values, + "attention_mask": input_mask, + "input_ids": input_ids, + "text_token_type_ids": token_type_ids, + "text_sequence_labels": sequence_labels, + "text_token_labels": token_labels, + "text_choice_labels": choice_labels, + } + + +@require_tf +class TFDeiTRobertaModelTest(TFVisionTextDualEncoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's + # just reinitialize it. + model = TFVisionTextDualEncoderModel.from_vision_text_pretrained( + "Rocketknight1/tiny-random-deit-tf", "hf-internal-testing/tiny-random-roberta" + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.vision_model.config.num_channels, + model.vision_model.config.image_size, + model.vision_model.config.image_size, + ] + ) + input_ids = ids_tensor([batch_size, 4], model.text_model.config.vocab_size) + attention_mask = random_attention_mask([batch_size, 4]) + inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} + + return model, inputs + + def check_vision_text_output_attention( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + model = TFVisionTextDualEncoderModel(vision_model=vision_model, text_model=text_model) + + output = model( + input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask, output_attentions=True + ) + + vision_attentions = output.vision_model_output.attentions + self.assertEqual(len(vision_attentions), vision_config.num_hidden_layers) + + # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) + image_size = to_2tuple(vision_model.config.image_size) + patch_size = to_2tuple(vision_model.config.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + seq_len = num_patches + 2 + self.assertEqual(vision_attentions[0].shape[-3:], (vision_config.num_attention_heads, seq_len, seq_len)) + + text_attentions = output.text_model_output.attentions + self.assertEqual(len(text_attentions), text_config.num_hidden_layers) + + self.assertEqual( + text_attentions[0].shape[-3:], + (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]), + ) + + def get_vision_text_model(self, vision_config, text_config): + vision_model = TFDeiTModel(vision_config, name="vision_model") + text_model = TFRobertaModel(text_config, name="text_model") + return vision_model, text_model + + def prepare_config_and_inputs(self): + vit_model_tester = TFDeiTModelTester(self) + bert_model_tester = TFRobertaModelTester(self) + vision_config_and_inputs = vit_model_tester.prepare_config_and_inputs() + text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() + + vision_config, pixel_values, _ = vision_config_and_inputs + + ( + text_config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = text_config_and_inputs + + return { + "text_config": text_config, + "vision_config": vision_config, + "pixel_values": pixel_values, + "attention_mask": input_mask, + "input_ids": input_ids, + "text_token_type_ids": token_type_ids, + "text_sequence_labels": sequence_labels, + "text_token_labels": token_labels, + "text_choice_labels": choice_labels, + } + + +@require_tf +class TFCLIPVisionBertModelTest(TFVisionTextDualEncoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = TFVisionTextDualEncoderModel.from_vision_text_pretrained( + "Rocketknight1/tiny-random-clip-tf", "hf-internal-testing/tiny-random-bert" + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.vision_model.config.num_channels, + model.vision_model.config.image_size, + model.vision_model.config.image_size, + ] + ) + input_ids = ids_tensor([batch_size, 4], model.text_model.config.vocab_size) + attention_mask = random_attention_mask([batch_size, 4]) + inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} + + return model, inputs + + def get_vision_text_model(self, vision_config, text_config): + vision_model = TFCLIPVisionModel(vision_config, name="vision_model") + text_model = TFBertModel(text_config, name="text_model") + return vision_model, text_model + + def prepare_config_and_inputs(self): + clip_model_tester = TFCLIPVisionModelTester(self) + bert_model_tester = TFBertModelTester(self) + vision_config_and_inputs = clip_model_tester.prepare_config_and_inputs() + text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() + + vision_config, pixel_values = vision_config_and_inputs + + ( + text_config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = text_config_and_inputs + + return { + "text_config": text_config, + "vision_config": vision_config, + "pixel_values": pixel_values, + "attention_mask": input_mask, + "input_ids": input_ids, + "text_token_type_ids": token_type_ids, + "text_sequence_labels": sequence_labels, + "text_token_labels": token_labels, + "text_choice_labels": choice_labels, + } + + +@require_vision +@require_tf +class TFVisionTextDualEncoderIntegrationTest(unittest.TestCase): + @slow + def test_inference(self): + model = TFVisionTextDualEncoderModel.from_pretrained( + "clip-italian/clip-italian", logit_scale_init_value=1.0, from_pt=True + ) + processor = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian") + + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + inputs = processor( + text=["una foto di un gatto", "una foto di un cane"], images=image, padding=True, return_tensors="np" + ) + + outputs = model(**inputs) + + # verify the logits + self.assertEqual(outputs.logits_per_image.shape, (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])) + self.assertEqual( + outputs.logits_per_text.shape, + (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]), + ) + + expected_logits = np.array([[1.2284727, 0.3104122]]) + + self.assertTrue(np.allclose(outputs.logits_per_image.numpy(), expected_logits, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..4a1ee2462e4f6ee5a54404f23f74d95bcbb6e35c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py @@ -0,0 +1,519 @@ +# coding=utf-8 +# 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 VisionTextDualEncoder model. """ + + +import collections +import tempfile +import unittest + +import numpy as np + +from transformers.testing_utils import is_pt_flax_cross_test, require_torch, require_vision, slow, torch_device +from transformers.utils import is_flax_available, is_torch_available, is_vision_available + +from ...test_modeling_common import floats_tensor, ids_tensor, random_attention_mask +from ..bert.test_modeling_bert import BertModelTester +from ..clip.test_modeling_clip import CLIPVisionModelTester +from ..deit.test_modeling_deit import DeiTModelTester +from ..roberta.test_modeling_roberta import RobertaModelTester +from ..vit.test_modeling_vit import ViTModelTester + + +if is_torch_available(): + import torch + + from transformers import ( + BertModel, + CLIPVisionModel, + DeiTModel, + RobertaModel, + VisionTextDualEncoderConfig, + VisionTextDualEncoderModel, + ViTModel, + ) + +if is_flax_available(): + from transformers import FlaxVisionTextDualEncoderModel + from transformers.modeling_flax_pytorch_utils import ( + convert_pytorch_state_dict_to_flax, + load_flax_weights_in_pytorch_model, + ) + +if is_vision_available(): + from PIL import Image + + from transformers import VisionTextDualEncoderProcessor + + +# Inspired by +# https://github.com/rwightman/pytorch-image-models/blob/b9bd960a032c75ca6b808ddeed76bee5f3ed4972/timm/models/layers/helpers.py +# From PyTorch internals +def to_2tuple(x): + if isinstance(x, collections.abc.Iterable): + return x + return (x, x) + + +@require_torch +class VisionTextDualEncoderMixin: + def get_vision_text_model(self, config, text_config): + pass + + def prepare_config_and_inputs(self): + pass + + def get_pretrained_model_and_inputs(self): + pass + + def check_model_from_pretrained_configs( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + config = VisionTextDualEncoderConfig.from_vision_text_configs(vision_config, text_config) + + model = VisionTextDualEncoderModel(config) + model.to(torch_device) + model.eval() + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + + self.assertEqual(output["text_embeds"].shape, (input_ids.shape[0], config.projection_dim)) + self.assertEqual(output["image_embeds"].shape, (pixel_values.shape[0], config.projection_dim)) + + def check_vision_text_dual_encoder_model( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + model = VisionTextDualEncoderModel(vision_model=vision_model, text_model=text_model) + model.to(torch_device) + model.eval() + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + + self.assertEqual(output["text_embeds"].shape, (input_ids.shape[0], model.config.projection_dim)) + self.assertEqual(output["image_embeds"].shape, (pixel_values.shape[0], model.config.projection_dim)) + + def check_vision_text_dual_encoder_from_pretrained( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + kwargs = {"vision_model": vision_model, "text_model": text_model} + model = VisionTextDualEncoderModel.from_vision_text_pretrained(**kwargs) + model.to(torch_device) + model.eval() + + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + + self.assertEqual(output["text_embeds"].shape, (input_ids.shape[0], model.config.projection_dim)) + self.assertEqual(output["image_embeds"].shape, (pixel_values.shape[0], model.config.projection_dim)) + + def check_save_load(self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + model = VisionTextDualEncoderModel(vision_model=vision_model, text_model=text_model) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + out_1 = output[0].cpu().numpy() + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = VisionTextDualEncoderModel.from_pretrained(tmpdirname).eval() + model.to(torch_device) + + after_output = model(input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask) + out_2 = after_output[0].cpu().numpy() + max_diff = np.amax(np.abs(out_2 - out_1)) + self.assertLessEqual(max_diff, 1e-5) + + def check_vision_text_output_attention( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + model = VisionTextDualEncoderModel(vision_model=vision_model, text_model=text_model) + model.to(torch_device) + model.eval() + + output = model( + input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask, output_attentions=True + ) + + vision_attentions = output.vision_model_output.attentions + self.assertEqual(len(vision_attentions), vision_config.num_hidden_layers) + + # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) + image_size = to_2tuple(vision_model.config.image_size) + patch_size = to_2tuple(vision_model.config.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + seq_len = num_patches + 1 + self.assertEqual(vision_attentions[0].shape[-3:], (vision_config.num_attention_heads, seq_len, seq_len)) + + text_attentions = output.text_model_output.attentions + self.assertEqual(len(text_attentions), text_config.num_hidden_layers) + + self.assertEqual( + text_attentions[0].shape[-3:], + (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]), + ) + + def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): + diff = np.abs((a - b)).max() + self.assertLessEqual(diff, tol, f"Difference between torch and flax is {diff} (>= {tol}).") + + def check_pt_flax_equivalence(self, pt_model, fx_model, input_ids, attention_mask, pixel_values, **kwargs): + pt_model.to(torch_device) + pt_model.eval() + + # prepare inputs + inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values} + pt_inputs = inputs_dict + flax_inputs = {k: v.numpy() for k, v in pt_inputs.items()} + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs).to_tuple() + + fx_outputs = fx_model(**flax_inputs).to_tuple() + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output in zip(fx_outputs[:4], pt_outputs[:4]): + self.assert_almost_equals(fx_output, pt_output.numpy(), 4e-2) + + # PT -> Flax + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = FlaxVisionTextDualEncoderModel.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**flax_inputs).to_tuple() + self.assertEqual(len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4], pt_outputs[:4]): + self.assert_almost_equals(fx_output_loaded, pt_output.numpy(), 4e-2) + + # Flax -> PT + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = VisionTextDualEncoderModel.from_pretrained(tmpdirname, from_flax=True) + + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs).to_tuple() + + self.assertEqual(len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output_loaded in zip(fx_outputs[:4], pt_outputs_loaded[:4]): + self.assert_almost_equals(fx_output, pt_output_loaded.numpy(), 4e-2) + + def check_equivalence_pt_to_flax(self, vision_config, text_config, inputs_dict): + config = VisionTextDualEncoderConfig.from_vision_text_configs(vision_config, text_config) + + pt_model = VisionTextDualEncoderModel(config) + fx_model = FlaxVisionTextDualEncoderModel(config) + + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + self.check_pt_flax_equivalence(pt_model, fx_model, **inputs_dict) + + def check_equivalence_flax_to_pt(self, vision_config, text_config, inputs_dict): + config = VisionTextDualEncoderConfig.from_vision_text_configs(vision_config, text_config) + + pt_model = VisionTextDualEncoderModel(config) + fx_model = FlaxVisionTextDualEncoderModel(config) + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + + self.check_pt_flax_equivalence(pt_model, fx_model, **inputs_dict) + + def test_vision_text_dual_encoder_model(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_vision_text_dual_encoder_model(**inputs_dict) + + def test_model_from_pretrained_configs(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_model_from_pretrained_configs(**inputs_dict) + + def test_vision_text_dual_encoder_from_pretrained(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_vision_text_dual_encoder_from_pretrained(**inputs_dict) + + def test_save_load(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_save_load(**inputs_dict) + + def test_vision_text_output_attention(self): + inputs_dict = self.prepare_config_and_inputs() + self.check_vision_text_output_attention(**inputs_dict) + + @is_pt_flax_cross_test + def test_pt_flax_equivalence(self): + config_inputs_dict = self.prepare_config_and_inputs() + vision_config = config_inputs_dict.pop("vision_config") + text_config = config_inputs_dict.pop("text_config") + + inputs_dict = config_inputs_dict + + self.check_equivalence_pt_to_flax(vision_config, text_config, inputs_dict) + self.check_equivalence_flax_to_pt(vision_config, text_config, inputs_dict) + + @slow + def test_real_model_save_load_from_pretrained(self): + model_2, inputs = self.get_pretrained_model_and_inputs() + model_2.to(torch_device) + + with torch.no_grad(): + outputs = model_2(**inputs) + out_2 = outputs[0].cpu().numpy() + + with tempfile.TemporaryDirectory() as tmp_dirname: + model_2.save_pretrained(tmp_dirname) + model_1 = VisionTextDualEncoderModel.from_pretrained(tmp_dirname) + model_1.to(torch_device) + + after_outputs = model_1(**inputs) + out_1 = after_outputs[0].cpu().numpy() + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + +@require_torch +class ViTBertModelTest(VisionTextDualEncoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = VisionTextDualEncoderModel.from_vision_text_pretrained( + "hf-internal-testing/tiny-random-vit", "hf-internal-testing/tiny-bert" + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.vision_model.config.num_channels, + model.vision_model.config.image_size, + model.vision_model.config.image_size, + ] + ) + input_ids = ids_tensor([batch_size, 4], model.text_model.config.vocab_size) + attention_mask = random_attention_mask([batch_size, 4]) + inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} + + return model, inputs + + def get_vision_text_model(self, vision_config, text_config): + vision_model = ViTModel(vision_config).eval() + text_model = BertModel(text_config).eval() + return vision_model, text_model + + def prepare_config_and_inputs(self): + vit_model_tester = ViTModelTester(self) + bert_model_tester = BertModelTester(self) + vision_config_and_inputs = vit_model_tester.prepare_config_and_inputs() + text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() + + vision_config, pixel_values, _ = vision_config_and_inputs + + ( + text_config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = text_config_and_inputs + + return { + "text_config": text_config, + "vision_config": vision_config, + "pixel_values": pixel_values, + "attention_mask": input_mask, + "input_ids": input_ids, + "text_token_type_ids": token_type_ids, + "text_sequence_labels": sequence_labels, + "text_token_labels": token_labels, + "text_choice_labels": choice_labels, + } + + +@require_torch +class DeiTRobertaModelTest(VisionTextDualEncoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = VisionTextDualEncoderModel.from_vision_text_pretrained( + "hf-internal-testing/tiny-random-deit", "hf-internal-testing/tiny-random-roberta" + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.vision_model.config.num_channels, + model.vision_model.config.image_size, + model.vision_model.config.image_size, + ] + ) + input_ids = ids_tensor([batch_size, 4], model.text_model.config.vocab_size) + attention_mask = random_attention_mask([batch_size, 4]) + inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} + + return model, inputs + + def check_vision_text_output_attention( + self, text_config, input_ids, attention_mask, vision_config, pixel_values=None, **kwargs + ): + vision_model, text_model = self.get_vision_text_model(vision_config, text_config) + model = VisionTextDualEncoderModel(vision_model=vision_model, text_model=text_model) + model.to(torch_device) + model.eval() + + output = model( + input_ids=input_ids, pixel_values=pixel_values, attention_mask=attention_mask, output_attentions=True + ) + + vision_attentions = output.vision_model_output.attentions + self.assertEqual(len(vision_attentions), vision_config.num_hidden_layers) + + # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) + image_size = to_2tuple(vision_model.config.image_size) + patch_size = to_2tuple(vision_model.config.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + seq_len = num_patches + 2 + self.assertEqual(vision_attentions[0].shape[-3:], (vision_config.num_attention_heads, seq_len, seq_len)) + + text_attentions = output.text_model_output.attentions + self.assertEqual(len(text_attentions), text_config.num_hidden_layers) + + self.assertEqual( + text_attentions[0].shape[-3:], + (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]), + ) + + def get_vision_text_model(self, vision_config, text_config): + vision_model = DeiTModel(vision_config).eval() + text_model = RobertaModel(text_config).eval() + return vision_model, text_model + + def prepare_config_and_inputs(self): + vit_model_tester = DeiTModelTester(self) + bert_model_tester = RobertaModelTester(self) + vision_config_and_inputs = vit_model_tester.prepare_config_and_inputs() + text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() + + vision_config, pixel_values, _ = vision_config_and_inputs + + ( + text_config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = text_config_and_inputs + + return { + "text_config": text_config, + "vision_config": vision_config, + "pixel_values": pixel_values, + "attention_mask": input_mask, + "input_ids": input_ids, + "text_token_type_ids": token_type_ids, + "text_sequence_labels": sequence_labels, + "text_token_labels": token_labels, + "text_choice_labels": choice_labels, + } + + # skip as DeiT is not available in Flax + def test_pt_flax_equivalence(self): + pass + + +@require_torch +class CLIPVisionBertModelTest(VisionTextDualEncoderMixin, unittest.TestCase): + def get_pretrained_model_and_inputs(self): + model = VisionTextDualEncoderModel.from_vision_text_pretrained( + "hf-internal-testing/tiny-random-clip", "hf-internal-testing/tiny-bert" + ) + batch_size = 13 + pixel_values = floats_tensor( + [ + batch_size, + model.vision_model.config.num_channels, + model.vision_model.config.image_size, + model.vision_model.config.image_size, + ] + ) + input_ids = ids_tensor([batch_size, 4], model.text_model.config.vocab_size) + attention_mask = random_attention_mask([batch_size, 4]) + inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} + + return model, inputs + + def get_vision_text_model(self, vision_config, text_config): + vision_model = CLIPVisionModel(vision_config).eval() + text_model = BertModel(text_config).eval() + return vision_model, text_model + + def prepare_config_and_inputs(self): + clip_model_tester = CLIPVisionModelTester(self) + bert_model_tester = BertModelTester(self) + vision_config_and_inputs = clip_model_tester.prepare_config_and_inputs() + text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() + + vision_config, pixel_values = vision_config_and_inputs + + ( + text_config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = text_config_and_inputs + + return { + "text_config": text_config, + "vision_config": vision_config, + "pixel_values": pixel_values, + "attention_mask": input_mask, + "input_ids": input_ids, + "text_token_type_ids": token_type_ids, + "text_sequence_labels": sequence_labels, + "text_token_labels": token_labels, + "text_choice_labels": choice_labels, + } + + +@require_vision +@require_torch +class VisionTextDualEncoderIntegrationTest(unittest.TestCase): + @slow + def test_inference(self): + model = VisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian", logit_scale_init_value=1.0) + processor = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian") + + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + inputs = processor( + text=["una foto di un gatto", "una foto di un cane"], images=image, padding=True, return_tensors="pt" + ) + + outputs = model(**inputs) + + # verify the logits + self.assertEqual(outputs.logits_per_image.shape, (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])) + self.assertEqual( + outputs.logits_per_text.shape, + (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]), + ) + + expected_logits = torch.tensor([[1.2284727, 0.3104122]]) + + self.assertTrue(torch.allclose(outputs.logits_per_image, expected_logits, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_processor_vision_text_dual_encoder.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_processor_vision_text_dual_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..aebe723bd5fd7f8c41070a824535fc3564fd504a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vision_text_dual_encoder/test_processor_vision_text_dual_encoder.py @@ -0,0 +1,181 @@ +# Copyright 2021 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 shutil +import tempfile +import unittest + +import numpy as np + +from transformers import BertTokenizerFast +from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer +from transformers.testing_utils import require_tokenizers, require_vision +from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available + + +if is_vision_available(): + from PIL import Image + + from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor + + +@require_tokenizers +@require_vision +class VisionTextDualEncoderProcessorTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"] # fmt: skip + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + image_processor_map = { + "do_resize": True, + "size": {"height": 18, "width": 18}, + "do_normalize": True, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + } + self.image_processor_file = os.path.join(self.tmpdirname, IMAGE_PROCESSOR_NAME) + with open(self.image_processor_file, "w", encoding="utf-8") as fp: + json.dump(image_processor_map, fp) + + def get_tokenizer(self, **kwargs): + return BertTokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def get_image_processor(self, **kwargs): + return ViTImageProcessor.from_pretrained(self.tmpdirname, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def prepare_image_inputs(self): + """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, + or a list of PyTorch tensors if one specifies torchify=True. + """ + + image_inputs = [np.random.randint(255, size=(3, 30, 400), dtype=np.uint8)] + + image_inputs = [Image.fromarray(np.moveaxis(x, 0, -1)) for x in image_inputs] + + return image_inputs + + def test_save_load_pretrained_default(self): + tokenizer = self.get_tokenizer() + image_processor = self.get_image_processor() + + processor = VisionTextDualEncoderProcessor(tokenizer=tokenizer, image_processor=image_processor) + + processor.save_pretrained(self.tmpdirname) + processor = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) + self.assertIsInstance(processor.tokenizer, (BertTokenizer, BertTokenizerFast)) + + self.assertEqual(processor.image_processor.to_json_string(), image_processor.to_json_string()) + self.assertIsInstance(processor.image_processor, ViTImageProcessor) + + def test_save_load_pretrained_additional_features(self): + processor = VisionTextDualEncoderProcessor( + tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor() + ) + processor.save_pretrained(self.tmpdirname) + + tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)") + image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0) + + processor = VisionTextDualEncoderProcessor.from_pretrained( + self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0 + ) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) + self.assertIsInstance(processor.tokenizer, (BertTokenizer, BertTokenizerFast)) + + self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.image_processor, ViTImageProcessor) + + def test_image_processor(self): + image_processor = self.get_image_processor() + tokenizer = self.get_tokenizer() + + processor = VisionTextDualEncoderProcessor(tokenizer=tokenizer, image_processor=image_processor) + + image_input = self.prepare_image_inputs() + + input_feat_extract = image_processor(image_input, return_tensors="np") + input_processor = processor(images=image_input, return_tensors="np") + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_tokenizer(self): + image_processor = self.get_image_processor() + tokenizer = self.get_tokenizer() + + processor = VisionTextDualEncoderProcessor(tokenizer=tokenizer, image_processor=image_processor) + + input_str = "lower newer" + + encoded_processor = processor(text=input_str) + + encoded_tok = tokenizer(input_str) + + for key in encoded_tok.keys(): + self.assertListEqual(encoded_tok[key], encoded_processor[key]) + + def test_processor(self): + image_processor = self.get_image_processor() + tokenizer = self.get_tokenizer() + + processor = VisionTextDualEncoderProcessor(tokenizer=tokenizer, image_processor=image_processor) + + input_str = "lower newer" + image_input = self.prepare_image_inputs() + + inputs = processor(text=input_str, images=image_input) + + self.assertListEqual(list(inputs.keys()), ["input_ids", "token_type_ids", "attention_mask", "pixel_values"]) + + # test if it raises when no input is passed + with self.assertRaises(ValueError): + processor() + + def test_tokenizer_decode(self): + image_processor = self.get_image_processor() + tokenizer = self.get_tokenizer() + + processor = VisionTextDualEncoderProcessor(tokenizer=tokenizer, image_processor=image_processor) + + predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] + + decoded_processor = processor.batch_decode(predicted_ids) + decoded_tok = tokenizer.batch_decode(predicted_ids) + + self.assertListEqual(decoded_tok, decoded_processor) + + def test_model_input_names(self): + image_processor = self.get_image_processor() + tokenizer = self.get_tokenizer() + + processor = VisionTextDualEncoderProcessor(tokenizer=tokenizer, image_processor=image_processor) + + input_str = "lower newer" + image_input = self.prepare_image_inputs() + + inputs = processor(text=input_str, images=image_input) + + self.assertListEqual(list(inputs.keys()), processor.model_input_names) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/visual_bert/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/visual_bert/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/visual_bert/test_modeling_visual_bert.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/visual_bert/test_modeling_visual_bert.py new file mode 100644 index 0000000000000000000000000000000000000000..c366e9145ea7c1812ddf17ad241be534f4c4c669 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/visual_bert/test_modeling_visual_bert.py @@ -0,0 +1,709 @@ +# coding=utf-8 +# 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 VisualBERT model. """ + +import copy +import unittest + +from transformers import VisualBertConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + VisualBertForMultipleChoice, + VisualBertForPreTraining, + VisualBertForQuestionAnswering, + VisualBertForRegionToPhraseAlignment, + VisualBertForVisualReasoning, + VisualBertModel, + ) + from transformers.models.visual_bert.modeling_visual_bert import VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST + + +class VisualBertModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + visual_seq_length=5, + is_training=True, + use_attention_mask=True, + use_visual_attention_mask=True, + use_token_type_ids=True, + use_visual_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + visual_embedding_dim=20, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.visual_seq_length = visual_seq_length + self.is_training = is_training + self.use_attention_mask = use_attention_mask + self.use_visual_attention_mask = use_visual_attention_mask + self.use_token_type_ids = use_token_type_ids + self.use_visual_token_type_ids = use_visual_token_type_ids + 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.visual_embedding_dim = visual_embedding_dim + self.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def get_config(self): + return VisualBertConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + visual_embedding_dim=self.visual_embedding_dim, + num_labels=self.num_labels, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + def prepare_config_and_inputs_for_common(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + visual_embeds = floats_tensor([self.batch_size, self.visual_seq_length, self.visual_embedding_dim]) + + attention_mask = None + if self.use_attention_mask: + attention_mask = torch.ones((self.batch_size, self.seq_length), dtype=torch.long, device=torch_device) + + visual_attention_mask = None + if self.use_visual_attention_mask: + visual_attention_mask = torch.ones( + (self.batch_size, self.visual_seq_length), dtype=torch.long, device=torch_device + ) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + visual_token_type_ids = None + if self.use_visual_token_type_ids: + visual_token_type_ids = ids_tensor([self.batch_size, self.visual_seq_length], self.type_vocab_size) + + config = self.get_config() + return config, { + "input_ids": input_ids, + "token_type_ids": token_type_ids, + "attention_mask": attention_mask, + "visual_embeds": visual_embeds, + "visual_token_type_ids": visual_token_type_ids, + "visual_attention_mask": visual_attention_mask, + } + + def prepare_config_and_inputs_for_pretraining(self): + masked_lm_labels = None + sentence_image_labels = None + + if self.use_labels: + masked_lm_labels = ids_tensor([self.batch_size, self.seq_length + self.visual_seq_length], self.vocab_size) + sentence_image_labels = ids_tensor( + [self.batch_size], + self.type_sequence_label_size, + ) + + config, input_dict = self.prepare_config_and_inputs_for_common() + + input_dict.update({"labels": masked_lm_labels, "sentence_image_labels": sentence_image_labels}) + + return config, input_dict + + def prepare_config_and_inputs_for_multiple_choice(self): + input_ids = ids_tensor([self.batch_size, self.num_choices, self.seq_length], self.vocab_size) + visual_embeds = floats_tensor( + [self.batch_size, self.num_choices, self.visual_seq_length, self.visual_embedding_dim] + ) + + attention_mask = None + if self.use_attention_mask: + attention_mask = torch.ones( + (self.batch_size, self.num_choices, self.seq_length), dtype=torch.long, device=torch_device + ) + + visual_attention_mask = None + if self.use_visual_attention_mask: + visual_attention_mask = torch.ones( + (self.batch_size, self.num_choices, self.visual_seq_length), dtype=torch.long, device=torch_device + ) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.num_choices, self.seq_length], self.type_vocab_size) + + visual_token_type_ids = None + if self.use_visual_token_type_ids: + visual_token_type_ids = ids_tensor( + [self.batch_size, self.num_choices, self.visual_seq_length], self.type_vocab_size + ) + + labels = None + + if self.use_labels: + labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + return config, { + "input_ids": input_ids, + "token_type_ids": token_type_ids, + "attention_mask": attention_mask, + "visual_embeds": visual_embeds, + "visual_token_type_ids": visual_token_type_ids, + "visual_attention_mask": visual_attention_mask, + "labels": labels, + } + + def prepare_config_and_inputs_for_vqa(self): + vqa_labels = None + + if self.use_labels: + vqa_labels = floats_tensor([self.batch_size, self.num_labels]) + + config, input_dict = self.prepare_config_and_inputs_for_common() + + input_dict.update({"labels": vqa_labels}) + return config, input_dict + + def prepare_config_and_inputs_for_nlvr(self): + nlvr_labels = None + + if self.use_labels: + nlvr_labels = ids_tensor([self.batch_size], self.num_labels) + + config, input_dict = self.prepare_config_and_inputs_for_common() + + input_dict.update({"labels": nlvr_labels}) + return config, input_dict + + def prepare_config_and_inputs_for_flickr(self): + region_to_phrase_position = torch.cat( + ( + ids_tensor([self.batch_size, self.seq_length], self.visual_seq_length), + torch.ones(self.batch_size, self.visual_seq_length, dtype=torch.long, device=torch_device) * -1, + ), + dim=-1, + ) + flickr_labels = None + if self.use_labels: + flickr_labels = floats_tensor( + [self.batch_size, self.seq_length + self.visual_seq_length, self.visual_seq_length] + ) + + config, input_dict = self.prepare_config_and_inputs_for_common() + + input_dict.update({"region_to_phrase_position": region_to_phrase_position, "labels": flickr_labels}) + return config, input_dict + + def create_and_check_model(self, config, input_dict): + model = VisualBertModel(config=config) + model.to(torch_device) + model.eval() + result = model(**input_dict) + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.seq_length + self.visual_seq_length, self.hidden_size), + ) + + def create_and_check_for_pretraining(self, config, input_dict): + model = VisualBertForPreTraining(config=config) + model.to(torch_device) + model.eval() + result = model(**input_dict) + self.parent.assertEqual( + result.prediction_logits.shape, + (self.batch_size, self.seq_length + self.visual_seq_length, self.vocab_size), + ) + + def create_and_check_for_vqa(self, config, input_dict): + model = VisualBertForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model(**input_dict) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_multiple_choice(self, config, input_dict): + model = VisualBertForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + result = model(**input_dict) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def create_and_check_for_nlvr(self, config, input_dict): + model = VisualBertForVisualReasoning(config=config) + model.to(torch_device) + model.eval() + result = model(**input_dict) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_flickr(self, config, input_dict): + model = VisualBertForRegionToPhraseAlignment(config=config) + model.to(torch_device) + model.eval() + result = model(**input_dict) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.seq_length + self.visual_seq_length, self.visual_seq_length) + ) + + +@require_torch +class VisualBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + VisualBertModel, + VisualBertForMultipleChoice, + VisualBertForVisualReasoning, + VisualBertForRegionToPhraseAlignment, + VisualBertForQuestionAnswering, + VisualBertForPreTraining, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = {"feature-extraction": VisualBertModel} if is_torch_available() else {} + test_torchscript = False + test_pruning = False + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = copy.deepcopy(inputs_dict) + if model_class == VisualBertForMultipleChoice: + for key in inputs_dict.keys(): + value = inputs_dict[key] + if isinstance(value, torch.Tensor) and value.ndim > 1: + if key != "visual_embeds": + inputs_dict[key] = ( + inputs_dict[key].unsqueeze(1).expand(-1, self.model_tester.num_choices, -1).contiguous() + ) + else: + inputs_dict[key] = ( + inputs_dict[key] + .unsqueeze(1) + .expand(-1, self.model_tester.num_choices, -1, self.model_tester.visual_embedding_dim) + .contiguous() + ) + + elif model_class == VisualBertForRegionToPhraseAlignment: + total_length = self.model_tester.seq_length + self.model_tester.visual_seq_length + batch_size = self.model_tester.batch_size + inputs_dict["region_to_phrase_position"] = torch.zeros( + (batch_size, total_length), + dtype=torch.long, + device=torch_device, + ) + + if return_labels: + if model_class == VisualBertForMultipleChoice: + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + elif model_class == VisualBertForPreTraining: + total_length = self.model_tester.seq_length + self.model_tester.visual_seq_length + batch_size = self.model_tester.batch_size + inputs_dict["labels"] = torch.zeros( + (batch_size, total_length), + dtype=torch.long, + device=torch_device, + ) + inputs_dict["sentence_image_labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + + # Flickr expects float labels + elif model_class == VisualBertForRegionToPhraseAlignment: + batch_size = self.model_tester.batch_size + total_length = self.model_tester.seq_length + self.model_tester.visual_seq_length + + inputs_dict["labels"] = torch.ones( + ( + batch_size, + total_length, + self.model_tester.visual_seq_length, + ), + dtype=torch.float, + device=torch_device, + ) + + # VQA expects float labels + elif model_class == VisualBertForQuestionAnswering: + inputs_dict["labels"] = torch.ones( + (self.model_tester.batch_size, self.model_tester.num_labels), + dtype=torch.float, + device=torch_device, + ) + + elif model_class == VisualBertForVisualReasoning: + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size), dtype=torch.long, device=torch_device + ) + + return inputs_dict + + def setUp(self): + self.model_tester = VisualBertModelTester(self) + self.config_tester = ConfigTester(self, config_class=VisualBertConfig, hidden_size=37) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + visual_seq_len = getattr(self.model_tester, "visual_seq_length", None) + + encoder_seq_length = (seq_len if seq_len is not None else 0) + ( + visual_seq_len if visual_seq_len is not None else 0 + ) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + chunk_length = getattr(self.model_tester, "chunk_length", None) + if chunk_length is not None and hasattr(self.model_tester, "num_hashes"): + encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + if chunk_length is not None: + self.assertListEqual( + list(attentions[0].shape[-4:]), + [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length], + ) + else: + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + elif self.is_encoder_decoder: + added_hidden_states = 2 + else: + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + if chunk_length is not None: + self.assertListEqual( + list(self_attentions[0].shape[-4:]), + [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length], + ) + else: + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + if hasattr(self.model_tester, "chunk_length") and self.model_tester.chunk_length > 1: + seq_length = seq_length * self.model_tester.chunk_length + else: + seq_length = self.model_tester.seq_length + self.model_tester.visual_seq_length + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_for_pretraining(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_pretraining() + self.model_tester.create_and_check_for_pretraining(*config_and_inputs) + + def test_model_for_vqa(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_vqa() + self.model_tester.create_and_check_for_vqa(*config_and_inputs) + + def test_model_for_nlvr(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_nlvr() + self.model_tester.create_and_check_for_nlvr(*config_and_inputs) + + def test_model_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_multiple_choice() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_model_for_flickr(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_flickr() + self.model_tester.create_and_check_for_flickr(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = VisualBertModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + +@require_torch +class VisualBertModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_vqa_coco_pre(self): + model = VisualBertForPreTraining.from_pretrained("uclanlp/visualbert-vqa-coco-pre") + + input_ids = torch.tensor([1, 2, 3, 4, 5, 6], dtype=torch.long).reshape(1, -1) + token_type_ids = torch.tensor([0, 0, 0, 1, 1, 1], dtype=torch.long).reshape(1, -1) + visual_embeds = torch.ones(size=(1, 10, 2048), dtype=torch.float32) * 0.5 + visual_token_type_ids = torch.ones(size=(1, 10), dtype=torch.long) + attention_mask = torch.tensor([1] * 6).reshape(1, -1) + visual_attention_mask = torch.tensor([1] * 10).reshape(1, -1) + + with torch.no_grad(): + output = model( + input_ids=input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + visual_embeds=visual_embeds, + visual_attention_mask=visual_attention_mask, + visual_token_type_ids=visual_token_type_ids, + ) + + vocab_size = 30522 + + expected_shape = torch.Size((1, 16, vocab_size)) + self.assertEqual(output.prediction_logits.shape, expected_shape) + + expected_slice = torch.tensor( + [[[-5.1858, -5.1903, -4.9142], [-6.2214, -5.9238, -5.8381], [-6.3027, -5.9939, -5.9297]]] + ) + + self.assertTrue(torch.allclose(output.prediction_logits[:, :3, :3], expected_slice, atol=1e-4)) + + expected_shape_2 = torch.Size((1, 2)) + self.assertEqual(output.seq_relationship_logits.shape, expected_shape_2) + + expected_slice_2 = torch.tensor([[0.7393, 0.1754]]) + + self.assertTrue(torch.allclose(output.seq_relationship_logits, expected_slice_2, atol=1e-4)) + + @slow + def test_inference_vqa(self): + model = VisualBertForQuestionAnswering.from_pretrained("uclanlp/visualbert-vqa") + + input_ids = torch.tensor([1, 2, 3, 4, 5, 6], dtype=torch.long).reshape(1, -1) + token_type_ids = torch.tensor([0, 0, 0, 1, 1, 1], dtype=torch.long).reshape(1, -1) + visual_embeds = torch.ones(size=(1, 10, 2048), dtype=torch.float32) * 0.5 + visual_token_type_ids = torch.ones(size=(1, 10), dtype=torch.long) + attention_mask = torch.tensor([1] * 6).reshape(1, -1) + visual_attention_mask = torch.tensor([1] * 10).reshape(1, -1) + + with torch.no_grad(): + output = model( + input_ids=input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + visual_embeds=visual_embeds, + visual_attention_mask=visual_attention_mask, + visual_token_type_ids=visual_token_type_ids, + ) + + # vocab_size = 30522 + + expected_shape = torch.Size((1, 3129)) + self.assertEqual(output.logits.shape, expected_shape) + + expected_slice = torch.tensor( + [[-8.9898, 3.0803, -1.8016, 2.4542, -8.3420, -2.0224, -3.3124, -4.4139, -3.1491, -3.8997]] + ) + + self.assertTrue(torch.allclose(output.logits[:, :10], expected_slice, atol=1e-4)) + + @slow + def test_inference_nlvr(self): + model = VisualBertForVisualReasoning.from_pretrained("uclanlp/visualbert-nlvr2") + + input_ids = torch.tensor([1, 2, 3, 4, 5, 6], dtype=torch.long).reshape(1, -1) + token_type_ids = torch.tensor([0, 0, 0, 1, 1, 1], dtype=torch.long).reshape(1, -1) + visual_embeds = torch.ones(size=(1, 10, 1024), dtype=torch.float32) * 0.5 + visual_token_type_ids = torch.ones(size=(1, 10), dtype=torch.long) + attention_mask = torch.tensor([1] * 6).reshape(1, -1) + visual_attention_mask = torch.tensor([1] * 10).reshape(1, -1) + + with torch.no_grad(): + output = model( + input_ids=input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + visual_embeds=visual_embeds, + visual_attention_mask=visual_attention_mask, + visual_token_type_ids=visual_token_type_ids, + ) + + # vocab_size = 30522 + + expected_shape = torch.Size((1, 2)) + self.assertEqual(output.logits.shape, expected_shape) + + expected_slice = torch.tensor([[-1.1436, 0.8900]]) + + self.assertTrue(torch.allclose(output.logits, expected_slice, atol=1e-4)) + + @slow + def test_inference_vcr(self): + model = VisualBertForMultipleChoice.from_pretrained("uclanlp/visualbert-vcr") + + input_ids = torch.tensor([[[1, 2, 3, 4, 5, 6] for i in range(4)]], dtype=torch.long) + attention_mask = torch.ones_like(input_ids) + token_type_ids = torch.ones_like(input_ids) + + visual_embeds = torch.ones(size=(1, 4, 10, 512), dtype=torch.float32) * 0.5 + visual_token_type_ids = torch.ones(size=(1, 4, 10), dtype=torch.long) + visual_attention_mask = torch.ones_like(visual_token_type_ids) + + with torch.no_grad(): + output = model( + input_ids=input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + visual_embeds=visual_embeds, + visual_attention_mask=visual_attention_mask, + visual_token_type_ids=visual_token_type_ids, + ) + + # vocab_size = 30522 + + expected_shape = torch.Size((1, 4)) + self.assertEqual(output.logits.shape, expected_shape) + + expected_slice = torch.tensor([[-7.7697, -7.7697, -7.7697, -7.7697]]) + + self.assertTrue(torch.allclose(output.logits, expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_image_processing_vit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_image_processing_vit.py new file mode 100644 index 0000000000000000000000000000000000000000..c1c22c0a800a40a9c9a1c1ddf3ce7ceb6559ba94 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_image_processing_vit.py @@ -0,0 +1,106 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 unittest + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs + + +if is_vision_available(): + from transformers import ViTImageProcessor + + +class ViTImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + image_size=18, + min_resolution=30, + max_resolution=400, + do_resize=True, + size=None, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + ): + size = size if size is not None else {"height": 18, "width": 18} + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.image_size = image_size + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + + def prepare_image_processor_dict(self): + return { + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_normalize": self.do_normalize, + "do_resize": self.do_resize, + "size": self.size, + } + + def expected_output_image_shape(self, images): + return self.num_channels, self.size["height"], self.size["width"] + + def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_image_inputs( + batch_size=self.batch_size, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class ViTImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = ViTImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = ViTImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "size")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"height": 18, "width": 18}) + + image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42) + self.assertEqual(image_processor.size, {"height": 42, "width": 42}) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_flax_vit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_flax_vit.py new file mode 100644 index 0000000000000000000000000000000000000000..af56f4717b888f86ea8e0f3cb74d65f39e66554d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_flax_vit.py @@ -0,0 +1,187 @@ +# Copyright 2021 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 inspect +import unittest + +import numpy as np + +from transformers import ViTConfig, is_flax_available +from transformers.testing_utils import require_flax, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor + + +if is_flax_available(): + import jax + + from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel + + +class FlaxViTModelTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=13, + image_size=30, + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + + # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = num_patches + 1 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + config = ViTConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + return config, pixel_values + + def create_and_check_model(self, config, pixel_values): + model = FlaxViTModel(config=config) + result = model(pixel_values) + # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + image_size = (self.image_size, self.image_size) + patch_size = (self.patch_size, self.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size)) + + def create_and_check_for_image_classification(self, config, pixel_values): + config.num_labels = self.type_sequence_label_size + model = FlaxViTForImageClassification(config=config) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + # test greyscale images + config.num_channels = 1 + model = FlaxViTForImageClassification(config) + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + pixel_values, + ) = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_flax +class FlaxViTModelTest(FlaxModelTesterMixin, unittest.TestCase): + all_model_classes = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () + + def setUp(self) -> None: + self.model_tester = FlaxViTModelTester(self) + self.config_tester = ConfigTester(self, config_class=ViTConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + # We need to override this test because ViT's forward signature is different than text models. + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.__call__) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + # We need to override this test because ViT expects pixel_values instead of input_ids + def test_jit_compilation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def model_jitted(pixel_values, **kwargs): + return model(pixel_values=pixel_values, **kwargs) + + with self.subTest("JIT Enabled"): + jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + @slow + def test_model_from_pretrained(self): + for model_class_name in self.all_model_classes: + model = model_class_name.from_pretrained("google/vit-base-patch16-224") + outputs = model(np.ones((1, 3, 224, 224))) + self.assertIsNotNone(outputs) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_tf_vit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_tf_vit.py new file mode 100644 index 0000000000000000000000000000000000000000..0db27dfb2ebf9397d74e37dd02034f5008d0b297 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_tf_vit.py @@ -0,0 +1,251 @@ +# coding=utf-8 +# 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 TensorFlow ViT model. """ + + +from __future__ import annotations + +import inspect +import unittest + +from transformers import ViTConfig +from transformers.testing_utils import require_tf, require_vision, slow +from transformers.utils import cached_property, is_tf_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import TFViTForImageClassification, TFViTModel + + +if is_vision_available(): + from PIL import Image + + from transformers import ViTImageProcessor + + +class TFViTModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=30, + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + num_labels=3, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.scope = scope + + # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = num_patches + 1 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return ViTConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = TFViTModel(config=config) + result = model(pixel_values, training=False) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + # Test with an image with different size than the one specified in config. + image_size = self.image_size // 2 + pixel_values = pixel_values[:, :, :image_size, :image_size] + result = model(pixel_values, interpolate_pos_encoding=True, training=False) + seq_length = (image_size // self.patch_size) ** 2 + 1 + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, seq_length, self.hidden_size)) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.type_sequence_label_size + model = TFViTForImageClassification(config) + result = model(pixel_values, labels=labels, training=False) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + # Test with an image with different size than the one specified in config. + image_size = self.image_size // 2 + pixel_values = pixel_values[:, :, :image_size, :image_size] + result = model(pixel_values, interpolate_pos_encoding=True, training=False) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + # test greyscale images + config.num_channels = 1 + model = TFViTForImageClassification(config) + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_tf +class TFViTModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_tf_common.py, as ViT does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () + pipeline_model_mapping = ( + {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification} + if is_tf_available() + else {} + ) + + test_resize_embeddings = False + test_head_masking = False + test_onnx = False + + def setUp(self): + self.model_tester = TFViTModelTester(self) + self.config_tester = ConfigTester(self, config_class=ViTConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="ViT does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="ViT does not use inputs_embeds") + def test_graph_mode_with_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (tf.keras.layers.Layer)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, tf.keras.layers.Layer)) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + model = TFViTModel.from_pretrained("google/vit-base-patch16-224") + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_tf +@require_vision +class TFViTModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224") if is_vision_available() else None + + @slow + def test_inference_image_classification_head(self): + model = TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224") + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="tf") + + # forward pass + outputs = model(**inputs) + + # verify the logits + expected_shape = tf.TensorShape((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = tf.constant([-0.2744, 0.8215, -0.0836]) + + tf.debugging.assert_near(outputs.logits[0, :3], expected_slice, atol=1e-4) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_vit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_vit.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9a632a3719d47cf479d8fbf91b29d7e72bc3a4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit/test_modeling_vit.py @@ -0,0 +1,322 @@ +# coding=utf-8 +# 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 ViT model. """ + + +import unittest + +from transformers import ViTConfig +from transformers.testing_utils import ( + require_accelerate, + require_torch, + require_torch_accelerator, + require_torch_fp16, + require_vision, + slow, + torch_device, +) +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel + from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import ViTImageProcessor + + +class ViTModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=30, + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + scope=None, + encoder_stride=2, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.scope = scope + self.encoder_stride = encoder_stride + + # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = num_patches + 1 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return ViTConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + encoder_stride=self.encoder_stride, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = ViTModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels): + model = ViTForMaskedImageModeling(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual( + result.reconstruction.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) + ) + + # test greyscale images + config.num_channels = 1 + model = ViTForMaskedImageModeling(config) + model.to(torch_device) + model.eval() + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.reconstruction.shape, (self.batch_size, 1, self.image_size, self.image_size)) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.type_sequence_label_size + model = ViTForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + # test greyscale images + config.num_channels = 1 + model = ViTForImageClassification(config) + model.to(torch_device) + model.eval() + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + pixel_values, + labels, + ) = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class ViTModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as ViT does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = ( + ( + ViTModel, + ViTForImageClassification, + ViTForMaskedImageModeling, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + {"feature-extraction": ViTModel, "image-classification": ViTForImageClassification} + if is_torch_available() + else {} + ) + fx_compatible = True + + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = ViTModelTester(self) + self.config_tester = ConfigTester(self, config_class=ViTConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="ViT does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_image_modeling(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = ViTModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class ViTModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224") if is_vision_available() else None + + @slow + def test_inference_image_classification_head(self): + model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224").to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-0.2744, 0.8215, -0.0836]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_interpolate_pos_encoding(self): + # ViT models have an `interpolate_pos_encoding` argument in their forward method, + # allowing to interpolate the pre-trained position embeddings in order to use + # the model on higher resolutions. The DINO model by Facebook AI leverages this + # to visualize self-attention on higher resolution images. + model = ViTModel.from_pretrained("facebook/dino-vits8").to(torch_device) + + image_processor = ViTImageProcessor.from_pretrained("facebook/dino-vits8", size=480) + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt") + pixel_values = inputs.pixel_values.to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(pixel_values, interpolate_pos_encoding=True) + + # verify the logits + expected_shape = torch.Size((1, 3601, 384)) + self.assertEqual(outputs.last_hidden_state.shape, expected_shape) + + expected_slice = torch.tensor( + [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] + ).to(torch_device) + + self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4)) + + @slow + @require_accelerate + @require_torch_accelerator + @require_torch_fp16 + def test_inference_fp16(self): + r""" + A small test to make sure that inference work in half precision without any problem. + """ + model = ViTModel.from_pretrained("facebook/dino-vits8", torch_dtype=torch.float16, device_map="auto") + image_processor = self.default_image_processor + + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt") + pixel_values = inputs.pixel_values.to(torch_device) + + # forward pass to make sure inference works in fp16 + with torch.no_grad(): + _ = model(pixel_values) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_hybrid/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_hybrid/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_hybrid/test_modeling_vit_hybrid.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_hybrid/test_modeling_vit_hybrid.py new file mode 100644 index 0000000000000000000000000000000000000000..870a4c83358315aadcf4315e634ae759887e0673 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_hybrid/test_modeling_vit_hybrid.py @@ -0,0 +1,277 @@ +# coding=utf-8 +# Copyright 2022 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 ViT Hybrid model. """ + + +import unittest + +from transformers import ViTHybridConfig +from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel + from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + +class ViTHybridModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=64, + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + backbone_featmap_shape=[1, 16, 4, 4], + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.scope = scope + self.backbone_featmap_shape = backbone_featmap_shape + + # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) + # the number of patches is based on the feature map of the backbone, which by default uses an output stride + # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size + num_patches = (self.image_size // 32) ** 2 + self.seq_length = num_patches + 1 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + backbone_config = { + "global_padding": "same", + "layer_type": "bottleneck", + "depths": [3, 4, 9], + "out_features": ["stage1", "stage2", "stage3"], + "embedding_dynamic_padding": True, + "hidden_sizes": [4, 8, 16, 32], + "num_groups": 2, + } + + return ViTHybridConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + backbone_featmap_shape=self.backbone_featmap_shape, + backbone_config=backbone_config, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = ViTHybridModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.type_sequence_label_size + model = ViTHybridForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class ViTHybridModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as ViT does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": ViTHybridModel, "image-classification": ViTHybridForImageClassification} + if is_torch_available() + else {} + ) + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + model_split_percents = [0.5, 0.9] + + def setUp(self): + self.model_tester = ViTHybridModelTester(self) + self.config_tester = ConfigTester(self, config_class=ViTHybridConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="ViT does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + # Skip the check for the backbone + for name, module in model.named_modules(): + if module.__class__.__name__ == "ViTHybridPatchEmbeddings": + backbone_params = [f"{name}.{key}" for key in module.state_dict().keys()] + break + + for name, param in model.named_parameters(): + if param.requires_grad: + if name in backbone_params: + continue + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + @slow + def test_model_from_pretrained(self): + for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = ViTHybridModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class ViTModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ( + ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]) + if is_vision_available() + else None + ) + + @slow + def test_inference_image_classification_head(self): + model = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( + torch_device + ) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([-1.9090, -0.4993, -0.2389]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) + + @slow + @require_accelerate + def test_accelerate_inference(self): + image_processor = ViTHybridImageProcessor.from_pretrained("google/vit-hybrid-base-bit-384") + model = ViTHybridForImageClassification.from_pretrained("google/vit-hybrid-base-bit-384", device_map="auto") + + image = prepare_img() + + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + outputs = model(**inputs) + logits = outputs.logits + # model predicts one of the 1000 ImageNet classes + predicted_class_idx = logits.argmax(-1).item() + + self.assertTrue(model.config.id2label[predicted_class_idx], "tabby, tabby cat") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_mae/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_mae/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_mae/test_modeling_tf_vit_mae.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_mae/test_modeling_tf_vit_mae.py new file mode 100644 index 0000000000000000000000000000000000000000..8f6064e01650e0d1b58fa5a15c42ea712fad8896 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_mae/test_modeling_tf_vit_mae.py @@ -0,0 +1,458 @@ +# coding=utf-8 +# Copyright 2022 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 TensorFlow ViTMAE model. """ + + +from __future__ import annotations + +import copy +import inspect +import json +import math +import os +import tempfile +import unittest +from importlib import import_module + +import numpy as np + +from transformers import ViTMAEConfig +from transformers.file_utils import cached_property, is_tf_available, is_vision_available +from transformers.testing_utils import require_tf, require_vision, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import TFViTMAEForPreTraining, TFViTMAEModel + + +if is_vision_available(): + from PIL import Image + + from transformers import ViTImageProcessor + + +class TFViTMAEModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=30, + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + num_labels=3, + mask_ratio=0.6, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.mask_ratio = mask_ratio + self.scope = scope + + # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above + # (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = int(math.ceil((1 - mask_ratio) * (num_patches + 1))) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return ViTMAEConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + decoder_hidden_size=self.hidden_size, + decoder_num_hidden_layers=self.num_hidden_layers, + decoder_num_attention_heads=self.num_attention_heads, + decoder_intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + mask_ratio=self.mask_ratio, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = TFViTMAEModel(config=config) + result = model(pixel_values, training=False) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_pretraining(self, config, pixel_values, labels): + model = TFViTMAEForPreTraining(config) + result = model(pixel_values, training=False) + # expected sequence length = num_patches + num_patches = (self.image_size // self.patch_size) ** 2 + expected_num_channels = self.patch_size**2 * self.num_channels + self.parent.assertEqual(result.logits.shape, (self.batch_size, num_patches, expected_num_channels)) + + # test greyscale images + config.num_channels = 1 + model = TFViTMAEForPreTraining(config) + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values, training=False) + expected_num_channels = self.patch_size**2 + self.parent.assertEqual(result.logits.shape, (self.batch_size, num_patches, expected_num_channels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + (config, pixel_values, labels) = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_tf +class TFViTMAEModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as ViTMAE does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () + pipeline_model_mapping = {"feature-extraction": TFViTMAEModel} if is_tf_available() else {} + + test_pruning = False + test_onnx = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = TFViTMAEModelTester(self) + self.config_tester = ConfigTester(self, config_class=ViTMAEConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="ViTMAE does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (tf.keras.layers.Layer)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, tf.keras.layers.Layer)) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_pretraining(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_pretraining(*config_and_inputs) + + # overwrite from common since TFViTMAEForPretraining has random masking, we need to fix the noise + # to generate masks during test + def test_keyword_and_dict_args(self): + # make the mask reproducible + np.random.seed(2) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + num_patches = int((config.image_size // config.patch_size) ** 2) + noise = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) + + for model_class in self.all_model_classes: + model = model_class(config) + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs_dict = model(inputs, noise=noise) + + inputs_keywords = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + outputs_keywords = model(**inputs_keywords, noise=noise) + output_dict = outputs_dict[0].numpy() + output_keywords = outputs_keywords[0].numpy() + + self.assertLess(np.sum(np.abs(output_dict - output_keywords)), 1e-6) + + # overwrite from common since TFViTMAEForPretraining has random masking, we need to fix the noise + # to generate masks during test + def test_numpy_arrays_inputs(self): + # make the mask reproducible + np.random.seed(2) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + num_patches = int((config.image_size // config.patch_size) ** 2) + noise = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) + + def prepare_numpy_arrays(inputs_dict): + inputs_np_dict = {} + for k, v in inputs_dict.items(): + if tf.is_tensor(v): + inputs_np_dict[k] = v.numpy() + else: + inputs_np_dict[k] = np.array(k) + + return inputs_np_dict + + for model_class in self.all_model_classes: + model = model_class(config) + + inputs = self._prepare_for_class(inputs_dict, model_class) + inputs_np = prepare_numpy_arrays(inputs) + + output_for_dict_input = model(inputs_np, noise=noise) + output_for_kw_input = model(**inputs_np, noise=noise) + self.assert_outputs_same(output_for_dict_input, output_for_kw_input) + + # overwrite from common since TFViTMAEForPretraining has random masking, we need to fix the noise + # to generate masks during test + def check_pt_tf_models(self, tf_model, pt_model, tf_inputs_dict): + # make masks reproducible + np.random.seed(2) + + num_patches = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2) + noise = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) + tf_noise = tf.constant(noise) + + # Add `noise` argument. + # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument + tf_inputs_dict["noise"] = tf_noise + + super().check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + + # overwrite from common since TFViTMAEForPretraining has random masking, we need to fix the noise + # to generate masks during test + def test_keras_save_load(self): + # make mask reproducible + np.random.seed(2) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + tf_main_layer_classes = { + module_member + for model_class in self.all_model_classes + for module in (import_module(model_class.__module__),) + for module_member_name in dir(module) + if module_member_name.endswith("MainLayer") + # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. + and module_member_name[: -len("MainLayer")] == model_class.__name__[: -len("Model")] + for module_member in (getattr(module, module_member_name),) + if isinstance(module_member, type) + and tf.keras.layers.Layer in module_member.__bases__ + and getattr(module_member, "_keras_serializable", False) + } + + num_patches = int((config.image_size // config.patch_size) ** 2) + noise = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) + noise = tf.convert_to_tensor(noise) + inputs_dict.update({"noise": noise}) + + for main_layer_class in tf_main_layer_classes: + main_layer = main_layer_class(config) + + symbolic_inputs = { + name: tf.keras.Input(tensor.shape[1:], dtype=tensor.dtype) for name, tensor in inputs_dict.items() + } + + model = tf.keras.Model(symbolic_inputs, outputs=main_layer(symbolic_inputs)) + outputs = model(inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + filepath = os.path.join(tmpdirname, "keras_model.h5") + model.save(filepath) + model = tf.keras.models.load_model( + filepath, custom_objects={main_layer_class.__name__: main_layer_class} + ) + assert isinstance(model, tf.keras.Model) + after_outputs = model(inputs_dict) + self.assert_outputs_same(after_outputs, outputs) + + # overwrite from common since TFViTMAEForPretraining has random masking, we need to fix the noise + # to generate masks during test + @slow + def test_save_load(self): + # make mask reproducible + np.random.seed(2) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + num_patches = int((config.image_size // config.patch_size) ** 2) + noise = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) + + for model_class in self.all_model_classes: + model = model_class(config) + model_input = self._prepare_for_class(inputs_dict, model_class) + outputs = model(model_input, noise=noise) + + if model_class.__name__ == "TFViTMAEModel": + out_2 = outputs.last_hidden_state.numpy() + out_2[np.isnan(out_2)] = 0 + else: + out_2 = outputs.logits.numpy() + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, saved_model=False) + model = model_class.from_pretrained(tmpdirname) + after_outputs = model(model_input, noise=noise) + + if model_class.__name__ == "TFViTMAEModel": + out_1 = after_outputs["last_hidden_state"].numpy() + out_1[np.isnan(out_1)] = 0 + else: + out_1 = after_outputs["logits"].numpy() + out_1[np.isnan(out_1)] = 0 + + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + # overwrite from common since TFViTMAEForPretraining has random masking, we need to fix the noise + # to generate masks during test + def test_save_load_config(self): + # make mask reproducible + np.random.seed(2) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + num_patches = int((config.image_size // config.patch_size) ** 2) + noise = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) + + for model_class in self.all_model_classes: + model = model_class(config) + model_inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs = model(model_inputs, noise=noise) + model_config = model.get_config() + # make sure that returned config is jsonifiable, which is required by keras + json.dumps(model_config) + new_model = model_class.from_config(model.get_config()) + # make sure it also accepts a normal config + _ = model_class.from_config(model.config) + _ = new_model(model_inputs) # Build model + new_model.set_weights(model.get_weights()) + after_outputs = new_model(model_inputs, noise=noise) + + self.assert_outputs_same(after_outputs, outputs) + + @unittest.skip( + reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load + to get deterministic results.""" + ) + def test_determinism(self): + pass + + @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""") + def test_model_outputs_equivalence(self): + pass + + @slow + def test_model_from_pretrained(self): + model = TFViTMAEModel.from_pretrained("google/vit-base-patch16-224") + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_tf +@require_vision +class TFViTMAEModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ViTImageProcessor.from_pretrained("facebook/vit-mae-base") if is_vision_available() else None + + @slow + def test_inference_for_pretraining(self): + # make random mask reproducible across the PT and TF model + np.random.seed(2) + + model = TFViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base") + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="tf") + + # prepare a noise vector that will be also used for testing the TF model + # (this way we can ensure that the PT and TF models operate on the same inputs) + vit_mae_config = ViTMAEConfig() + num_patches = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2) + noise = np.random.uniform(size=(1, num_patches)) + + # forward pass + outputs = model(**inputs, noise=noise) + + # verify the logits + expected_shape = tf.convert_to_tensor([1, 196, 768]) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = tf.convert_to_tensor( + [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] + ) + + tf.debugging.assert_near(outputs.logits[0, :3, :3], expected_slice, atol=1e-4) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_mae/test_modeling_vit_mae.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_mae/test_modeling_vit_mae.py new file mode 100644 index 0000000000000000000000000000000000000000..21a66b8a6d92a26597b01ff1b0b61773238512dd --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_mae/test_modeling_vit_mae.py @@ -0,0 +1,322 @@ +# coding=utf-8 +# Copyright 2022 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 ViTMAE model. """ + + +import math +import tempfile +import unittest + +import numpy as np + +from transformers import ViTMAEConfig +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ViTMAEForPreTraining, ViTMAEModel + from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import ViTImageProcessor + + +class ViTMAEModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=30, + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + num_labels=3, + mask_ratio=0.6, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.mask_ratio = mask_ratio + self.scope = scope + + # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above + # (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = int(math.ceil((1 - mask_ratio) * (num_patches + 1))) + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return ViTMAEConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + mask_ratio=self.mask_ratio, + decoder_hidden_size=self.hidden_size, + decoder_intermediate_size=self.intermediate_size, + decoder_num_attention_heads=self.num_attention_heads, + decoder_num_hidden_layers=self.num_hidden_layers, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = ViTMAEModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_pretraining(self, config, pixel_values, labels): + model = ViTMAEForPreTraining(config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + num_patches = (self.image_size // self.patch_size) ** 2 + expected_num_channels = self.patch_size**2 * self.num_channels + self.parent.assertEqual(result.logits.shape, (self.batch_size, num_patches, expected_num_channels)) + + # test greyscale images + config.num_channels = 1 + model = ViTMAEForPreTraining(config) + model.to(torch_device) + model.eval() + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + expected_num_channels = self.patch_size**2 + self.parent.assertEqual(result.logits.shape, (self.batch_size, num_patches, expected_num_channels)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class ViTMAEModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as ViTMAE does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () + pipeline_model_mapping = {"feature-extraction": ViTMAEModel} if is_torch_available() else {} + + test_pruning = False + test_torchscript = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = ViTMAEModelTester(self) + self.config_tester = ConfigTester(self, config_class=ViTMAEConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="ViTMAE does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_pretraining(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_pretraining(*config_and_inputs) + + # overwrite from common since ViTMAEForPretraining has random masking, we need to fix the noise + # to generate masks during test + def check_pt_tf_models(self, tf_model, pt_model, pt_inputs_dict): + # make masks reproducible + np.random.seed(2) + + num_patches = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2) + noise = np.random.uniform(size=(self.model_tester.batch_size, num_patches)) + pt_noise = torch.from_numpy(noise) + + # Add `noise` argument. + # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument + pt_inputs_dict["noise"] = pt_noise + + super().check_pt_tf_models(tf_model, pt_model, pt_inputs_dict) + + def test_save_load(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + # make random mask reproducible + torch.manual_seed(2) + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + out_2 = outputs[0].cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained(tmpdirname) + model.to(torch_device) + # make random mask reproducible + torch.manual_seed(2) + with torch.no_grad(): + after_outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + # Make sure we don't have nans + out_1 = after_outputs[0].cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + @unittest.skip( + reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load + to get deterministic results.""" + ) + def test_determinism(self): + pass + + @unittest.skip( + reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load + to get deterministic results.""" + ) + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip( + reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load + to get deterministic results.""" + ) + def test_save_load_fast_init_to_base(self): + pass + + @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""") + def test_model_outputs_equivalence(self): + pass + + @slow + def test_model_from_pretrained(self): + for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = ViTMAEModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class ViTMAEModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ViTImageProcessor.from_pretrained("facebook/vit-mae-base") if is_vision_available() else None + + @slow + def test_inference_for_pretraining(self): + # make random mask reproducible across the PT and TF model + np.random.seed(2) + + model = ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base").to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # prepare a noise vector that will be also used for testing the TF model + # (this way we can ensure that the PT and TF models operate on the same inputs) + vit_mae_config = ViTMAEConfig() + num_patches = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2) + noise = np.random.uniform(size=(1, num_patches)) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs, noise=torch.from_numpy(noise).to(device=torch_device)) + + # verify the logits + expected_shape = torch.Size((1, 196, 768)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor( + [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] + ) + + self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_slice.to(torch_device), atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_msn/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_msn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_msn/test_modeling_vit_msn.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_msn/test_modeling_vit_msn.py new file mode 100644 index 0000000000000000000000000000000000000000..96e107e7950ecc183a9ac959cb5acc4334075627 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vit_msn/test_modeling_vit_msn.py @@ -0,0 +1,232 @@ +# coding=utf-8 +# Copyright 2022 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 ViTMSN model. """ + + +import unittest + +from transformers import ViTMSNConfig +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ViTMSNForImageClassification, ViTMSNModel + from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import ViTImageProcessor + + +class ViTMSNModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=30, + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.scope = scope + + # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = num_patches + 1 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return ViTMSNConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = ViTMSNModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_image_classification(self, config, pixel_values, labels): + config.num_labels = self.type_sequence_label_size + model = ViTMSNForImageClassification(config) + model.to(torch_device) + model.eval() + result = model(pixel_values, labels=labels) + print("Pixel and labels shape: {pixel_values.shape}, {labels.shape}") + print("Labels: {labels}") + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + # test greyscale images + config.num_channels = 1 + model = ViTMSNForImageClassification(config) + model.to(torch_device) + model.eval() + + pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) + result = model(pixel_values) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class ViTMSNModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as ViTMSN does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification} + if is_torch_available() + else {} + ) + + test_pruning = False + test_torchscript = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = ViTMSNModelTester(self) + self.config_tester = ConfigTester(self, config_class=ViTMSNConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="ViTMSN does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_image_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_image_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = ViTMSNModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class ViTMSNModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return ViTImageProcessor.from_pretrained("facebook/vit-msn-small") if is_vision_available() else None + + @slow + def test_inference_image_classification_head(self): + torch.manual_seed(2) + model = ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-small").to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 1000)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice = torch.tensor([0.5588, 0.6853, -0.5929]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitdet/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitdet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitdet/test_modeling_vitdet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitdet/test_modeling_vitdet.py new file mode 100644 index 0000000000000000000000000000000000000000..2df1b7925789aaade48296a1a1cf30e019e2b114 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitdet/test_modeling_vitdet.py @@ -0,0 +1,302 @@ +# coding=utf-8 +# Copyright 2023 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 ViTDet model. """ + + +import unittest + +from transformers import VitDetConfig +from transformers.testing_utils import is_flaky, require_torch, torch_device +from transformers.utils import is_torch_available + +from ...test_backbone_common import BackboneTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import VitDetBackbone, VitDetModel + + +class VitDetModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=30, + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.scope = scope + + self.num_patches_one_direction = self.image_size // self.patch_size + self.seq_length = (self.image_size // self.patch_size) ** 2 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return VitDetConfig( + image_size=self.image_size, + pretrain_image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = VitDetModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction), + ) + + def create_and_check_backbone(self, config, pixel_values, labels): + model = VitDetBackbone(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + # verify hidden states + self.parent.assertEqual(len(result.feature_maps), len(config.out_features)) + self.parent.assertListEqual( + list(result.feature_maps[0].shape), + [self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction], + ) + + # verify channels + self.parent.assertEqual(len(model.channels), len(config.out_features)) + self.parent.assertListEqual(model.channels, [config.hidden_size]) + + # verify backbone works with out_features=None + config.out_features = None + model = VitDetBackbone(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + # verify feature maps + self.parent.assertEqual(len(result.feature_maps), 1) + self.parent.assertListEqual( + list(result.feature_maps[0].shape), + [self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction], + ) + + # verify channels + self.parent.assertEqual(len(model.channels), 1) + self.parent.assertListEqual(model.channels, [config.hidden_size]) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class VitDetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as VitDet does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (VitDetModel, VitDetBackbone) if is_torch_available() else () + pipeline_model_mapping = {"feature-extraction": VitDetModel} if is_torch_available() else {} + + fx_compatible = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = VitDetModelTester(self) + self.config_tester = ConfigTester(self, config_class=VitDetConfig, has_text_modality=False, hidden_size=37) + + @is_flaky(max_attempts=3, description="`torch.nn.init.trunc_normal_` is flaky.") + def test_initialization(self): + super().test_initialization() + + # TODO: Fix me (once this model gets more usage) + @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.") + def test_cpu_offload(self): + super().test_cpu_offload() + + # TODO: Fix me (once this model gets more usage) + @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.") + def test_disk_offload_bin(self): + super().test_disk_offload() + + @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.") + def test_disk_offload_safetensors(self): + super().test_disk_offload() + + # TODO: Fix me (once this model gets more usage) + @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.") + def test_model_parallelism(self): + super().test_model_parallelism() + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="VitDet does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_backbone(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_backbone(*config_and_inputs) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_stages = self.model_tester.num_hidden_layers + self.assertEqual(len(hidden_states), expected_num_stages + 1) + + # VitDet's feature maps are of shape (batch_size, num_channels, height, width) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [ + self.model_tester.num_patches_one_direction, + self.model_tester.num_patches_one_direction, + ], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + # overwrite since VitDet only supports retraining gradients of hidden states + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs = model(**inputs) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + hidden_states.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + + @unittest.skip(reason="VitDet does not support feedforward chunking") + def test_feed_forward_chunking(self): + pass + + @unittest.skip(reason="VitDet does not have standalone checkpoints since it used as backbone in other models") + def test_model_from_pretrained(self): + pass + + +@require_torch +class VitDetBackboneTest(unittest.TestCase, BackboneTesterMixin): + all_model_classes = (VitDetBackbone,) if is_torch_available() else () + config_class = VitDetConfig + + has_attentions = False + + def setUp(self): + self.model_tester = VitDetModelTester(self) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitmatte/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitmatte/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitmatte/test_image_processing_vitmatte.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitmatte/test_image_processing_vitmatte.py new file mode 100644 index 0000000000000000000000000000000000000000..e1009c759283207bfc87f6dab7b2e8b97e9fd9c8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitmatte/test_image_processing_vitmatte.py @@ -0,0 +1,194 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +import numpy as np + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs + + +if is_torch_available(): + import torch + + +if is_vision_available(): + from PIL import Image + + from transformers import VitMatteImageProcessor + + +class VitMatteImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + image_size=18, + min_resolution=30, + max_resolution=400, + do_rescale=True, + rescale_factor=0.5, + do_pad=True, + size_divisibility=10, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + ): + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.image_size = image_size + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_rescale = do_rescale + self.rescale_factor = rescale_factor + self.do_pad = do_pad + self.size_divisibility = size_divisibility + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + + def prepare_image_processor_dict(self): + return { + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_normalize": self.do_normalize, + "do_rescale": self.do_rescale, + "rescale_factor": self.rescale_factor, + "do_pad": self.do_pad, + "size_divisibility": self.size_divisibility, + } + + def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_image_inputs( + batch_size=self.batch_size, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class VitMatteImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = VitMatteImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = VitMatteImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_rescale")) + self.assertTrue(hasattr(image_processing, "rescale_factor")) + self.assertTrue(hasattr(image_processing, "do_pad")) + self.assertTrue(hasattr(image_processing, "size_divisibility")) + + def test_call_numpy(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) + for image in image_inputs: + self.assertIsInstance(image, np.ndarray) + + # Test not batched input (image processor does not support batched inputs) + image = image_inputs[0] + trimap = np.random.randint(0, 3, size=image.shape[:2]) + encoded_images = image_processing(images=image, trimaps=trimap, return_tensors="pt").pixel_values + + # Verify that width and height can be divided by size_divisibility + self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) + self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) + + def test_call_pytorch(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test not batched input (image processor does not support batched inputs) + image = image_inputs[0] + trimap = np.random.randint(0, 3, size=image.shape[:2]) + encoded_images = image_processing(images=image, trimaps=trimap, return_tensors="pt").pixel_values + + # Verify that width and height can be divided by size_divisibility + self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) + self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) + + def test_call_pil(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PIL images + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) + for image in image_inputs: + self.assertIsInstance(image, Image.Image) + + # Test not batched input (image processor does not support batched inputs) + image = image_inputs[0] + trimap = np.random.randint(0, 3, size=image.size[::-1]) + encoded_images = image_processing(images=image, trimaps=trimap, return_tensors="pt").pixel_values + + # Verify that width and height can be divided by size_divisibility + self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) + self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) + + def test_call_numpy_4_channels(self): + # Test that can process images which have an arbitrary number of channels + # Initialize image_processing + image_processor = self.image_processing_class(**self.image_processor_dict) + + # create random numpy tensors + self.image_processor_tester.num_channels = 4 + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) + + # Test not batched input (image processor does not support batched inputs) + image = image_inputs[0] + trimap = np.random.randint(0, 3, size=image.shape[:2]) + encoded_images = image_processor( + images=image, + trimaps=trimap, + input_data_format="channels_first", + image_mean=0, + image_std=1, + return_tensors="pt", + ).pixel_values + + # Verify that width and height can be divided by size_divisibility + self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) + self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) + + def test_padding(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + image = np.random.randn(3, 249, 491) + images = image_processing.pad_image(image) + assert images.shape == (3, 256, 512) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitmatte/test_modeling_vitmatte.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitmatte/test_modeling_vitmatte.py new file mode 100644 index 0000000000000000000000000000000000000000..c9446b116f1e452f7832c9f7afe2ad29692cdfe1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vitmatte/test_modeling_vitmatte.py @@ -0,0 +1,269 @@ +# coding=utf-8 +# Copyright 2023 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 VitMatte model. """ + + +import unittest + +from huggingface_hub import hf_hub_download + +from transformers import VitMatteConfig +from transformers.testing_utils import ( + require_torch, + slow, + torch_device, +) +from transformers.utils import is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import VitDetConfig, VitMatteForImageMatting + from transformers.models.vitmatte.modeling_vitmatte import VITMATTE_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import VitMatteImageProcessor + + +class VitMatteModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=32, + patch_size=16, + num_channels=4, + is_training=True, + use_labels=False, + hidden_size=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_act="gelu", + type_sequence_label_size=10, + initializer_range=0.02, + scope=None, + out_features=["stage1"], + fusion_hidden_sizes=[128, 64, 32, 16], + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_act = hidden_act + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.scope = scope + self.out_features = out_features + self.fusion_hidden_sizes = fusion_hidden_sizes + + self.seq_length = (self.image_size // self.patch_size) ** 2 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + raise NotImplementedError("Training is not yet supported") + + config = self.get_config() + + return config, pixel_values, labels + + def get_backbone_config(self): + return VitDetConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_size=self.hidden_size, + is_training=self.is_training, + hidden_act=self.hidden_act, + out_features=self.out_features, + ) + + def get_config(self): + return VitMatteConfig( + backbone_config=self.get_backbone_config(), + hidden_size=self.hidden_size, + fusion_hidden_sizes=self.fusion_hidden_sizes, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = VitMatteForImageMatting(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.alphas.shape, (self.batch_size, 1, self.image_size, self.image_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class VitMatteModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as VitMatte does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (VitMatteForImageMatting,) if is_torch_available() else () + pipeline_model_mapping = {} + + fx_compatible = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = VitMatteModelTester(self) + self.config_tester = ConfigTester(self, config_class=VitMatteConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + @unittest.skip(reason="VitMatte does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="Training is not yet supported") + def test_training(self): + pass + + @unittest.skip(reason="Training is not yet supported") + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + @unittest.skip(reason="ViTMatte does not support input and output embeddings") + def test_model_common_attributes(self): + pass + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in VITMATTE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = VitMatteForImageMatting.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip(reason="ViTMatte does not support retaining gradient on attention logits") + def test_retain_grad_hidden_states_attentions(self): + pass + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [2, 2], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + print("Hello we're here") + + check_hidden_states_output(inputs_dict, config, model_class) + + +@require_torch +class VitMatteModelIntegrationTest(unittest.TestCase): + @slow + def test_inference(self): + processor = VitMatteImageProcessor.from_pretrained("hustvl/vitmatte-small-composition-1k") + model = VitMatteForImageMatting.from_pretrained("hustvl/vitmatte-small-composition-1k").to(torch_device) + + filepath = hf_hub_download( + repo_id="hf-internal-testing/image-matting-fixtures", filename="image.png", repo_type="dataset" + ) + image = Image.open(filepath).convert("RGB") + filepath = hf_hub_download( + repo_id="hf-internal-testing/image-matting-fixtures", filename="trimap.png", repo_type="dataset" + ) + trimap = Image.open(filepath).convert("L") + + # prepare image + trimap for the model + inputs = processor(images=image, trimaps=trimap, return_tensors="pt").to(torch_device) + + with torch.no_grad(): + alphas = model(**inputs).alphas + + expected_shape = torch.Size((1, 1, 640, 960)) + self.assertEqual(alphas.shape, expected_shape) + + expected_slice = torch.tensor( + [[0.9977, 0.9987, 0.9990], [0.9980, 0.9998, 0.9998], [0.9983, 0.9998, 0.9998]], device=torch_device + ) + self.assertTrue(torch.allclose(alphas[0, 0, :3, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vits/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vits/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vits/test_modeling_vits.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vits/test_modeling_vits.py new file mode 100644 index 0000000000000000000000000000000000000000..abae6999cdfca20c5dc00611c5c34a203241d0d8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vits/test_modeling_vits.py @@ -0,0 +1,425 @@ +# coding=utf-8 +# Copyright 2023 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 VITS model. """ + +import copy +import os +import tempfile +import unittest +from typing import Dict, List, Tuple + +import numpy as np + +from transformers import PretrainedConfig, VitsConfig +from transformers.testing_utils import ( + is_flaky, + is_torch_available, + require_torch, + require_torch_multi_gpu, + slow, + torch_device, +) +from transformers.trainer_utils import set_seed + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + global_rng, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import VitsModel, VitsTokenizer + + +CONFIG_NAME = "config.json" +GENERATION_CONFIG_NAME = "generation_config.json" + + +def _config_zero_init(config): + configs_no_init = copy.deepcopy(config) + for key in configs_no_init.__dict__.keys(): + if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: + setattr(configs_no_init, key, 1e-10) + if isinstance(getattr(configs_no_init, key, None), PretrainedConfig): + no_init_subconfig = _config_zero_init(getattr(configs_no_init, key)) + setattr(configs_no_init, key, no_init_subconfig) + return configs_no_init + + +@require_torch +class VitsModelTester: + def __init__( + self, + parent, + batch_size=2, + seq_length=7, + is_training=False, + hidden_size=16, + num_hidden_layers=2, + num_attention_heads=2, + intermediate_size=64, + flow_size=16, + vocab_size=38, + spectrogram_bins=8, + duration_predictor_num_flows=2, + duration_predictor_filter_channels=16, + prior_encoder_num_flows=2, + upsample_initial_channel=16, + upsample_rates=[8, 2], + upsample_kernel_sizes=[16, 4], + resblock_kernel_sizes=[3, 7], + resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]], + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + 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.flow_size = flow_size + self.vocab_size = vocab_size + self.spectrogram_bins = spectrogram_bins + self.duration_predictor_num_flows = duration_predictor_num_flows + self.duration_predictor_filter_channels = duration_predictor_filter_channels + self.prior_encoder_num_flows = prior_encoder_num_flows + self.upsample_initial_channel = upsample_initial_channel + self.upsample_rates = upsample_rates + self.upsample_kernel_sizes = upsample_kernel_sizes + self.resblock_kernel_sizes = resblock_kernel_sizes + self.resblock_dilation_sizes = resblock_dilation_sizes + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(2) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + } + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_config(self): + return VitsConfig( + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + ffn_dim=self.intermediate_size, + flow_size=self.flow_size, + vocab_size=self.vocab_size, + spectrogram_bins=self.spectrogram_bins, + duration_predictor_num_flows=self.duration_predictor_num_flows, + prior_encoder_num_flows=self.prior_encoder_num_flows, + duration_predictor_filter_channels=self.duration_predictor_filter_channels, + posterior_encoder_num_wavenet_layers=self.num_hidden_layers, + upsample_initial_channel=self.upsample_initial_channel, + upsample_rates=self.upsample_rates, + upsample_kernel_sizes=self.upsample_kernel_sizes, + resblock_kernel_sizes=self.resblock_kernel_sizes, + resblock_dilation_sizes=self.resblock_dilation_sizes, + ) + + def create_and_check_model_forward(self, config, inputs_dict): + model = VitsModel(config=config).to(torch_device).eval() + + input_ids = inputs_dict["input_ids"] + attention_mask = inputs_dict["attention_mask"] + + result = model(input_ids, attention_mask=attention_mask) + self.parent.assertEqual((self.batch_size, 624), result.waveform.shape) + + +@require_torch +class VitsModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (VitsModel,) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": VitsModel, "text-to-audio": VitsModel} if is_torch_available() else {} + ) + is_encoder_decoder = False + test_pruning = False + test_headmasking = False + test_resize_embeddings = False + test_head_masking = False + test_torchscript = False + has_attentions = False + + input_name = "input_ids" + + def setUp(self): + self.model_tester = VitsModelTester(self) + self.config_tester = ConfigTester(self, config_class=VitsConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip("Need to fix this after #26538") + def test_model_forward(self): + set_seed(12345) + global_rng.seed(12345) + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + @require_torch_multi_gpu + # override to force all elements of the batch to have the same sequence length across GPUs + def test_multi_gpu_data_parallel_forward(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.use_stochastic_duration_prediction = False + + # move input tensors to cuda:O + for key, value in inputs_dict.items(): + if torch.is_tensor(value): + # make all elements of the batch the same -> ensures the output seq lengths are the same for DP + value[1:] = value[0] + inputs_dict[key] = value.to(0) + + for model_class in self.all_model_classes: + model = model_class(config=config) + model.to(0) + model.eval() + + # Wrap model in nn.DataParallel + model = torch.nn.DataParallel(model) + set_seed(555) + with torch.no_grad(): + _ = model(**self._prepare_for_class(inputs_dict, model_class)).waveform + + @unittest.skip("VITS is not deterministic") + def test_determinism(self): + pass + + @is_flaky( + max_attempts=3, + description="Weight initialisation for the VITS conv layers sometimes exceeds the kaiming normal range", + ) + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + uniform_init_parms = [ + "emb_rel_k", + "emb_rel_v", + "conv_1", + "conv_2", + "conv_pre", + "conv_post", + "conv_proj", + "conv_dds", + "project", + "wavenet.in_layers", + "wavenet.res_skip_layers", + "upsampler", + "resblocks", + ] + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + @unittest.skip("VITS has no inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip("VITS has no input embeddings") + def test_model_common_attributes(self): + pass + + # override since the model is not deterministic, so we need to set the seed for each forward pass + def test_model_outputs_equivalence(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def set_nan_tensor_to_zero(t): + t[t != t] = 0 + return t + + def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): + with torch.no_grad(): + set_seed(0) + tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs) + set_seed(0) + dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple() + + def recursive_check(tuple_object, dict_object): + if isinstance(tuple_object, (List, Tuple)): + for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif isinstance(tuple_object, Dict): + for tuple_iterable_value, dict_iterable_value in zip( + tuple_object.values(), dict_object.values() + ): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif tuple_object is None: + return + else: + self.assertTrue( + torch.allclose( + set_nan_tensor_to_zero(tuple_object), set_nan_tensor_to_zero(dict_object), atol=1e-5 + ), + msg=( + "Tuple and dict output are not equal. Difference:" + f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:" + f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has" + f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}." + ), + ) + + recursive_check(tuple_output, dict_output) + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + if self.has_attentions: + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence( + model, tuple_inputs, dict_inputs, {"output_hidden_states": True, "output_attentions": True} + ) + + # override since the model is not deterministic, so we need to set the seed for each forward pass + def test_save_load(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_save_load(out1, out2): + # make sure we don't have nans + out_2 = out2.cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + out_1 = out1.cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + set_seed(0) + first = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + # the config file (and the generation config file, if it can generate) should be saved + self.assertTrue(os.path.exists(os.path.join(tmpdirname, CONFIG_NAME))) + self.assertEqual( + model.can_generate(), os.path.exists(os.path.join(tmpdirname, GENERATION_CONFIG_NAME)) + ) + + model = model_class.from_pretrained(tmpdirname) + model.to(torch_device) + with torch.no_grad(): + set_seed(0) + second = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + if isinstance(first, tuple) and isinstance(second, tuple): + for tensor1, tensor2 in zip(first, second): + check_save_load(tensor1, tensor2) + else: + check_save_load(first, second) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + + +@require_torch +@slow +class VitsModelIntegrationTests(unittest.TestCase): + def test_forward(self): + # GPU gives different results than CPU + torch_device = "cpu" + + model = VitsModel.from_pretrained("facebook/mms-tts-eng") + model.to(torch_device) + + tokenizer = VitsTokenizer.from_pretrained("facebook/mms-tts-eng") + + set_seed(555) # make deterministic + + input_text = "Mister quilter is the apostle of the middle classes and we are glad to welcome his gospel!" + input_ids = tokenizer(input_text, return_tensors="pt").input_ids.to(torch_device) + + with torch.no_grad(): + outputs = model(input_ids) + + self.assertEqual(outputs.waveform.shape, (1, 87040)) + # fmt: off + EXPECTED_LOGITS = torch.tensor( + [ + -0.0042, 0.0176, 0.0354, 0.0504, 0.0621, 0.0777, 0.0980, 0.1224, + 0.1475, 0.1679, 0.1817, 0.1832, 0.1713, 0.1542, 0.1384, 0.1256, + 0.1147, 0.1066, 0.1026, 0.0958, 0.0823, 0.0610, 0.0340, 0.0022, + -0.0337, -0.0677, -0.0969, -0.1178, -0.1311, -0.1363 + ] + ) + # fmt: on + self.assertTrue(torch.allclose(outputs.waveform[0, 10000:10030].cpu(), EXPECTED_LOGITS, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vits/test_tokenization_vits.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vits/test_tokenization_vits.py new file mode 100644 index 0000000000000000000000000000000000000000..c02caaaa9083392c7d3e13b9fe60b3ca3a4ca2b5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vits/test_tokenization_vits.py @@ -0,0 +1,186 @@ +# coding=utf-8 +# Copyright 2023 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. +"""Tests for the VITS tokenizer.""" +import json +import os +import shutil +import tempfile +import unittest + +from transformers import VitsTokenizer +from transformers.models.vits.tokenization_vits import VOCAB_FILES_NAMES +from transformers.testing_utils import slow + +from ...test_tokenization_common import TokenizerTesterMixin + + +class VitsTokenizerTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = VitsTokenizer + test_rust_tokenizer = False + + def setUp(self): + super().setUp() + + vocab = ( + "k ' z y u d h e s w – 3 c p - 1 j m i X f l o 0 b r a 4 2 n _ x v t q 5 6 g ț ţ < > | ".split( + " " + ) + ) + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + vocab_tokens[" "] = vocab_tokens["X"] + del vocab_tokens["X"] + + self.special_tokens_map = {"pad_token": "", "unk_token": ""} + + self.tmpdirname = tempfile.mkdtemp() + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(vocab_tokens) + "\n") + + def get_tokenizer(self, **kwargs): + kwargs.update(self.special_tokens_map) + kwargs["phonemize"] = False + kwargs["normalize"] = False + return VitsTokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5): + txt = "beyonce lives in los angeles" + ids = tokenizer.encode(txt, add_special_tokens=False) + return txt, ids + + @unittest.skip("Adding multicharacter tokens does not work with the VITS tokenizer") + def test_add_tokens_tokenizer(self): + pass + + @unittest.skip("Adding multicharacter tokens does not work with the VITS tokenizer") + def test_encode_decode_with_spaces(self): + pass + + @unittest.skip("The VITS tokenizer does not support `is_split_into_words`") + def test_pretokenized_inputs(self): + pass + + def test_save_and_load_tokenizer(self): + # safety check on max_len default value so we are sure the test works + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + self.assertNotEqual(tokenizer.model_max_length, 42) + + # Now let's start the test + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + sample_text = " He is very happy, UNwant\u00E9d,running" + before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) + 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() + self.assertListEqual(before_tokens, after_tokens) + self.assertDictEqual(before_vocab, after_vocab) + + shutil.rmtree(tmpdirname) + + @unittest.skip("Adding multicharacter tokens does not work the VITS tokenizer") + def test_special_tokens_initialization_with_non_empty_additional_special_tokens(self): + pass + + def test_ron_normalization(self): + tokenizer = self.get_tokenizer() + tokenizer.language = "ron" + + sequences = ["vițs"] + normalized_sequences = ["viţs"] + + encoded_ids = tokenizer(sequences, normalize=True)["input_ids"] + decoded_sequences = tokenizer.batch_decode(encoded_ids) + self.assertEqual(normalized_sequences, decoded_sequences) + + def test_normalization(self): + tokenizer = self.get_tokenizer() + + sequences = ["VITS; is a model for t-t-s!"] + normalized_sequences = ["vits is a model for t-t-s"] + unnormalized_sequences = [ + " is a model for t-t-s" + ] # can't handle upper-case or certain punctuations + + encoded_normalized_ids = tokenizer(sequences, normalize=True) + encoded_unnormalized_ids = tokenizer(sequences, normalize=False) + + decoded_normalized_sequences = [ + tokenizer.decode(seq, skip_special_tokens=False) for seq in encoded_normalized_ids["input_ids"] + ] + decoded_unnormalized_sequences = [ + tokenizer.decode(seq, skip_special_tokens=False) for seq in encoded_unnormalized_ids["input_ids"] + ] + + self.assertEqual(decoded_normalized_sequences, normalized_sequences) + self.assertEqual(decoded_unnormalized_sequences, unnormalized_sequences) + + @slow + def test_tokenizer_integration(self): + sequences = [ + "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " + "conditioning on both left and right context in all layers.", + "The quick brown fox! Jumps over the lazy dog...", + "We use k as our padding token", + ] + + normalized_sequences = [ + "bert is designed to pre-train deep bidirectional representations from unlabeled text by jointly " + "conditioning on both left and right context in all layers", + "the quick brown fox jumps over the lazy dog", + "we use k as our padding token", + ] + + # fmt: off + expected_encoding = { + 'input_ids': [ + [0, 24, 0, 7, 0, 25, 0, 33, 0, 19, 0, 18, 0, 8, 0, 19, 0, 5, 0, 7, 0, 8, 0, 18, 0, 37, 0, 29, 0, 7, 0, 5, 0, 19, 0, 33, 0, 22, 0, 19, 0, 13, 0, 25, 0, 7, 0, 14, 0, 33, 0, 25, 0, 26, 0, 18, 0, 29, 0, 19, 0, 5, 0, 7, 0, 7, 0, 13, 0, 19, 0, 24, 0, 18, 0, 5, 0, 18, 0, 25, 0, 7, 0, 12, 0, 33, 0, 18, 0, 22, 0, 29, 0, 26, 0, 21, 0, 19, 0, 25, 0, 7, 0, 13, 0, 25, 0, 7, 0, 8, 0, 7, 0, 29, 0, 33, 0, 26, 0, 33, 0, 18, 0, 22, 0, 29, 0, 8, 0, 19, 0, 20, 0, 25, 0, 22, 0, 17, 0, 19, 0, 4, 0, 29, 0, 21, 0, 26, 0, 24, 0, 7, 0, 21, 0, 7, 0, 5, 0, 19, 0, 33, 0, 7, 0, 31, 0, 33, 0, 19, 0, 24, 0, 3, 0, 19, 0, 16, 0, 22, 0, 18, 0, 29, 0, 33, 0, 21, 0, 3, 0, 19, 0, 12, 0, 22, 0, 29, 0, 5, 0, 18, 0, 33, 0, 18, 0, 22, 0, 29, 0, 18, 0, 29, 0, 37, 0, 19, 0, 22, 0, 29, 0, 19, 0, 24, 0, 22, 0, 33, 0, 6, 0, 19, 0, 21, 0, 7, 0, 20, 0, 33, 0, 19, 0, 26, 0, 29, 0, 5, 0, 19, 0, 25, 0, 18, 0, 37, 0, 6, 0, 33, 0, 19, 0, 12, 0, 22, 0, 29, 0, 33, 0, 7, 0, 31, 0, 33, 0, 19, 0, 18, 0, 29, 0, 19, 0, 26, 0, 21, 0, 21, 0, 19, 0, 21, 0, 26, 0, 3, 0, 7, 0, 25, 0, 8, 0], + [0, 33, 0, 6, 0, 7, 0, 19, 0, 34, 0, 4, 0, 18, 0, 12, 0, 0, 0, 19, 0, 24, 0, 25, 0, 22, 0, 9, 0, 29, 0, 19, 0, 20, 0, 22, 0, 31, 0, 19, 0, 16, 0, 4, 0, 17, 0, 13, 0, 8, 0, 19, 0, 22, 0, 32, 0, 7, 0, 25, 0, 19, 0, 33, 0, 6, 0, 7, 0, 19, 0, 21, 0, 26, 0, 2, 0, 3, 0, 19, 0, 5, 0, 22, 0, 37, 0, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39], + [0, 9, 0, 7, 0, 19, 0, 4, 0, 8, 0, 7, 0, 19, 0, 0, 0, 19, 0, 26, 0, 8, 0, 19, 0, 22, 0, 4, 0, 25, 0, 19, 0, 13, 0, 26, 0, 5, 0, 5, 0, 18, 0, 29, 0, 37, 0, 19, 0, 33, 0, 22, 0, 0, 0, 7, 0, 29, 0, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39], + ], + 'attention_mask': [ + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + } + # fmt: on + tokenizer_classes = [self.tokenizer_class] + if self.test_rust_tokenizer: + tokenizer_classes.append(self.rust_tokenizer_class) + for tokenizer_class in tokenizer_classes: + tokenizer = tokenizer_class.from_pretrained( + "facebook/mms-tts-eng", + revision="28cedf176aa99de5023a4344fd8a2cc477126fb8", # to pin the tokenizer version + pad_token="", + ) + + encoding = tokenizer(sequences, padding=True, normalize=True) + decoded_sequences = [tokenizer.decode(seq, skip_special_tokens=True) for seq in encoding["input_ids"]] + + encoding_data = encoding.data + self.assertDictEqual(encoding_data, expected_encoding) + + for expected, decoded in zip(normalized_sequences, decoded_sequences): + self.assertEqual(expected, decoded) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vivit/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vivit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vivit/test_image_processing_vivit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vivit/test_image_processing_vivit.py new file mode 100644 index 0000000000000000000000000000000000000000..dad120ef818e9b404d1ad8aeec13ca630f63623d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vivit/test_image_processing_vivit.py @@ -0,0 +1,228 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. +# +# 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 unittest + +import numpy as np + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingTestMixin, prepare_video_inputs + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + from transformers import VivitImageProcessor + + +class VivitImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + num_frames=10, + image_size=18, + min_resolution=30, + max_resolution=400, + do_resize=True, + size=None, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + crop_size=None, + ): + size = size if size is not None else {"shortest_edge": 18} + crop_size = crop_size if crop_size is not None else {"height": 18, "width": 18} + + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.num_frames = num_frames + self.image_size = image_size + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + self.crop_size = crop_size + + def prepare_image_processor_dict(self): + return { + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_normalize": self.do_normalize, + "do_resize": self.do_resize, + "size": self.size, + "crop_size": self.crop_size, + } + + def expected_output_image_shape(self, images): + return self.num_frames, self.num_channels, self.crop_size["height"], self.crop_size["width"] + + def prepare_video_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_video_inputs( + batch_size=self.batch_size, + num_channels=self.num_channels, + num_frames=self.num_frames, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class VivitImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = VivitImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = VivitImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "do_center_crop")) + self.assertTrue(hasattr(image_processing, "size")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"shortest_edge": 18}) + self.assertEqual(image_processor.crop_size, {"height": 18, "width": 18}) + + image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42, crop_size=84) + self.assertEqual(image_processor.size, {"shortest_edge": 42}) + self.assertEqual(image_processor.crop_size, {"height": 84, "width": 84}) + + def test_rescale(self): + # ViVit optionally rescales between -1 and 1 instead of the usual 0 and 1 + image = np.arange(0, 256, 1, dtype=np.uint8).reshape(1, 8, 32) + + image_processor = self.image_processing_class(**self.image_processor_dict) + + rescaled_image = image_processor.rescale(image, scale=1 / 127.5) + expected_image = (image * (1 / 127.5)).astype(np.float32) - 1 + self.assertTrue(np.allclose(rescaled_image, expected_image)) + + rescaled_image = image_processor.rescale(image, scale=1 / 255, offset=False) + expected_image = (image / 255.0).astype(np.float32) + self.assertTrue(np.allclose(rescaled_image, expected_image)) + + def test_call_pil(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PIL videos + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], Image.Image) + + # Test not batched input + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos) + self.assertEqual( + tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape) + ) + + def test_call_numpy(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], np.ndarray) + + # Test not batched input + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos) + self.assertEqual( + tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape) + ) + + def test_call_numpy_4_channels(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + self.image_processor_tester.num_channels = 4 + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], np.ndarray) + + # Test not batched input + encoded_videos = image_processing( + video_inputs[0], return_tensors="pt", image_mean=0, image_std=1, input_data_format="channels_first" + ).pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = image_processing( + video_inputs, return_tensors="pt", image_mean=0, image_std=1, input_data_format="channels_first" + ).pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos) + self.assertEqual( + tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape) + ) + self.image_processor_tester.num_channels = 3 + + def test_call_pytorch(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, torchify=True) + for video in video_inputs: + self.assertIsInstance(video, list) + self.assertIsInstance(video[0], torch.Tensor) + + # Test not batched input + encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape([encoded_videos[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values + expected_output_video_shape = self.image_processor_tester.expected_output_image_shape(encoded_videos) + self.assertEqual( + tuple(encoded_videos.shape), (self.image_processor_tester.batch_size, *expected_output_video_shape) + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vivit/test_modeling_vivit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vivit/test_modeling_vivit.py new file mode 100644 index 0000000000000000000000000000000000000000..152cfac155b8a1bad6479db8c5c3f247d6c4cbe6 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/vivit/test_modeling_vivit.py @@ -0,0 +1,356 @@ +# coding=utf-8 +# Copyright 2023 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 ViViT model. """ + + +import copy +import inspect +import unittest + +import numpy as np +from huggingface_hub import hf_hub_download + +from transformers import VivitConfig +from transformers.models.auto import get_values +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel + from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from transformers import VivitImageProcessor + + +class VivitModelTester: + def __init__( + self, + parent, + batch_size=2, + is_training=True, + use_labels=True, + num_labels=10, + image_size=10, + num_frames=8, # decreased, because default 32 takes too much RAM at inference + tubelet_size=[2, 4, 4], + num_channels=3, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu_fast", + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + initializer_range=0.02, + layer_norm_eps=1e-06, + qkv_bias=True, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.is_training = is_training + self.use_labels = use_labels + self.num_labels = num_labels + self.image_size = image_size + self.num_frames = num_frames + self.tubelet_size = tubelet_size + self.num_channels = num_channels + 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.initializer_range = initializer_range + self.layer_norm_eps = layer_norm_eps + self.qkv_bias = qkv_bias + self.scope = scope + + self.seq_length = ( + (self.image_size // self.tubelet_size[2]) + * (self.image_size // self.tubelet_size[1]) + * (self.num_frames // self.tubelet_size[0]) + ) + 1 # CLS token + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor( + [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] + ) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.num_labels) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + config = VivitConfig( + num_frames=self.num_frames, + image_size=self.image_size, + tubelet_size=self.tubelet_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + initializer_range=self.initializer_range, + layer_norm_eps=self.layer_norm_eps, + qkv_bias=self.qkv_bias, + ) + config.num_labels = self.num_labels + return config + + def create_and_check_model(self, config, pixel_values, labels): + model = VivitModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_video_classification(self, config, pixel_values, labels): + model = VivitForVideoClassification(config) + model.to(torch_device) + model.eval() + + result = model(pixel_values) + + # verify the logits shape + expected_shape = torch.Size((self.batch_size, self.num_labels)) + self.parent.assertEqual(result.logits.shape, expected_shape) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class VivitModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as Vivit does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (VivitModel, VivitForVideoClassification) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": VivitModel, "video-classification": VivitForVideoClassification} + if is_torch_available() + else {} + ) + + test_pruning = False + test_torchscript = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = VivitModelTester(self) + self.config_tester = ConfigTester(self, config_class=VivitConfig, has_text_modality=False, hidden_size=37) + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = copy.deepcopy(inputs_dict) + + if return_labels: + if model_class in get_values(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING): + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + + return inputs_dict + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="Vivit does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values", "head_mask"] + self.assertListEqual(arg_names[:2], expected_arg_names) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_video_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_video_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = VivitModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + seq_len = self.model_tester.seq_length + + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + expected_num_layers = self.model_tester.num_hidden_layers + 1 + self.assertEqual(len(hidden_states), expected_num_layers) + + seq_length = self.model_tester.seq_length + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + +# We will verify our results on a video of eating spaghetti +# Frame indices used: [164 168 172 176 181 185 189 193 198 202 206 210 215 219 223 227] +def prepare_video(): + file = hf_hub_download( + repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti_32_frames.npy", repo_type="dataset" + ) + video = np.load(file) + return list(video) + + +@require_torch +@require_vision +class VivitModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return VivitImageProcessor() if is_vision_available() else None + + @slow + def test_inference_for_video_classification(self): + model = VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400").to(torch_device) + + image_processor = self.default_image_processor + video = prepare_video() + inputs = image_processor(video, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + expected_shape = torch.Size((1, 400)) + self.assertEqual(outputs.logits.shape, expected_shape) + + # taken from original model + expected_slice = torch.tensor([-0.9498, 2.7971, -1.4049, 0.1024, -1.8353]).to(torch_device) + + self.assertTrue(torch.allclose(outputs.logits[0, :5], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_feature_extraction_wav2vec2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_feature_extraction_wav2vec2.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ab09b6069a2bad45dd988a8347abb218ca5fc3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_feature_extraction_wav2vec2.py @@ -0,0 +1,233 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 itertools +import random +import unittest + +import numpy as np + +from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, Wav2Vec2Config, Wav2Vec2FeatureExtractor +from transformers.testing_utils import require_torch, slow + +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +global_rng = random.Random() + + +# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +class Wav2Vec2FeatureExtractionTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + min_seq_length=400, + max_seq_length=2000, + feature_size=1, + padding_value=0.0, + sampling_rate=16000, + return_attention_mask=True, + do_normalize=True, + ): + self.parent = parent + self.batch_size = batch_size + self.min_seq_length = min_seq_length + self.max_seq_length = max_seq_length + self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) + self.feature_size = feature_size + self.padding_value = padding_value + self.sampling_rate = sampling_rate + self.return_attention_mask = return_attention_mask + self.do_normalize = do_normalize + + def prepare_feat_extract_dict(self): + return { + "feature_size": self.feature_size, + "padding_value": self.padding_value, + "sampling_rate": self.sampling_rate, + "return_attention_mask": self.return_attention_mask, + "do_normalize": self.do_normalize, + } + + def prepare_inputs_for_common(self, equal_length=False, numpify=False): + def _flatten(list_of_lists): + return list(itertools.chain(*list_of_lists)) + + if equal_length: + speech_inputs = floats_list((self.batch_size, self.max_seq_length)) + else: + # make sure that inputs increase in size + speech_inputs = [ + _flatten(floats_list((x, self.feature_size))) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + + return speech_inputs + + +class Wav2Vec2FeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = Wav2Vec2FeatureExtractor + + def setUp(self): + self.feat_extract_tester = Wav2Vec2FeatureExtractionTester(self) + + def _check_zero_mean_unit_variance(self, input_vector): + self.assertTrue(np.all(np.mean(input_vector, axis=0) < 1e-3)) + self.assertTrue(np.all(np.abs(np.var(input_vector, axis=0) - 1) < 1e-3)) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test not batched input + encoded_sequences_1 = feat_extract(speech_inputs[0], return_tensors="np").input_values + encoded_sequences_2 = feat_extract(np_speech_inputs[0], return_tensors="np").input_values + self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) + + # Test batched + encoded_sequences_1 = feat_extract(speech_inputs, return_tensors="np").input_values + encoded_sequences_2 = feat_extract(np_speech_inputs, return_tensors="np").input_values + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test 2-D numpy arrays are batched. + speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] + np_speech_inputs = np.asarray(speech_inputs) + encoded_sequences_1 = feat_extract(speech_inputs, return_tensors="np").input_values + encoded_sequences_2 = feat_extract(np_speech_inputs, return_tensors="np").input_values + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + def test_zero_mean_unit_variance_normalization_np(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + paddings = ["longest", "max_length", "do_not_pad"] + max_lengths = [None, 1600, None] + for max_length, padding in zip(max_lengths, paddings): + processed = feat_extract(speech_inputs, padding=padding, max_length=max_length, return_tensors="np") + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0][:800]) + self.assertTrue(input_values[0][800:].sum() < 1e-6) + self._check_zero_mean_unit_variance(input_values[1][:1000]) + self.assertTrue(input_values[0][1000:].sum() < 1e-6) + self._check_zero_mean_unit_variance(input_values[2][:1200]) + + def test_zero_mean_unit_variance_normalization(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + lengths = range(800, 1400, 200) + speech_inputs = [floats_list((1, x))[0] for x in lengths] + + paddings = ["longest", "max_length", "do_not_pad"] + max_lengths = [None, 1600, None] + + for max_length, padding in zip(max_lengths, paddings): + processed = feat_extract(speech_inputs, max_length=max_length, padding=padding) + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0][:800]) + self._check_zero_mean_unit_variance(input_values[1][:1000]) + self._check_zero_mean_unit_variance(input_values[2][:1200]) + + def test_zero_mean_unit_variance_normalization_trunc_np_max_length(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + processed = feat_extract( + speech_inputs, truncation=True, max_length=1000, padding="max_length", return_tensors="np" + ) + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0, :800]) + self._check_zero_mean_unit_variance(input_values[1]) + self._check_zero_mean_unit_variance(input_values[2]) + + def test_zero_mean_unit_variance_normalization_trunc_np_longest(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + processed = feat_extract( + speech_inputs, truncation=True, max_length=1000, padding="longest", return_tensors="np" + ) + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0, :800]) + self._check_zero_mean_unit_variance(input_values[1, :1000]) + self._check_zero_mean_unit_variance(input_values[2]) + + # make sure that if max_length < longest -> then pad to max_length + self.assertTrue(input_values.shape == (3, 1000)) + + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + processed = feat_extract( + speech_inputs, truncation=True, max_length=2000, padding="longest", return_tensors="np" + ) + input_values = processed.input_values + + self._check_zero_mean_unit_variance(input_values[0, :800]) + self._check_zero_mean_unit_variance(input_values[1, :1000]) + self._check_zero_mean_unit_variance(input_values[2]) + + # make sure that if max_length > longest -> then pad to longest + self.assertTrue(input_values.shape == (3, 1200)) + + @require_torch + def test_double_precision_pad(self): + import torch + + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + np_speech_inputs = np.random.rand(100).astype(np.float64) + py_speech_inputs = np_speech_inputs.tolist() + + for inputs in [py_speech_inputs, np_speech_inputs]: + np_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="np") + self.assertTrue(np_processed.input_values.dtype == np.float32) + pt_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="pt") + self.assertTrue(pt_processed.input_values.dtype == torch.float32) + + @slow + @require_torch + def test_pretrained_checkpoints_are_set_correctly(self): + # this test makes sure that models that are using + # group norm don't have their feature extractor return the + # attention_mask + for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: + config = Wav2Vec2Config.from_pretrained(model_id) + feat_extract = Wav2Vec2FeatureExtractor.from_pretrained(model_id) + + # only "layer" feature extraction norm should make use of + # attention_mask + self.assertEqual(feat_extract.return_attention_mask, config.feat_extract_norm == "layer") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_flax_wav2vec2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_flax_wav2vec2.py new file mode 100644 index 0000000000000000000000000000000000000000..4cff7dca41ca043797e4804bed4e74c3822243e8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_flax_wav2vec2.py @@ -0,0 +1,639 @@ +# Copyright 2021 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 inspect +import math +import multiprocessing +import traceback +import unittest + +import numpy as np +from datasets import load_dataset + +from transformers import Wav2Vec2Config, is_flax_available +from transformers.testing_utils import ( + CaptureLogger, + is_flaky, + is_librosa_available, + is_pt_flax_cross_test, + is_pyctcdecode_available, + require_flax, + require_librosa, + require_pyctcdecode, + require_soundfile, + run_test_in_subprocess, + slow, +) + +from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, random_attention_mask + + +if is_flax_available(): + import jax + import jax.numpy as jnp + import optax + from flax.traverse_util import flatten_dict + + from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Processor + from transformers.models.wav2vec2.modeling_flax_wav2vec2 import ( + FlaxWav2Vec2ForCTC, + FlaxWav2Vec2ForPreTraining, + FlaxWav2Vec2GumbelVectorQuantizer, + FlaxWav2Vec2Model, + _compute_mask_indices, + _sample_negative_indices, + ) + + +if is_pyctcdecode_available(): + import pyctcdecode.decoder + + from transformers import Wav2Vec2ProcessorWithLM + from transformers.models.wav2vec2_with_lm import processing_wav2vec2_with_lm + + +if is_librosa_available(): + import librosa + + +def _test_wav2vec2_with_lm_invalid_pool(in_queue, out_queue, timeout): + error = None + try: + _ = in_queue.get(timeout=timeout) + + ds = load_dataset("common_voice", "es", split="test", streaming=True) + sample = next(iter(ds)) + + resampled_audio = librosa.resample(sample["audio"]["array"], 48_000, 16_000) + + model = FlaxWav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(resampled_audio, return_tensors="np").input_values + + logits = model(input_values).logits + + # use a spawn pool, which should trigger a warning if different than fork + with CaptureLogger(pyctcdecode.decoder.logger) as cl, multiprocessing.get_context("spawn").Pool(1) as pool: + transcription = processor.batch_decode(np.array(logits), pool).text + + unittest.TestCase().assertIn("Falling back to sequential decoding.", cl.out) + unittest.TestCase().assertEqual(transcription[0], "bien y qué regalo vas a abrir primero") + + # force batch_decode to internally create a spawn pool, which should trigger a warning if different than fork + multiprocessing.set_start_method("spawn", force=True) + with CaptureLogger(processing_wav2vec2_with_lm.logger) as cl: + transcription = processor.batch_decode(np.array(logits)).text + + unittest.TestCase().assertIn("Falling back to sequential decoding.", cl.out) + unittest.TestCase().assertEqual(transcription[0], "bien y qué regalo vas a abrir primero") + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +class FlaxWav2Vec2ModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=1024, # speech is longer + is_training=False, + hidden_size=24, + feat_extract_norm="layer", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout_prob=0.1, # this is most likely not correctly set yet + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + vocab_size=32, + do_stable_layer_norm=True, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout_prob = hidden_dropout_prob + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.scope = scope + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = Wav2Vec2Config( + do_stable_layer_norm=self.do_stable_layer_norm, + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout_prob=self.hidden_dropout_prob, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + ) + + return config, input_values, attention_mask + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_values, attention_mask = config_and_inputs + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_flax +class FlaxWav2Vec2ModelTest(FlaxModelTesterMixin, unittest.TestCase): + all_model_classes = ( + (FlaxWav2Vec2Model, FlaxWav2Vec2ForCTC, FlaxWav2Vec2ForPreTraining) if is_flax_available() else () + ) + + def setUp(self): + self.model_tester = FlaxWav2Vec2ModelTester(self) + + def test_train(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + input_values = inputs_dict["input_values"] + attention_mask = inputs_dict["attention_mask"] + + model = FlaxWav2Vec2ForPreTraining(config) + + features_shape = ( + input_values.shape[0], + model._get_feat_extract_output_lengths(np.array(input_values.shape[1])), + ) + + batch_size, sequence_length = features_shape[:2] + + mask_prob = 0.5 + mask_length = 4 + mask_time_indices = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + + dropout_rng, gumbel_rng = jax.random.split(jax.random.PRNGKey(0)) + + output = model( + input_values, + attention_mask=attention_mask, + mask_time_indices=mask_time_indices, + train=True, + dropout_rng=dropout_rng, + gumbel_rng=gumbel_rng, + )[0] + + self.assertTrue(output.shape == (batch_size, sequence_length, model.config.proj_codevector_dim)) + + # overwrite because of `input_values` + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.__call__) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["input_values", "attention_mask"] + self.assertListEqual(arg_names[:2], expected_arg_names) + + # overwrite because of `input_values` + def test_jit_compilation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def model_jitted(input_values, attention_mask=None, **kwargs): + return model(input_values=input_values, attention_mask=attention_mask, **kwargs) + + with self.subTest("JIT Enabled"): + jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + def test_freeze_feature_encoder(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + input_values = inputs_dict["input_values"] + attention_mask = inputs_dict["attention_mask"] + + model = FlaxWav2Vec2ForPreTraining(config) + params = model.params + + # dummy loss function + def compute_loss( + params, input_values, attention_mask, freeze_feature_encoder: bool = False, epsilon: float = 1e-8 + ): + outputs = model( + input_values, + attention_mask=attention_mask, + freeze_feature_encoder=freeze_feature_encoder, + params=params, + ) + # compute cosine similarity of projected and projected_quantized states + cosine_sim = optax.cosine_similarity( + outputs.projected_states, outputs.projected_quantized_states, epsilon=epsilon + ) + loss = cosine_sim.sum() + return loss, outputs.to_tuple() + + # transform the loss function to get the gradients + grad_fn = jax.value_and_grad(compute_loss, has_aux=True) + + # compute loss, outputs and gradients for unfrozen model + (loss, outputs), grads = grad_fn(params, input_values, attention_mask, freeze_feature_encoder=False) + + # compare to loss, outputs and gradients for frozen model + (loss_frozen, outputs_frozen), grads_frozen = grad_fn( + params, input_values, attention_mask, freeze_feature_encoder=True + ) + + # ensure that the outputs and losses remain precisely equal + for output, output_frozen in zip(outputs, outputs_frozen): + self.assertTrue((output == output_frozen).all()) + self.assertEqual(loss, loss_frozen) + + grads = flatten_dict(grads) + grads_frozen = flatten_dict(grads_frozen) + + # ensure that the dicts of gradients contain the same keys + self.assertEqual(grads.keys(), grads_frozen.keys()) + + # ensure that the gradients of the feature extractor layers are precisely zero when frozen and contain non-zero entries when unfrozen + feature_extractor_grads = tuple(grads[k] for k in grads if "feature_extractor" in k) + feature_extractor_grads_frozen = tuple(grads_frozen[k] for k in grads_frozen if "feature_extractor" in k) + + for feature_extractor_grad, feature_extractor_grad_frozen in zip( + feature_extractor_grads, feature_extractor_grads_frozen + ): + self.assertTrue((feature_extractor_grad_frozen == 0.0).all()) + self.assertTrue((feature_extractor_grad > 0.0).any()) + + # ensure that the gradients of all unfrozen layers remain equal, i.e. all layers excluding the frozen 'feature_extractor' + grads = tuple(grads[k] for k in grads if "feature_extractor" not in k) + grads_frozen = tuple(grads_frozen[k] for k in grads_frozen if "feature_extractor" not in k) + + for grad, grad_frozen in zip(grads, grads_frozen): + self.assertTrue((grad == grad_frozen).all()) + + @slow + def test_model_from_pretrained(self): + for model_class_name in self.all_model_classes: + model = model_class_name.from_pretrained("facebook/wav2vec2-large-960h-lv60-self", from_pt=True) + outputs = model(np.ones((1, 1024), dtype="f4")) + self.assertIsNotNone(outputs) + + @is_pt_flax_cross_test + @is_flaky() + def test_equivalence_pt_to_flax(self): + super().test_equivalence_pt_to_flax() + + +@require_flax +class FlaxWav2Vec2UtilsTest(unittest.TestCase): + def test_compute_mask_indices(self): + batch_size = 4 + sequence_length = 60 + mask_prob = 0.5 + mask_length = 1 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + + self.assertListEqual(mask.sum(axis=-1).tolist(), [mask_prob * sequence_length for _ in range(batch_size)]) + + def test_compute_mask_indices_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + + # because of overlap mask don't have to add up exactly to `mask_prob * sequence_length`, but have to be smaller or equal + for batch_sum in mask.sum(axis=-1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + def test_compute_mask_indices_attn_mask_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + attention_mask = np.ones((batch_size, sequence_length), dtype=np.int32) + attention_mask[:2, sequence_length // 2 :] = 0 + + mask = _compute_mask_indices( + (batch_size, sequence_length), mask_prob, mask_length, attention_mask=attention_mask + ) + + for batch_sum in mask.sum(axis=-1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + self.assertTrue(mask[:2, sequence_length // 2 :].sum() == 0) + + def test_compute_perplexity(self): + probs = np.arange(100).reshape(2, 5, 10) / 100 + + ppl = FlaxWav2Vec2GumbelVectorQuantizer._compute_perplexity(probs) + self.assertTrue(abs(ppl.item() - 141.4291) < 1e-3) + + # mask half of the input + mask = np.ones((2,), dtype=bool) + mask[0] = 0 + + ppl = FlaxWav2Vec2GumbelVectorQuantizer._compute_perplexity(probs, mask) + self.assertTrue(abs(ppl.item() - 58.6757) < 1e-3) + + def test_sample_negatives(self): + batch_size = 2 + sequence_length = 10 + hidden_size = 4 + num_negatives = 3 + + features = (np.arange(sequence_length * hidden_size) // hidden_size).reshape( + sequence_length, hidden_size + ) # each value in vector consits of same value + features = np.broadcast_to(features[None, :], (batch_size, sequence_length, hidden_size)) + + negative_indices = _sample_negative_indices(features.shape, num_negatives) + + features = features.reshape(-1, hidden_size) # BTC => (BxT)C + # take negative vectors from sampled indices + sampled_negatives = features[negative_indices.reshape(-1)] + negatives = sampled_negatives.reshape(batch_size, sequence_length, num_negatives, hidden_size).transpose( + 2, 0, 1, 3 + ) + + self.assertTrue(negatives.shape == (num_negatives, batch_size, sequence_length, hidden_size)) + + # make sure no negatively sampled vector is actually a positive one + for negative in negatives: + self.assertTrue(((negative - features.reshape(negative.shape)) == 0).sum() == 0.0) + + # make sure that full vectors are sampled and not values of vectors + # => this means that `unique()` yields a single value for `hidden_size` dim + self.assertEqual(np.unique(negatives, axis=-1).shape, (num_negatives, batch_size, sequence_length, 1)) + + def test_sample_negatives_with_attn_mask(self): + batch_size = 2 + sequence_length = 10 + hidden_size = 4 + num_negatives = 3 + + features = (np.arange(sequence_length * hidden_size) // hidden_size).reshape( + sequence_length, hidden_size + ) # each value in vector consits of same value + + # second half of last input tensor is padded + attention_mask = np.ones((batch_size, sequence_length), dtype=np.int8) + attention_mask[-1, sequence_length // 2 :] = 0 + + forbidden_indices = ( + np.arange(sequence_length // 2, sequence_length, dtype=np.int32) + (batch_size - 1) * sequence_length + ).tolist() + + features = np.broadcast_to(features[None, :], (batch_size, sequence_length, hidden_size)) + + negative_indices = _sample_negative_indices(features.shape, num_negatives, attention_mask=attention_mask) + + # make sure that no padding tokens are sampled + self.assertTrue(all(idx not in negative_indices for idx in forbidden_indices)) + + features = features.reshape(-1, hidden_size) # BTC => (BxT)C + # take negative vectors from sampled indices + sampled_negatives = features[negative_indices.reshape(-1)] + negatives = sampled_negatives.reshape(batch_size, sequence_length, num_negatives, hidden_size).transpose( + 2, 0, 1, 3 + ) + + self.assertTrue(negatives.shape == (num_negatives, batch_size, sequence_length, hidden_size)) + + # make sure no negatively sampled vector is actually a positive one + for negative in negatives: + self.assertTrue(((negative - features.reshape(negative.shape)) == 0).sum() == 0.0) + + # make sure that full vectors are sampled and not just slices of vectors + # => this means that `unique()` yields a single value for `hidden_size` dim + self.assertEqual(np.unique(negatives, axis=-1).shape, (num_negatives, batch_size, sequence_length, 1)) + + +@require_flax +@require_soundfile +@slow +class FlaxWav2Vec2ModelIntegrationTest(unittest.TestCase): + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter( + lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] + )[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_inference_ctc_robust_batched(self): + model = FlaxWav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-large-960h-lv60-self", from_pt=True) + processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-large-960h-lv60-self", do_lower_case=True) + + input_speech = self._load_datasamples(4) + + inputs = processor(input_speech, return_tensors="np", padding=True) + + input_values = inputs.input_values + attention_mask = inputs.attention_mask + + logits = model(input_values, attention_mask=attention_mask).logits + + predicted_ids = jnp.argmax(logits, axis=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore", + "the cut on his chest still dripping blood the ache of his overstrained eyes even the soaring arena around" + " him with the thousands of spectators were trivialities not worth thinking about", + "his instant panic was followed by a small sharp blow high on his chest", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + def test_inference_pretrained(self): + model = FlaxWav2Vec2ForPreTraining.from_pretrained("facebook/wav2vec2-large-lv60", from_pt=True) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( + "facebook/wav2vec2-large-lv60", return_attention_mask=True + ) + input_speech = self._load_datasamples(2) + + inputs_dict = feature_extractor(input_speech, return_tensors="np", padding=True) + + features_shape = ( + inputs_dict["input_values"].shape[0], + model._get_feat_extract_output_lengths(np.array(inputs_dict["input_values"].shape[1])), + ) + + mask_time_indices = _compute_mask_indices( + features_shape, + model.config.mask_time_prob, + model.config.mask_time_length, + min_masks=2, + ) + + outputs = model( + inputs_dict.input_values, + attention_mask=inputs_dict.attention_mask, + mask_time_indices=mask_time_indices, + ) + + # compute cosine similarity + cosine_sim = optax.cosine_similarity( + outputs.projected_states, outputs.projected_quantized_states, epsilon=1e-8 + ) + + # retrieve cosine sim of masked features + cosine_sim_masked = cosine_sim[mask_time_indices] + + # ... now compare to randomly initialized model + + config = Wav2Vec2Config.from_pretrained("facebook/wav2vec2-large-lv60") + model_rand = FlaxWav2Vec2ForPreTraining(config) + + outputs_rand = model_rand( + inputs_dict.input_values, + attention_mask=inputs_dict.attention_mask, + mask_time_indices=mask_time_indices, + ) + + # compute cosine similarity + cosine_sim_rand = optax.cosine_similarity( + outputs_rand.projected_states, outputs_rand.projected_quantized_states + ) + + # retrieve cosine sim of masked features + cosine_sim_masked_rand = cosine_sim_rand[mask_time_indices] + + # a pretrained wav2vec2 model has learned to predict the quantized latent states + # => the cosine similarity between quantized states and predicted states > 0.5 + # a random wav2vec2 model has not learned to predict the quantized latent states + # => the cosine similarity between quantized states and predicted states is very likely < 0.1 + self.assertTrue(cosine_sim_masked.mean().item() - 5 * cosine_sim_masked_rand.mean().item() > 0) + + @require_pyctcdecode + @require_librosa + def test_wav2vec2_with_lm(self): + ds = load_dataset("common_voice", "es", split="test", streaming=True) + sample = next(iter(ds)) + + resampled_audio = librosa.resample(sample["audio"]["array"], 48_000, 16_000) + + model = FlaxWav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(resampled_audio, return_tensors="np").input_values + + logits = model(input_values).logits + + transcription = processor.batch_decode(np.array(logits)).text + + self.assertEqual(transcription[0], "bien y qué regalo vas a abrir primero") + + @require_pyctcdecode + @require_librosa + def test_wav2vec2_with_lm_pool(self): + ds = load_dataset("common_voice", "es", split="test", streaming=True) + sample = next(iter(ds)) + + resampled_audio = librosa.resample(sample["audio"]["array"], 48_000, 16_000) + + model = FlaxWav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(resampled_audio, return_tensors="np").input_values + + logits = model(input_values).logits + + # test user-managed pool + with multiprocessing.get_context("fork").Pool(2) as pool: + transcription = processor.batch_decode(np.array(logits), pool).text + + self.assertEqual(transcription[0], "bien y qué regalo vas a abrir primero") + + # user-managed pool + num_processes should trigger a warning + with CaptureLogger(processing_wav2vec2_with_lm.logger) as cl, multiprocessing.get_context("fork").Pool( + 2 + ) as pool: + transcription = processor.batch_decode(np.array(logits), pool, num_processes=2).text + + self.assertIn("num_process", cl.out) + self.assertIn("it will be ignored", cl.out) + + self.assertEqual(transcription[0], "bien y qué regalo vas a abrir primero") + + @require_pyctcdecode + @require_librosa + def test_wav2vec2_with_lm_invalid_pool(self): + run_test_in_subprocess(test_case=self, target_func=_test_wav2vec2_with_lm_invalid_pool, inputs=None) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_tf_wav2vec2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_tf_wav2vec2.py new file mode 100644 index 0000000000000000000000000000000000000000..7af3cd34e8a4298e26c03628e11399db7f539443 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_tf_wav2vec2.py @@ -0,0 +1,932 @@ +# coding=utf-8 +# 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. + + +from __future__ import annotations + +import copy +import gc +import glob +import inspect +import math +import multiprocessing +import os +import tempfile +import traceback +import unittest + +import numpy as np +import pytest +from datasets import load_dataset +from huggingface_hub import snapshot_download + +from transformers import Wav2Vec2Config, is_tf_available +from transformers.testing_utils import ( + CaptureLogger, + is_flaky, + is_pt_tf_cross_test, + require_librosa, + require_pyctcdecode, + require_tf, + run_test_in_subprocess, + slow, +) +from transformers.utils import is_librosa_available, is_pyctcdecode_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import ( + AutoFeatureExtractor, + TFWav2Vec2ForCTC, + TFWav2Vec2ForSequenceClassification, + TFWav2Vec2Model, + Wav2Vec2Processor, + ) + from transformers.models.wav2vec2.modeling_tf_wav2vec2 import _compute_mask_indices + + +if is_pyctcdecode_available(): + import pyctcdecode.decoder + + from transformers import Wav2Vec2ProcessorWithLM + from transformers.models.wav2vec2_with_lm import processing_wav2vec2_with_lm + + +if is_librosa_available(): + import librosa + + +def _test_wav2vec2_with_lm_invalid_pool(in_queue, out_queue, timeout): + error = None + try: + _ = in_queue.get(timeout=timeout) + + downloaded_folder = snapshot_download("patrickvonplaten/common_voice_es_sample") + file_path = glob.glob(downloaded_folder + "/*")[0] + sample = librosa.load(file_path, sr=16_000)[0] + + model = TFWav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(sample, return_tensors="tf").input_values + + logits = model(input_values).logits + + # use a spawn pool, which should trigger a warning if different than fork + with CaptureLogger(pyctcdecode.decoder.logger) as cl, multiprocessing.get_context("spawn").Pool(1) as pool: + transcription = processor.batch_decode(logits.numpy(), pool).text + + unittest.TestCase().assertIn("Falling back to sequential decoding.", cl.out) + unittest.TestCase().assertEqual(transcription[0], "el libro ha sido escrito por cervantes") + + # force batch_decode to internally create a spawn pool, which should trigger a warning if different than fork + multiprocessing.set_start_method("spawn", force=True) + with CaptureLogger(processing_wav2vec2_with_lm.logger) as cl: + transcription = processor.batch_decode(logits.numpy()).text + + unittest.TestCase().assertIn("Falling back to sequential decoding.", cl.out) + unittest.TestCase().assertEqual(transcription[0], "el libro ha sido escrito por cervantes") + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +@require_tf +class TFWav2Vec2ModelTester: + def __init__( + self, + parent, + batch_size=3, + seq_length=1024, + is_training=False, + hidden_size=16, + feat_extract_norm="group", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout_prob=0.1, # this is most likely not correctly set yet + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + vocab_size=32, + do_stable_layer_norm=False, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout_prob = hidden_dropout_prob + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.scope = scope + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length + + def prepare_config_and_inputs(self): + input_values = tf.cast(ids_tensor([self.batch_size, self.seq_length], 32768), tf.float32) / 32768.0 + attention_mask = tf.ones_like(input_values) + + config = Wav2Vec2Config( + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout_prob=self.hidden_dropout_prob, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + do_stable_layer_norm=self.do_stable_layer_norm, + ) + + return config, input_values, attention_mask + + def create_and_check_model(self, config, input_values, attention_mask): + model = TFWav2Vec2Model(config) + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_batch_inference(self, config, input_values, *args): + # test does not pass for models making use of `group_norm` + # check: https://github.com/pytorch/fairseq/issues/3227 + config.layerdrop = 0.0 + model = TFWav2Vec2Model(config) + + input_values = input_values[:3] + attention_mask = tf.ones_like(input_values) + + input_lengths = tf.constant([input_values.shape[-1] // i for i in [4, 2, 1]]) + length_mask = tf.sequence_mask(input_lengths, dtype=tf.float32) + + # convert values that are over input_lengths to padding + input_values = input_values * length_mask + attention_mask = attention_mask * length_mask + + batch_outputs = model(input_values, attention_mask=attention_mask, training=False).last_hidden_state + + for i in range(input_values.shape[0]): + input_slice = input_values[i : i + 1, : input_lengths[i]] + output = model(input_slice, training=False).last_hidden_state + + batch_output = batch_outputs[i : i + 1, : output.shape[1]] + self.parent.assertTrue(np.allclose(output, batch_output, atol=1e-3)) + + def check_ctc_loss(self, config, input_values, *args): + model = TFWav2Vec2ForCTC(config) + + input_values = input_values[:3] + attention_mask = tf.ones_like(input_values) + + input_lengths = tf.constant([input_values.shape[-1] // i for i in [4, 2, 1]]) + max_length_labels = model.wav2vec2._get_feat_extract_output_lengths(input_lengths) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) + + length_mask = tf.sequence_mask(input_lengths, dtype=tf.float32) + + # convert values that are over input_lengths to padding + input_values = input_values * length_mask + attention_mask = attention_mask * length_mask + + model.config.ctc_loss_reduction = "sum" + sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss + + model.config.ctc_loss_reduction = "mean" + mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss + + self.parent.assertTrue(abs(labels.shape[0] * mean_loss - sum_loss) < 1e-2) + + def check_seq_classifier_loss(self, loss, config, input_values, *args): + model = TFWav2Vec2ForSequenceClassification(config) + + input_values = input_values[:3] + attention_mask = tf.ones(input_values.shape, dtype=tf.int32) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = tf.random.uniform((input_values.shape[0],), maxval=len(model.config.id2label), dtype=tf.int32) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + training = False + masked_loss = ( + model(input_values, attention_mask=attention_mask, labels=labels, training=training).loss.numpy().item() + ) + unmasked_loss = model(input_values, labels=labels, training=training).loss.numpy().item() + + assert isinstance(masked_loss, float) + assert isinstance(unmasked_loss, float) + assert masked_loss != unmasked_loss + + def check_training(self, config, input_values, *args): + model = TFWav2Vec2ForCTC(config) + + # freeze feature encoder + model.freeze_feature_encoder() + + input_values = input_values[:3] + + input_lengths = tf.constant([input_values.shape[-1] // i for i in [4, 2, 1]]) + max_length_labels = model.wav2vec2._get_feat_extract_output_lengths(input_lengths) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) + + length_mask = tf.sequence_mask(input_lengths, dtype=tf.float32) + + input_values = input_values * length_mask + + pad_size = max(max_length_labels) - labels.shape[1] + labels = tf.pad(labels, ((0, 0), (0, pad_size)), constant_values=-100) + + loss = model(input_values, labels=labels, training=True).loss + + self.parent.assertFalse(tf.math.is_inf(loss)) + + def check_labels_out_of_vocab(self, config, input_values, *args): + model = TFWav2Vec2ForCTC(config) + input_lengths = tf.constant([input_values.shape[-1] // i for i in [4, 2, 1]]) + max_length_labels = model.wav2vec2._get_feat_extract_output_lengths(input_lengths) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size + 500) + with pytest.raises(ValueError): + model(input_values, labels=labels) + + def prepare_config_and_inputs_for_common(self): + config, input_values, attention_mask = self.prepare_config_and_inputs() + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_tf +class TFWav2Vec2ModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (TFWav2Vec2Model, TFWav2Vec2ForCTC, TFWav2Vec2ForSequenceClassification) if is_tf_available() else () + ) + pipeline_model_mapping = ( + {"audio-classification": TFWav2Vec2ForSequenceClassification, "feature-extraction": TFWav2Vec2Model} + if is_tf_available() + else {} + ) + test_resize_embeddings = False + test_head_masking = False + test_onnx = False + + def setUp(self): + self.model_tester = TFWav2Vec2ModelTester(self) + self.config_tester = ConfigTester(self, config_class=Wav2Vec2Config, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + # overwrite because input_values != input_ids + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["input_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + # overwrite because input_values != input_ids + def test_keyword_and_dict_args(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs_dict = model(inputs) + + inputs_keywords = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + input_values = inputs_keywords.pop("input_values", None) + outputs_keywords = model(input_values, **inputs_keywords) + output_dict = outputs_dict[0].numpy() + output_keywords = outputs_keywords[0].numpy() + + self.assertLess(np.sum(np.abs(output_dict - output_keywords)), 1e-6) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_hidden_states_output(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_hidden_states_output(config, inputs_dict, model_class): + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + + hidden_states = outputs.hidden_states + self.assertEqual(config.output_attentions, False) + self.assertEqual(len(hidden_states), expected_num_layers) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.output_seq_length, self.model_tester.hidden_size], + ) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(config, inputs_dict, model_class) + + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + check_hidden_states_output(config, inputs_dict, model_class) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + @is_flaky() + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + def test_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_training(*config_and_inputs) + + @unittest.skip(reason="Wav2Vec2 has no input embeddings") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="Wav2Vec2 has no tokens embeddings") + def test_resize_tokens_embeddings(self): + pass + + @unittest.skip(reason="Wav2Vec2 has no input embeddings") + def test_model_common_attributes(self): + pass + + @slow + def test_model_from_pretrained(self): + model = TFWav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h") + self.assertIsNotNone(model) + + @unittest.skip(reason="Fix me! Wav2Vec2 hits OOM errors when loss is computed on full batch") + def test_dataset_conversion(self): + # TODO: (Amy) - check whether skipping CTC model resolves this issue and possible resolutions for CTC + pass + + @unittest.skip(reason="Fix me! Wav2Vec2 hits OOM errors when loss is computed on full batch") + def test_keras_fit(self): + # TODO: (Amy) - check whether skipping CTC model resolves this issue and possible resolutions for CTC + pass + + @is_pt_tf_cross_test + def test_pt_tf_model_equivalence(self, allow_missing_keys=False): + # We override the base test here to skip loss calculation for Wav2Vec2 models because the loss is massive with + # the default labels and frequently overflows to inf or exceeds numerical tolerances between TF/PT + import torch + + import transformers + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # Make sure no sequence has all zeros as attention mask, otherwise some tests fail due to the inconsistency + # of the usage `1e-4`, `1e-9`, `1e-30`, `-inf`. + # TODO: Use a uniform value for all models, make sure all tests pass without this processing, and remove it. + self._make_attention_mask_non_null(inputs_dict) + + pt_model_class_name = model_class.__name__[2:] # Skip the "TF" at the beginning + pt_model_class = getattr(transformers, pt_model_class_name) + + tf_model = model_class(config) + pt_model = pt_model_class(config) + + tf_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + + # Check we can load pt model in tf and vice-versa with model => model functions + tf_model = transformers.load_pytorch_model_in_tf2_model( + tf_model, pt_model, tf_inputs=tf_inputs_dict, allow_missing_keys=allow_missing_keys + ) + pt_model = transformers.load_tf2_model_in_pytorch_model( + pt_model, tf_model, allow_missing_keys=allow_missing_keys + ) + + # Original test: check without `labels` + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + + # Check we can load pt model in tf and vice-versa with checkpoint => model functions + with tempfile.TemporaryDirectory() as tmpdirname: + pt_checkpoint_path = os.path.join(tmpdirname, "pt_model.bin") + torch.save(pt_model.state_dict(), pt_checkpoint_path) + tf_model = transformers.load_pytorch_checkpoint_in_tf2_model( + tf_model, pt_checkpoint_path, allow_missing_keys=allow_missing_keys + ) + + tf_checkpoint_path = os.path.join(tmpdirname, "tf_model.h5") + tf_model.save_weights(tf_checkpoint_path) + pt_model = transformers.load_tf2_checkpoint_in_pytorch_model( + pt_model, tf_checkpoint_path, allow_missing_keys=allow_missing_keys + ) + + # Original test: check without `labels` + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + + +@require_tf +class TFWav2Vec2RobustModelTest(TFModelTesterMixin, unittest.TestCase): + all_model_classes = ( + (TFWav2Vec2Model, TFWav2Vec2ForCTC, TFWav2Vec2ForSequenceClassification) if is_tf_available() else () + ) + test_resize_embeddings = False + test_head_masking = False + test_onnx = False + + def setUp(self): + self.model_tester = TFWav2Vec2ModelTester( + self, + conv_stride=(3, 3, 3), + feat_extract_norm="layer", + do_stable_layer_norm=True, + scope="robust", + ) + self.config_tester = ConfigTester(self, config_class=Wav2Vec2Config, hidden_size=37) + + # overwrite because input_values != input_ids + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["input_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + # overwrite because input_values != input_ids + def test_keyword_and_dict_args(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs_dict = model(inputs) + + inputs_keywords = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + input_values = inputs_keywords.pop("input_values", None) + outputs_keywords = model(input_values, **inputs_keywords) + output_dict = outputs_dict[0].numpy() + output_keywords = outputs_keywords[0].numpy() + + self.assertLess(np.sum(np.abs(output_dict - output_keywords)), 1e-6) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_hidden_states_output(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_hidden_states_output(config, inputs_dict, model_class): + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + + hidden_states = outputs.hidden_states + self.assertEqual(config.output_attentions, False) + self.assertEqual(len(hidden_states), expected_num_layers) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.output_seq_length, self.model_tester.hidden_size], + ) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(config, inputs_dict, model_class) + + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + check_hidden_states_output(config, inputs_dict, model_class) + + def test_batched_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_batch_inference(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + # TODO (Joao): fix me + @unittest.skip("Broke with TF 2.10") + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + def test_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_training(*config_and_inputs) + + @unittest.skip(reason="Wav2Vec2 has no input embeddings") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="Wav2Vec2 has no tokens embeddings") + def test_resize_tokens_embeddings(self): + pass + + @unittest.skip(reason="Wav2Vec2 has no input embeddings") + def test_model_common_attributes(self): + pass + + @slow + def test_model_from_pretrained(self): + model = TFWav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h") + self.assertIsNotNone(model) + + @unittest.skip(reason="Fix me! Wav2Vec2 hits OOM errors when loss is computed on full batch") + def test_dataset_conversion(self): + # TODO: (Amy) - check whether skipping CTC model resolves this issue and possible resolutions for CTC + pass + + @unittest.skip(reason="Fix me! Wav2Vec2 hits OOM errors when loss is computed on full batch") + def test_keras_fit(self): + # TODO: (Amy) - check whether skipping CTC model resolves this issue and possible resolutions for CTC + pass + + @is_pt_tf_cross_test + def test_pt_tf_model_equivalence(self, allow_missing_keys=False): + # We override the base test here to skip loss calculation for Wav2Vec2 models because the loss is massive with + # the default labels and frequently overflows to inf or exceeds numerical tolerances between TF/PT + import torch + + import transformers + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # Make sure no sequence has all zeros as attention mask, otherwise some tests fail due to the inconsistency + # of the usage `1e-4`, `1e-9`, `1e-30`, `-inf`. + # TODO: Use a uniform value for all models, make sure all tests pass without this processing, and remove it. + self._make_attention_mask_non_null(inputs_dict) + + pt_model_class_name = model_class.__name__[2:] # Skip the "TF" at the beginning + pt_model_class = getattr(transformers, pt_model_class_name) + + tf_model = model_class(config) + pt_model = pt_model_class(config) + + tf_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + + # Check we can load pt model in tf and vice-versa with model => model functions + tf_model = transformers.load_pytorch_model_in_tf2_model( + tf_model, pt_model, tf_inputs=tf_inputs_dict, allow_missing_keys=allow_missing_keys + ) + pt_model = transformers.load_tf2_model_in_pytorch_model( + pt_model, tf_model, allow_missing_keys=allow_missing_keys + ) + + # Original test: check without `labels` + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + + # Check we can load pt model in tf and vice-versa with checkpoint => model functions + with tempfile.TemporaryDirectory() as tmpdirname: + pt_checkpoint_path = os.path.join(tmpdirname, "pt_model.bin") + torch.save(pt_model.state_dict(), pt_checkpoint_path) + tf_model = transformers.load_pytorch_checkpoint_in_tf2_model( + tf_model, pt_checkpoint_path, allow_missing_keys=allow_missing_keys + ) + + tf_checkpoint_path = os.path.join(tmpdirname, "tf_model.h5") + tf_model.save_weights(tf_checkpoint_path) + pt_model = transformers.load_tf2_checkpoint_in_pytorch_model( + pt_model, tf_checkpoint_path, allow_missing_keys=allow_missing_keys + ) + + # Original test: check without `labels` + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + + +@require_tf +class TFWav2Vec2UtilsTest(unittest.TestCase): + def test_compute_mask_indices(self): + batch_size = 4 + sequence_length = 60 + mask_prob = 0.5 + mask_length = 1 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + + self.assertListEqual( + tf.reduce_sum(mask, -1).numpy().tolist(), [mask_prob * sequence_length for _ in range(batch_size)] + ) + + def test_compute_mask_indices_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + + # because of overlap mask don't have to add up exactly to `mask_prob * sequence_length`, but have to be smaller or equal + for batch_sum in tf.reduce_sum(mask, -1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + +@require_tf +@slow +class TFWav2Vec2ModelIntegrationTest(unittest.TestCase): + def tearDown(self): + super().tearDown() + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter( + lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] + )[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def _load_superb(self, task, num_samples): + ds = load_dataset("anton-l/superb_dummy", task, split="test") + + return ds[:num_samples] + + def test_inference_ctc_normal(self): + model = TFWav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") + processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h", do_lower_case=True) + input_speech = self._load_datasamples(1) + + input_values = processor(input_speech, return_tensors="tf", sampling_rate=16000).input_values + + logits = model(input_values).logits + + predicted_ids = tf.argmax(logits, axis=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = ["a man said to the universe sir i exist"] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + def test_inference_ctc_normal_batched(self): + model = TFWav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") + processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h", do_lower_case=True) + + input_speech = self._load_datasamples(2) + + input_values = processor(input_speech, return_tensors="tf", padding=True, sampling_rate=16000).input_values + + logits = model(input_values).logits + + predicted_ids = tf.argmax(logits, axis=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "sweat covered brion's body trickling into the tight lowing cloth that was the only garment he wore", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + def test_inference_ctc_robust_batched(self): + model = TFWav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-large-960h-lv60-self") + processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-large-960h-lv60-self", do_lower_case=True) + + input_speech = self._load_datasamples(4) + + inputs = processor(input_speech, return_tensors="tf", padding=True, sampling_rate=16000) + + input_values = inputs.input_values + attention_mask = inputs.attention_mask + + logits = model(input_values, attention_mask=attention_mask).logits + + predicted_ids = tf.argmax(logits, axis=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore", + "the cut on his chest still dripping blood the ache of his overstrained eyes even the soaring arena around" + " him with the thousands of spectators were trivialities not worth thinking about", + "his instant panic was followed by a small sharp blow high on his chest", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + @require_pyctcdecode + @require_librosa + def test_wav2vec2_with_lm(self): + downloaded_folder = snapshot_download("patrickvonplaten/common_voice_es_sample") + file_path = glob.glob(downloaded_folder + "/*")[0] + sample = librosa.load(file_path, sr=16_000)[0] + + model = TFWav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(sample, return_tensors="tf").input_values + + logits = model(input_values).logits + + transcription = processor.batch_decode(logits.numpy()).text + + self.assertEqual(transcription[0], "el libro ha sido escrito por cervantes") + + @require_pyctcdecode + @require_librosa + def test_wav2vec2_with_lm_pool(self): + downloaded_folder = snapshot_download("patrickvonplaten/common_voice_es_sample") + file_path = glob.glob(downloaded_folder + "/*")[0] + sample = librosa.load(file_path, sr=16_000)[0] + + model = TFWav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(sample, return_tensors="tf").input_values + + logits = model(input_values).logits + + # test user-managed pool + with multiprocessing.get_context("fork").Pool(2) as pool: + transcription = processor.batch_decode(logits.numpy(), pool).text + + self.assertEqual(transcription[0], "el libro ha sido escrito por cervantes") + + # user-managed pool + num_processes should trigger a warning + with CaptureLogger(processing_wav2vec2_with_lm.logger) as cl, multiprocessing.get_context("fork").Pool( + 2 + ) as pool: + transcription = processor.batch_decode(logits.numpy(), pool, num_processes=2).text + + self.assertIn("num_process", cl.out) + self.assertIn("it will be ignored", cl.out) + + self.assertEqual(transcription[0], "el libro ha sido escrito por cervantes") + + @require_pyctcdecode + @require_librosa + def test_wav2vec2_with_lm_invalid_pool(self): + run_test_in_subprocess(test_case=self, target_func=_test_wav2vec2_with_lm_invalid_pool, inputs=None) + + def test_inference_keyword_spotting(self): + model = TFWav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-ks", from_pt=True) + processor = AutoFeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-ks") + input_data = self._load_superb("ks", 4) + inputs = processor(input_data["speech"], return_tensors="tf", padding=True) + input_values = inputs.input_values + attention_mask = inputs.attention_mask + outputs = model(input_values, attention_mask) + predicted_logits, predicted_ids = ( + tf.math.reduce_max(outputs.logits, axis=-1), + tf.argmax(outputs.logits, axis=-1), + ) + expected_labels = [7, 6, 10, 9] + expected_logits = tf.convert_to_tensor([6.1186, 11.8961, 10.2931, 6.0898]) + self.assertListEqual(predicted_ids.numpy().tolist(), expected_labels) + self.assertTrue(np.allclose(predicted_logits, expected_logits, atol=1e-2)) + + def test_inference_intent_classification(self): + model = TFWav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-ic", from_pt=True) + processor = AutoFeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-ic") + input_data = self._load_superb("ic", 4) + inputs = processor(input_data["speech"], return_tensors="tf", padding=True) + input_values = inputs.input_values + attention_mask = inputs.attention_mask + outputs = model(input_values, attention_mask=attention_mask) + predicted_logits_action, predicted_ids_action = ( + tf.math.reduce_max(outputs.logits[:, :6], axis=-1), + tf.argmax(outputs.logits[:, :6], axis=-1), + ) + predicted_logits_object, predicted_ids_object = ( + tf.math.reduce_max(outputs.logits[:, 6:20], axis=-1), + tf.argmax(outputs.logits[:, 6:20], axis=-1), + ) + predicted_logits_location, predicted_ids_location = ( + tf.math.reduce_max(outputs.logits[:, 20:24], axis=-1), + tf.argmax(outputs.logits[:, 20:24], axis=-1), + ) + expected_labels_action = [0, 0, 2, 3] + expected_logits_action = tf.convert_to_tensor([0.4568, 11.0848, 1.6621, 9.3841]) + expected_labels_object = [3, 10, 3, 4] + expected_logits_object = tf.convert_to_tensor([1.5322, 10.7094, 5.2469, 22.1318]) + expected_labels_location = [0, 0, 0, 1] + expected_logits_location = tf.convert_to_tensor([1.5335, 6.5096, 10.5704, 11.0569]) + + self.assertListEqual(predicted_ids_action.numpy().tolist(), expected_labels_action) + self.assertListEqual(predicted_ids_object.numpy().tolist(), expected_labels_object) + self.assertListEqual(predicted_ids_location.numpy().tolist(), expected_labels_location) + + self.assertTrue(np.allclose(predicted_logits_action, expected_logits_action, atol=1e-2)) + self.assertTrue(np.allclose(predicted_logits_object, expected_logits_object, atol=1e-2)) + self.assertTrue(np.allclose(predicted_logits_location, expected_logits_location, atol=1e-2)) + + def test_inference_speaker_identification(self): + model = TFWav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-sid", from_pt=True) + processor = AutoFeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-sid") + input_data = self._load_superb("si", 4) + output_logits = [] + for example in input_data["speech"]: + input = processor(example, return_tensors="tf", padding=True) + output = model(input.input_values, attention_mask=None) + output_logits.append(output.logits[0]) + output_logits = tf.stack(output_logits) + predicted_logits, predicted_ids = tf.math.reduce_max(output_logits, axis=-1), tf.argmax(output_logits, axis=-1) + expected_labels = [251, 1, 1, 3] + expected_logits = tf.convert_to_tensor([37.5627, 71.6362, 64.2419, 31.7778]) + self.assertListEqual(predicted_ids.numpy().tolist(), expected_labels) + self.assertTrue(np.allclose(predicted_logits, expected_logits, atol=1e-2)) + + def test_inference_emotion_recognition(self): + model = TFWav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-er", from_pt=True) + processor = AutoFeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-er") + input_data = self._load_superb("er", 4) + inputs = processor(input_data["speech"], return_tensors="tf", padding=True) + + input_values = inputs.input_values + attention_mask = inputs.attention_mask + outputs = model(input_values, attention_mask=attention_mask) + predicted_logits, predicted_ids = ( + tf.math.reduce_max(outputs.logits, axis=-1), + tf.argmax(outputs.logits, axis=-1), + ) + + expected_labels = [1, 1, 2, 2] + # s3prl logits for the same batch + expected_logits = tf.convert_to_tensor([2.1722, 3.0779, 8.0287, 6.6797]) + + self.assertListEqual(predicted_ids.numpy().tolist(), expected_labels) + self.assertTrue(np.allclose(predicted_logits, expected_logits, atol=1e-2)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_wav2vec2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_wav2vec2.py new file mode 100644 index 0000000000000000000000000000000000000000..353606252c0dd4070cbc54c640e5dd8a76068f5b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_modeling_wav2vec2.py @@ -0,0 +1,1999 @@ +# coding=utf-8 +# 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 Wav2Vec2 model. """ + +import gc +import math +import multiprocessing +import os +import pickle +import tempfile +import traceback +import unittest + +import numpy as np +from datasets import load_dataset + +from transformers import Wav2Vec2Config, is_torch_available +from transformers.testing_utils import ( + CaptureLogger, + backend_empty_cache, + is_pt_flax_cross_test, + is_pyctcdecode_available, + is_torchaudio_available, + require_pyctcdecode, + require_soundfile, + require_torch, + require_torchaudio, + run_test_in_subprocess, + slow, + torch_device, +) +from transformers.utils import is_torch_fx_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from safetensors.torch import save_file as safe_save_file + + from transformers import ( + Wav2Vec2FeatureExtractor, + Wav2Vec2ForAudioFrameClassification, + Wav2Vec2ForCTC, + Wav2Vec2ForMaskedLM, + Wav2Vec2ForPreTraining, + Wav2Vec2ForSequenceClassification, + Wav2Vec2ForXVector, + Wav2Vec2Model, + Wav2Vec2Processor, + ) + from transformers.models.wav2vec2.modeling_wav2vec2 import ( + WAV2VEC2_ADAPTER_PT_FILE, + WAV2VEC2_ADAPTER_SAFE_FILE, + Wav2Vec2GumbelVectorQuantizer, + _compute_mask_indices, + _sample_negative_indices, + ) + + +if is_torchaudio_available(): + import torchaudio + + +if is_pyctcdecode_available(): + import pyctcdecode.decoder + + from transformers import Wav2Vec2ProcessorWithLM + from transformers.models.wav2vec2_with_lm import processing_wav2vec2_with_lm + + +if is_torch_fx_available(): + from transformers.utils.fx import symbolic_trace + + +def _test_wav2vec2_with_lm_invalid_pool(in_queue, out_queue, timeout): + error = None + try: + _ = in_queue.get(timeout=timeout) + + ds = load_dataset("mozilla-foundation/common_voice_11_0", "es", split="test", streaming=True) + sample = next(iter(ds)) + + resampled_audio = torchaudio.functional.resample( + torch.tensor(sample["audio"]["array"]), 48_000, 16_000 + ).numpy() + + model = Wav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm").to( + torch_device + ) + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(resampled_audio, return_tensors="pt").input_values + + with torch.no_grad(): + logits = model(input_values.to(torch_device)).logits + + # use a spawn pool, which should trigger a warning if different than fork + with CaptureLogger(pyctcdecode.decoder.logger) as cl, multiprocessing.get_context("spawn").Pool(1) as pool: + transcription = processor.batch_decode(logits.cpu().numpy(), pool).text + + unittest.TestCase().assertIn("Falling back to sequential decoding.", cl.out) + unittest.TestCase().assertEqual(transcription[0], "habitan aguas poco profundas y rocosas") + + # force batch_decode to internally create a spawn pool, which should trigger a warning if different than fork + multiprocessing.set_start_method("spawn", force=True) + with CaptureLogger(processing_wav2vec2_with_lm.logger) as cl: + transcription = processor.batch_decode(logits.cpu().numpy()).text + + unittest.TestCase().assertIn("Falling back to sequential decoding.", cl.out) + unittest.TestCase().assertEqual(transcription[0], "habitan aguas poco profundas y rocosas") + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +class Wav2Vec2ModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=1024, # speech is longer + is_training=False, + hidden_size=16, + feat_extract_norm="group", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout_prob=0.1, # this is most likely not correctly set yet + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + mask_time_prob=0.5, + mask_time_length=2, + vocab_size=32, + do_stable_layer_norm=False, + num_adapter_layers=1, + adapter_stride=2, + tdnn_dim=(32, 32), + tdnn_kernel=(5, 3), + tdnn_dilation=(1, 2), + xvector_output_dim=32, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout_prob = hidden_dropout_prob + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.num_adapter_layers = num_adapter_layers + self.adapter_stride = adapter_stride + self.mask_time_prob = mask_time_prob + self.mask_time_length = mask_time_length + self.scope = scope + self.tdnn_dim = tdnn_dim + self.tdnn_kernel = tdnn_kernel + self.tdnn_dilation = tdnn_dilation + self.xvector_output_dim = xvector_output_dim + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length + + self.adapter_output_seq_length = (self.output_seq_length - 1) // adapter_stride + 1 + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + + return config, input_values, attention_mask + + def get_config(self): + return Wav2Vec2Config( + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + mask_time_prob=self.mask_time_prob, + mask_time_length=self.mask_time_length, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout_prob=self.hidden_dropout_prob, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + do_stable_layer_norm=self.do_stable_layer_norm, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + num_adapter_layers=self.num_adapter_layers, + adapter_stride=self.adapter_stride, + tdnn_dim=self.tdnn_dim, + tdnn_kernel=self.tdnn_kernel, + tdnn_dilation=self.tdnn_dilation, + xvector_output_dim=self.xvector_output_dim, + ) + + def create_and_check_model(self, config, input_values, attention_mask): + model = Wav2Vec2Model(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_model_with_adapter(self, config, input_values, attention_mask): + config.add_adapter = True + model = Wav2Vec2Model(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.adapter_output_seq_length, self.hidden_size) + ) + + def create_and_check_model_with_adapter_for_ctc(self, config, input_values, attention_mask): + config.add_adapter = True + config.output_hidden_size = 2 * config.hidden_size + model = Wav2Vec2ForCTC(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.adapter_output_seq_length, self.vocab_size) + ) + + def create_and_check_model_with_adapter_proj_dim(self, config, input_values, attention_mask): + config.add_adapter = True + config.output_hidden_size = 8 + model = Wav2Vec2Model(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.adapter_output_seq_length, config.output_hidden_size), + ) + + def create_and_check_model_with_attn_adapter(self, config, input_values, attention_mask): + config.adapter_attn_dim = 16 + model = Wav2Vec2ForCTC(config=config) + + self.parent.assertIsNotNone(model._get_adapters()) + + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.output_seq_length, self.vocab_size)) + + def create_and_check_batch_inference(self, config, input_values, *args): + # test does not pass for models making use of `group_norm` + # check: https://github.com/pytorch/fairseq/issues/3227 + model = Wav2Vec2Model(config=config) + model.to(torch_device) + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0.0 + + batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state + + for i in range(input_values.shape[0]): + input_slice = input_values[i : i + 1, : input_lengths[i]] + output = model(input_slice).last_hidden_state + + batch_output = batch_outputs[i : i + 1, : output.shape[1]] + self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) + + def check_ctc_loss(self, config, input_values, *args): + model = Wav2Vec2ForCTC(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + model.config.ctc_loss_reduction = "sum" + sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + model.config.ctc_loss_reduction = "mean" + mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(sum_loss, float)) + self.parent.assertTrue(isinstance(mean_loss, float)) + + def check_seq_classifier_loss(self, config, input_values, *args): + model = Wav2Vec2ForSequenceClassification(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + unmasked_loss = model(input_values, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(masked_loss, float)) + self.parent.assertTrue(isinstance(unmasked_loss, float)) + self.parent.assertTrue(masked_loss != unmasked_loss) + + def check_ctc_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = Wav2Vec2ForCTC(config=config) + model.to(torch_device) + model.train() + + # freeze feature encoder + model.freeze_feature_encoder() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + if max_length_labels[i] < labels.shape[-1]: + # it's important that we make sure that target lengths are at least + # one shorter than logit lengths to prevent -inf + labels[i, max_length_labels[i] - 1 :] = -100 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_seq_classifier_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = Wav2Vec2ForSequenceClassification(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_xvector_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = Wav2Vec2ForXVector(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_labels_out_of_vocab(self, config, input_values, *args): + model = Wav2Vec2ForCTC(config) + model.to(torch_device) + model.train() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) + + with self.parent.assertRaises(ValueError): + model(input_values, labels=labels) + + def prepare_config_and_inputs_for_common(self): + config, input_values, attention_mask = self.prepare_config_and_inputs() + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class Wav2Vec2ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (Wav2Vec2ForCTC, Wav2Vec2Model, Wav2Vec2ForMaskedLM, Wav2Vec2ForSequenceClassification, Wav2Vec2ForPreTraining) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + { + "audio-classification": Wav2Vec2ForSequenceClassification, + "automatic-speech-recognition": Wav2Vec2ForCTC, + "feature-extraction": Wav2Vec2Model, + "fill-mask": Wav2Vec2ForMaskedLM, + } + if is_torch_available() + else {} + ) + fx_compatible = True + test_pruning = False + test_headmasking = False + + def setUp(self): + self.model_tester = Wav2Vec2ModelTester(self) + self.config_tester = ConfigTester(self, config_class=Wav2Vec2Config, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_with_adapter(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_adapter(*config_and_inputs) + + def test_model_with_adapter_for_ctc(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_adapter_for_ctc(*config_and_inputs) + + def test_model_with_adapter_proj_dim(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_adapter_proj_dim(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_seq_classifier_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_seq_classifier_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_training(*config_and_inputs) + + def test_xvector_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_xvector_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # Wav2Vec2 has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # Wav2Vec2 cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # Wav2Vec2 has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + @is_pt_flax_cross_test + # non-robust architecture does not exist in Flax + def test_equivalence_flax_to_pt(self): + pass + + @is_pt_flax_cross_test + # non-robust architecture does not exist in Flax + def test_equivalence_pt_to_flax(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "objective.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "codevectors") and module.codevectors is not None: + module.codevectors.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + def test_mask_feature_prob_ctc(self): + model = Wav2Vec2ForCTC.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", mask_feature_prob=0.2, mask_feature_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_prob_ctc(self): + model = Wav2Vec2ForCTC.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", mask_time_prob=0.2, mask_time_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + @unittest.skip(reason="Feed forward chunking is not implemented") + def test_feed_forward_chunking(self): + pass + + @slow + def test_model_from_pretrained(self): + model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h") + self.assertIsNotNone(model) + + # Wav2Vec2 cannot be torchscripted because of group norm. + def _create_and_check_torch_fx_tracing(self, config, inputs_dict, output_loss=False): + # TODO: fix it + self.skipTest("torch 2.1 breaks torch fx tests for wav2vec2/hubert.") + + if not is_torch_fx_available() or not self.fx_compatible: + return + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.return_dict = False + + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=output_loss) + + try: + input_names = [ + "attention_mask", + "bbox", + "input_features", + "input_ids", + "input_values", + "pixel_values", + "token_type_ids", + "visual_feats", + "visual_pos", + ] + + labels = inputs.get("labels", None) + start_positions = inputs.get("start_positions", None) + end_positions = inputs.get("end_positions", None) + if labels is not None: + input_names.append("labels") + if start_positions is not None: + input_names.append("start_positions") + if end_positions is not None: + input_names.append("end_positions") + + filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names} + input_names = list(filtered_inputs.keys()) + + model_output = model(**filtered_inputs) + + if ( + isinstance(model, Wav2Vec2ForSequenceClassification) + and not hasattr(model.config, "problem_type") + or model.config.problem_type is None + ): + model.config.problem_type = "single_label_classification" + + traced_model = symbolic_trace(model, input_names) + traced_output = traced_model(**filtered_inputs) + + except Exception as e: + self.fail(f"Couldn't trace module: {e}") + + def flatten_output(output): + flatten = [] + for x in output: + if isinstance(x, (tuple, list)): + flatten += flatten_output(x) + elif not isinstance(x, torch.Tensor): + continue + else: + flatten.append(x) + return flatten + + model_output = flatten_output(model_output) + traced_output = flatten_output(traced_output) + num_outputs = len(model_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], traced_output[i]), + f"traced {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Test that the model can be serialized and restored properly + with tempfile.TemporaryDirectory() as tmp_dir_name: + pkl_file_name = os.path.join(tmp_dir_name, "model.pkl") + try: + with open(pkl_file_name, "wb") as f: + pickle.dump(traced_model, f) + with open(pkl_file_name, "rb") as f: + loaded = pickle.load(f) + except Exception as e: + self.fail(f"Couldn't serialize / deserialize the traced model: {e}") + + loaded_output = loaded(**filtered_inputs) + loaded_output = flatten_output(loaded_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], loaded_output[i]), + f"serialized model {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Avoid memory leak. Without this, each call increase RAM usage by ~20MB. + # (Even with this call, there are still memory leak by ~0.04MB) + self.clear_torch_jit_class_registry() + + @unittest.skip( + "Need to investigate why config.do_stable_layer_norm is set to False here when it doesn't seem to be supported" + ) + def test_flax_from_pt_safetensors(self): + return + + +@require_torch +class Wav2Vec2RobustModelTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + Wav2Vec2ForCTC, + Wav2Vec2Model, + Wav2Vec2ForMaskedLM, + Wav2Vec2ForSequenceClassification, + Wav2Vec2ForPreTraining, + Wav2Vec2ForAudioFrameClassification, + Wav2Vec2ForXVector, + ) + if is_torch_available() + else () + ) + test_pruning = False + test_headmasking = False + + def setUp(self): + self.model_tester = Wav2Vec2ModelTester( + self, conv_stride=(3, 3, 3), feat_extract_norm="layer", do_stable_layer_norm=True + ) + self.config_tester = ConfigTester(self, config_class=Wav2Vec2Config, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_with_adapter(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_adapter(*config_and_inputs) + + def test_model_with_adapter_proj_dim(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_adapter_proj_dim(*config_and_inputs) + + def test_model_with_attn_adapter(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_attn_adapter(*config_and_inputs) + + def test_batched_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_batch_inference(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_seq_classifier_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_seq_classifier_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_training(*config_and_inputs) + + def test_xvector_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_xvector_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # Wav2Vec2 has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # Wav2Vec2 cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # Wav2Vec2 has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "objective.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "codevectors") and module.codevectors is not None: + module.codevectors.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + def test_model_for_pretraining(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = Wav2Vec2ForPreTraining(config).to(torch_device) + + batch_size = inputs_dict["input_values"].shape[0] + feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1])) + + features_shape = (batch_size, feature_seq_length) + + mask_time_indices = _compute_mask_indices( + features_shape, + model.config.mask_time_prob, + model.config.mask_time_length, + min_masks=2, + ) + sampled_negative_indices = _sample_negative_indices(features_shape, 10, mask_time_indices) + + mask_time_indices = torch.from_numpy(mask_time_indices).to(torch_device) + sampled_negative_indices = torch.from_numpy(sampled_negative_indices).to(torch_device) + + loss = model( + inputs_dict["input_values"], + attention_mask=inputs_dict["attention_mask"], + mask_time_indices=mask_time_indices, + sampled_negative_indices=sampled_negative_indices, + ).loss + + # more losses + mask_time_indices[:, : mask_time_indices.shape[-1] // 2] = True + + sampled_negative_indices = _sample_negative_indices(features_shape, 10, mask_time_indices.cpu().numpy()) + sampled_negative_indices = torch.from_numpy(sampled_negative_indices).to(torch_device) + loss_more_masked = model( + inputs_dict["input_values"], + attention_mask=inputs_dict["attention_mask"], + mask_time_indices=mask_time_indices, + sampled_negative_indices=sampled_negative_indices, + ).loss + + # loss_more_masked has to be bigger or equal loss since more masked inputs have to be predicted + self.assertTrue(loss.detach().item() <= loss_more_masked.detach().item()) + + def test_mask_feature_prob_ctc(self): + model = Wav2Vec2ForCTC.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", mask_feature_prob=0.2, mask_feature_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_prob_ctc(self): + model = Wav2Vec2ForCTC.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", mask_time_prob=0.2, mask_time_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_feature_prob_ctc_single_batch(self): + model = Wav2Vec2ForCTC.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", + mask_time_prob=0.2, + mask_feature_prob=0.2, + mask_time_length=2, + mask_feature_length=2, + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", return_attention_mask=True + ) + + batch_duration_in_seconds = [6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (1, 1498, 32)) + + @unittest.skip(reason="Feed forward chunking is not implemented") + def test_feed_forward_chunking(self): + pass + + def test_load_and_set_attn_adapter(self): + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", return_attention_mask=True + ) + + def get_logits(model, input_features): + model = model.to(torch_device) + batch = processor( + input_features, + padding=True, + sampling_rate=processor.feature_extractor.sampling_rate, + return_tensors="pt", + ) + + with torch.no_grad(): + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + return logits + + input_features = [np.random.random(16_000 * s) for s in [1, 3, 2, 6]] + + model = Wav2Vec2ForCTC.from_pretrained("hf-internal-testing/tiny-random-wav2vec2-adapter", target_lang="it") + + logits = get_logits(model, input_features) + + model_2 = Wav2Vec2ForCTC.from_pretrained("hf-internal-testing/tiny-random-wav2vec2-adapter") + model_2.load_adapter("it") + + logits_2 = get_logits(model_2, input_features) + + self.assertTrue(torch.allclose(logits, logits_2, atol=1e-3)) + + # test that loading adapter weights with mismatched vocab sizes can be loaded + def test_load_target_lang_with_mismatched_size(self): + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", return_attention_mask=True + ) + + def get_logits(model, input_features): + model = model.to(torch_device) + batch = processor( + input_features, + padding=True, + sampling_rate=processor.feature_extractor.sampling_rate, + return_tensors="pt", + ) + + with torch.no_grad(): + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + return logits + + input_features = [np.random.random(16_000 * s) for s in [1, 3, 2, 6]] + + model = Wav2Vec2ForCTC.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2-adapter", target_lang="fr", ignore_mismatched_sizes=True + ) + + logits = get_logits(model, input_features) + + model_2 = Wav2Vec2ForCTC.from_pretrained("hf-internal-testing/tiny-random-wav2vec2-adapter") + model_2.load_adapter("fr") + + logits_2 = get_logits(model_2, input_features) + + self.assertTrue(torch.allclose(logits, logits_2, atol=1e-3)) + + def test_load_attn_adapter(self): + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2", return_attention_mask=True + ) + + def get_logits(model, input_features): + model = model.to(torch_device) + batch = processor( + input_features, + padding=True, + sampling_rate=processor.feature_extractor.sampling_rate, + return_tensors="pt", + ) + + with torch.no_grad(): + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + return logits + + input_features = [np.random.random(16_000 * s) for s in [1, 3, 2, 6]] + + model = Wav2Vec2ForCTC.from_pretrained("hf-internal-testing/tiny-random-wav2vec2", adapter_attn_dim=16) + + with tempfile.TemporaryDirectory() as tempdir: + model.save_pretrained(tempdir) + model = Wav2Vec2ForCTC.from_pretrained(tempdir) + + logits = get_logits(model, input_features) + adapter_weights = model._get_adapters() + + # save safe weights + safe_filepath = os.path.join(tempdir, WAV2VEC2_ADAPTER_SAFE_FILE.format("eng")) + safe_save_file(adapter_weights, safe_filepath, metadata={"format": "pt"}) + + model.load_adapter("eng") + model.load_adapter("eng", use_safetensors=True) + + with self.assertRaises(OSError): + model.load_adapter("eng", use_safetensors=False) + with self.assertRaises(Exception): + model.load_adapter("ita", use_safetensors=True) + logits_2 = get_logits(model, input_features) + + self.assertTrue(torch.allclose(logits, logits_2, atol=1e-3)) + + with tempfile.TemporaryDirectory() as tempdir: + model.save_pretrained(tempdir) + model = Wav2Vec2ForCTC.from_pretrained(tempdir) + + logits = get_logits(model, input_features) + adapter_weights = model._get_adapters() + + # save pt weights + pt_filepath = os.path.join(tempdir, WAV2VEC2_ADAPTER_PT_FILE.format("eng")) + torch.save(adapter_weights, pt_filepath) + + model.load_adapter("eng") + model.load_adapter("eng", use_safetensors=False) + + with self.assertRaises(OSError): + model.load_adapter("eng", use_safetensors=True) + + logits_2 = get_logits(model, input_features) + + self.assertTrue(torch.allclose(logits, logits_2, atol=1e-3)) + + model = Wav2Vec2ForCTC.from_pretrained("hf-internal-testing/tiny-random-wav2vec2-adapter") + logits = get_logits(model, input_features) + + model.load_adapter("eng") + model.load_adapter("eng", use_safetensors=False) + model.load_adapter("eng", use_safetensors=True) + + logits_2 = get_logits(model, input_features) + + self.assertTrue(torch.allclose(logits, logits_2, atol=1e-3)) + + @slow + def test_model_from_pretrained(self): + model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h") + self.assertIsNotNone(model) + + +@require_torch +class Wav2Vec2UtilsTest(unittest.TestCase): + def test_compute_mask_indices(self): + batch_size = 4 + sequence_length = 60 + mask_prob = 0.5 + mask_length = 1 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + self.assertListEqual(mask.sum(axis=-1).tolist(), [mask_prob * sequence_length for _ in range(batch_size)]) + + def test_compute_mask_indices_low_prob(self): + # with these settings num_masked_spans=0.5, which means probabilistic rounding + # ensures that in 5 out of 10 method calls, num_masked_spans=0, and in + # the other 5 out of 10, cases num_masked_spans=1 + n_trials = 100 + batch_size = 4 + sequence_length = 100 + mask_prob = 0.05 + mask_length = 10 + + count_dimensions_masked = 0 + count_dimensions_not_masked = 0 + + for _ in range(n_trials): + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + num_masks = torch.sum(mask).item() + + if num_masks > 0: + count_dimensions_masked += 1 + else: + count_dimensions_not_masked += 1 + + # as we test for at least 10 masked dimension and at least + # 10 non-masked dimension, this test could fail with probability: + # P(100 coin flips, at most 9 heads) = 1.66e-18 + self.assertGreater(count_dimensions_masked, int(n_trials * 0.1)) + self.assertGreater(count_dimensions_not_masked, int(n_trials * 0.1)) + + def test_compute_mask_indices_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + # because of overlap mask don't have to add up exactly to `mask_prob * sequence_length`, but have to be smaller or equal + for batch_sum in mask.sum(axis=-1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + def test_compute_mask_indices_attn_mask_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + attention_mask = torch.ones((batch_size, sequence_length), dtype=torch.long, device=torch_device) + attention_mask[:2, sequence_length // 2 :] = 0 + + mask = _compute_mask_indices( + (batch_size, sequence_length), mask_prob, mask_length, attention_mask=attention_mask + ) + mask = torch.from_numpy(mask).to(torch_device) + + for batch_sum in mask.sum(axis=-1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + self.assertTrue(mask[:2, sequence_length // 2 :].sum() == 0) + + def test_compute_mask_indices_short_audio(self): + batch_size = 4 + sequence_length = 100 + mask_prob = 0.05 + mask_length = 10 + + attention_mask = torch.ones((batch_size, sequence_length), dtype=torch.long, device=torch_device) + # force one example to be heavily padded + attention_mask[0, 5:] = 0 + + mask = _compute_mask_indices( + (batch_size, sequence_length), mask_prob, mask_length, attention_mask=attention_mask, min_masks=2 + ) + + # make sure that non-padded examples cannot be padded + self.assertFalse(mask[0][attention_mask[0].to(torch.bool).cpu()].any()) + + def test_compute_perplexity(self): + probs = torch.arange(100, device=torch_device).reshape(2, 5, 10) / 100 + + ppl = Wav2Vec2GumbelVectorQuantizer._compute_perplexity(probs) + self.assertTrue(abs(ppl.item() - 141.4291) < 1e-3) + + # mask half of the input + mask = torch.ones((2,), device=torch_device, dtype=torch.bool) + mask[0] = 0 + + ppl = Wav2Vec2GumbelVectorQuantizer._compute_perplexity(probs, mask) + self.assertTrue(abs(ppl.item() - 58.6757) < 1e-3) + + def test_sample_negatives(self): + batch_size = 2 + sequence_length = 10 + hidden_size = 4 + num_negatives = 3 + sequence = torch.div( + torch.arange(sequence_length * hidden_size, device=torch_device), hidden_size, rounding_mode="floor" + ) + features = sequence.view(sequence_length, hidden_size) # each value in vector consits of same value + features = features[None, :].expand(batch_size, sequence_length, hidden_size).contiguous() + + # sample negative indices + sampled_negative_indices = _sample_negative_indices((batch_size, sequence_length), num_negatives, None) + sampled_negative_indices = torch.from_numpy(sampled_negative_indices).to(torch_device) + negatives = features.view(-1, hidden_size)[sampled_negative_indices.long().view(-1)] + negatives = negatives.view(batch_size, sequence_length, -1, hidden_size).permute(2, 0, 1, 3) + self.assertTrue(negatives.shape == (num_negatives, batch_size, sequence_length, hidden_size)) + + # make sure no negatively sampled vector is actually a positive one + for negative in negatives: + self.assertTrue(((negative - features) == 0).sum() == 0.0) + + # make sure that full vectors are sampled and not values of vectors => this means that `unique()` yields a single value for `hidden_size` dim + self.assertEqual(negatives.unique(dim=-1).shape, (num_negatives, batch_size, sequence_length, 1)) + + def test_sample_negatives_with_mask(self): + batch_size = 2 + sequence_length = 10 + hidden_size = 4 + num_negatives = 3 + + # second half of last input tensor is padded + mask = torch.ones((batch_size, sequence_length), dtype=torch.long, device=torch_device) + mask[-1, sequence_length // 2 :] = 0 + + sequence = torch.div( + torch.arange(sequence_length * hidden_size, device=torch_device), hidden_size, rounding_mode="floor" + ) + features = sequence.view(sequence_length, hidden_size) # each value in vector consits of same value + features = features[None, :].expand(batch_size, sequence_length, hidden_size).contiguous() + + # replace masked feature vectors with -100 to test that those are not sampled + features = torch.where(mask[:, :, None].expand(features.shape).bool(), features, -100) + + # sample negative indices + sampled_negative_indices = _sample_negative_indices( + (batch_size, sequence_length), num_negatives, mask.cpu().numpy() + ) + sampled_negative_indices = torch.from_numpy(sampled_negative_indices).to(torch_device) + negatives = features.view(-1, hidden_size)[sampled_negative_indices.long().view(-1)] + negatives = negatives.view(batch_size, sequence_length, -1, hidden_size).permute(2, 0, 1, 3) + + self.assertTrue((negatives >= 0).all().item()) + + self.assertTrue(negatives.shape == (num_negatives, batch_size, sequence_length, hidden_size)) + + # make sure no negatively sampled vector is actually a positive one + for negative in negatives: + self.assertTrue(((negative - features) == 0).sum() == 0.0) + + # make sure that full vectors are sampled and not values of vectors => this means that `unique()` yields a single value for `hidden_size` dim + self.assertEqual(negatives.unique(dim=-1).shape, (num_negatives, batch_size, sequence_length, 1)) + + +@require_torch +@require_soundfile +@slow +class Wav2Vec2ModelIntegrationTest(unittest.TestCase): + def tearDown(self): + super().tearDown() + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + backend_empty_cache(torch_device) + + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter( + lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] + )[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def _load_superb(self, task, num_samples): + ds = load_dataset("anton-l/superb_dummy", task, split="test") + + return ds[:num_samples] + + def test_inference_ctc_normal(self): + model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") + model.to(torch_device) + processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h", do_lower_case=True) + input_speech = self._load_datasamples(1) + + input_values = processor(input_speech, return_tensors="pt").input_values.to(torch_device) + + with torch.no_grad(): + logits = model(input_values).logits + + predicted_ids = torch.argmax(logits, dim=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = ["a man said to the universe sir i exist"] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + def test_inference_ctc_normal_batched(self): + model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") + model.to(torch_device) + processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h", do_lower_case=True) + + input_speech = self._load_datasamples(2) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + + with torch.no_grad(): + logits = model(input_values).logits + + predicted_ids = torch.argmax(logits, dim=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "sweat covered brion's body trickling into the tight lowing cloth that was the only garment he wore", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + def test_inference_ctc_robust_batched(self): + model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-large-960h-lv60-self").to(torch_device) + processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-large-960h-lv60-self", do_lower_case=True) + + input_speech = self._load_datasamples(4) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + + with torch.no_grad(): + logits = model(input_values, attention_mask=attention_mask).logits + + predicted_ids = torch.argmax(logits, dim=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore", + "the cut on his chest still dripping blood the ache of his overstrained eyes even the soaring arena around" + " him with the thousands of spectators were trivialities not worth thinking about", + "his instant panic was followed by a small sharp blow high on his chest", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + @unittest.skipIf(torch_device != "cpu", "cannot make deterministic on GPU") + def test_inference_integration(self): + model = Wav2Vec2ForPreTraining.from_pretrained("facebook/wav2vec2-base") + model.to(torch_device) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/wav2vec2-base") + input_speech = self._load_datasamples(2) + + inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) + + batch_size = inputs_dict["input_values"].shape[0] + feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1])) + + features_shape = (batch_size, feature_seq_length) + + np.random.seed(4) + mask_time_indices = _compute_mask_indices( + features_shape, + model.config.mask_time_prob, + model.config.mask_time_length, + min_masks=2, + ) + mask_time_indices = torch.from_numpy(mask_time_indices).to(torch_device) + + with torch.no_grad(): + outputs = model( + inputs_dict.input_values.to(torch_device), + mask_time_indices=mask_time_indices, + ) + + # compute cosine similarity + cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1) + + # retrieve cosine sim of masked features + cosine_sim_masked = cosine_sim[mask_time_indices] + + # cosine similarity of model is all > 0.5 as model is + # pre-trained on contrastive loss + # fmt: off + expected_cosine_sim_masked = torch.tensor([ + 0.8523, 0.5860, 0.6905, 0.5557, 0.7456, 0.5249, 0.6639, 0.7654, 0.7565, + 0.8167, 0.8222, 0.7960, 0.8034, 0.8166, 0.8310, 0.8263, 0.8274, 0.8258, + 0.8179, 0.8412, 0.8536, 0.5098, 0.4728, 0.6461, 0.4498, 0.6002, 0.5774, + 0.6457, 0.7123, 0.5668, 0.6866, 0.4960, 0.6293, 0.7423, 0.7419, 0.7526, + 0.7768, 0.4898, 0.5393, 0.8183 + ], device=torch_device) + # fmt: on + + self.assertTrue(torch.allclose(cosine_sim_masked, expected_cosine_sim_masked, atol=1e-3)) + + def test_inference_pretrained(self): + model = Wav2Vec2ForPreTraining.from_pretrained("facebook/wav2vec2-base") + model.to(torch_device) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( + "facebook/wav2vec2-base", return_attention_mask=True + ) + input_speech = self._load_datasamples(2) + + inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) + + batch_size = inputs_dict["input_values"].shape[0] + feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1])) + + features_shape = (batch_size, feature_seq_length) + + torch.manual_seed(0) + mask_time_indices = _compute_mask_indices( + features_shape, + model.config.mask_time_prob, + model.config.mask_time_length, + min_masks=2, + ) + mask_time_indices = torch.from_numpy(mask_time_indices).to(torch_device) + + with torch.no_grad(): + outputs = model( + inputs_dict.input_values.to(torch_device), + attention_mask=inputs_dict.attention_mask.to(torch_device), + mask_time_indices=mask_time_indices, + ) + + # compute cosine similarity + cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1) + + # retrieve cosine sim of masked features + cosine_sim_masked = cosine_sim[mask_time_indices] + + # ... now compare to randomly initialized model + + config = Wav2Vec2Config.from_pretrained("facebook/wav2vec2-base") + model_rand = Wav2Vec2ForPreTraining(config).to(torch_device).eval() + + with torch.no_grad(): + outputs_rand = model_rand( + inputs_dict.input_values.to(torch_device), + attention_mask=inputs_dict.attention_mask.to(torch_device), + mask_time_indices=mask_time_indices, + ) + + # compute cosine similarity + cosine_sim_rand = torch.cosine_similarity( + outputs_rand.projected_states, outputs_rand.projected_quantized_states, dim=-1 + ) + + # retrieve cosine sim of masked features + cosine_sim_masked_rand = cosine_sim_rand[mask_time_indices] + + # a pretrained wav2vec2 model has learned to predict the quantized latent states + # => the cosine similarity between quantized states and predicted states > 0.5 + # a random wav2vec2 model has not learned to predict the quantized latent states + # => the cosine similarity between quantized states and predicted states is very likely < 0.1 + self.assertTrue(cosine_sim_masked.mean().item() - 5 * cosine_sim_masked_rand.mean().item() > 0) + + @unittest.skipIf(torch_device != "cpu", "cannot make deterministic on GPU") + def test_loss_pretraining(self): + model = Wav2Vec2ForPreTraining.from_pretrained( + "facebook/wav2vec2-base", + attention_dropout=0.0, + feat_proj_dropout=0.0, + hidden_dropout=0.0, + layerdrop=0.0, + ) + model.to(torch_device).train() + + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( + "facebook/wav2vec2-base", return_attention_mask=True + ) + input_speech = self._load_datasamples(2) + + inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) + + batch_size = inputs_dict["input_values"].shape[0] + feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1])) + + features_shape = (batch_size, feature_seq_length) + + torch.manual_seed(0) + np.random.seed(0) + + mask_time_indices = _compute_mask_indices( + features_shape, + model.config.mask_time_prob, + model.config.mask_time_length, + min_masks=2, + ) + sampled_negative_indices = _sample_negative_indices( + mask_time_indices.shape, model.config.num_negatives, mask_time_indices + ) + + mask_time_indices = torch.from_numpy(mask_time_indices).to(torch_device) + sampled_negative_indices = torch.from_numpy(sampled_negative_indices).to(torch_device) + + with torch.no_grad(): + outputs = model( + inputs_dict.input_values.to(torch_device), + attention_mask=inputs_dict.attention_mask.to(torch_device), + mask_time_indices=mask_time_indices, + sampled_negative_indices=sampled_negative_indices, + ) + + # check diversity loss + num_codevectors = model.config.num_codevectors_per_group * model.config.num_codevector_groups + diversity_loss = (num_codevectors - outputs.codevector_perplexity) / num_codevectors + self.assertTrue(abs(diversity_loss.item() - 0.9538) < 1e-3) + + # check overall loss (contrastive loss + diversity loss) + expected_loss = 116.7094 + + self.assertTrue(abs(outputs.loss.item() - expected_loss) < 1e-3) + + def test_inference_keyword_spotting(self): + model = Wav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-ks").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-ks") + input_data = self._load_superb("ks", 4) + inputs = processor(input_data["speech"], return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + with torch.no_grad(): + outputs = model(input_values, attention_mask=attention_mask) + predicted_logits, predicted_ids = torch.max(outputs.logits, dim=-1) + + expected_labels = [7, 6, 10, 9] + # s3prl logits for the same batch + expected_logits = torch.tensor([6.1186, 11.8961, 10.2931, 6.0898], device=torch_device) + + self.assertListEqual(predicted_ids.tolist(), expected_labels) + self.assertTrue(torch.allclose(predicted_logits, expected_logits, atol=1e-2)) + + def test_inference_intent_classification(self): + model = Wav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-ic").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-ic") + input_data = self._load_superb("ic", 4) + inputs = processor(input_data["speech"], return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + with torch.no_grad(): + outputs = model(input_values, attention_mask=attention_mask) + + predicted_logits_action, predicted_ids_action = torch.max(outputs.logits[:, :6], dim=-1) + predicted_logits_object, predicted_ids_object = torch.max(outputs.logits[:, 6:20], dim=-1) + predicted_logits_location, predicted_ids_location = torch.max(outputs.logits[:, 20:24], dim=-1) + + expected_labels_action = [0, 0, 2, 3] + expected_logits_action = torch.tensor([0.4568, 11.0848, 1.6621, 9.3841], device=torch_device) + expected_labels_object = [3, 10, 3, 4] + expected_logits_object = torch.tensor([1.5322, 10.7094, 5.2469, 22.1318], device=torch_device) + expected_labels_location = [0, 0, 0, 1] + expected_logits_location = torch.tensor([1.5335, 6.5096, 10.5704, 11.0569], device=torch_device) + + self.assertListEqual(predicted_ids_action.tolist(), expected_labels_action) + self.assertListEqual(predicted_ids_object.tolist(), expected_labels_object) + self.assertListEqual(predicted_ids_location.tolist(), expected_labels_location) + + self.assertTrue(torch.allclose(predicted_logits_action, expected_logits_action, atol=1e-2)) + self.assertTrue(torch.allclose(predicted_logits_object, expected_logits_object, atol=1e-2)) + self.assertTrue(torch.allclose(predicted_logits_location, expected_logits_location, atol=1e-2)) + + def test_inference_speaker_identification(self): + model = Wav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-sid").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-sid") + input_data = self._load_superb("si", 4) + + output_logits = [] + with torch.no_grad(): + for example in input_data["speech"]: + input = processor(example, return_tensors="pt", padding=True) + output = model(input.input_values.to(torch_device), attention_mask=None) + output_logits.append(output.logits[0]) + output_logits = torch.stack(output_logits) + predicted_logits, predicted_ids = torch.max(output_logits, dim=-1) + + expected_labels = [251, 1, 1, 3] + # s3prl logits for the same batch + expected_logits = torch.tensor([37.5627, 71.6362, 64.2419, 31.7778], device=torch_device) + + self.assertListEqual(predicted_ids.tolist(), expected_labels) + self.assertTrue(torch.allclose(predicted_logits, expected_logits, atol=1e-2)) + + def test_inference_emotion_recognition(self): + model = Wav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-er").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-er") + input_data = self._load_superb("er", 4) + inputs = processor(input_data["speech"], return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + with torch.no_grad(): + outputs = model(input_values, attention_mask=attention_mask) + predicted_logits, predicted_ids = torch.max(outputs.logits, dim=-1) + + expected_labels = [1, 1, 2, 2] + # s3prl logits for the same batch + expected_logits = torch.tensor([2.1722, 3.0779, 8.0287, 6.6797], device=torch_device) + + self.assertListEqual(predicted_ids.tolist(), expected_labels) + self.assertTrue(torch.allclose(predicted_logits, expected_logits, atol=1e-2)) + + def test_phoneme_recognition(self): + model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft").to(torch_device) + processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") + + input_speech = self._load_datasamples(4) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + + with torch.no_grad(): + logits = model(input_values, attention_mask=attention_mask).logits + + predicted_ids = torch.argmax(logits, dim=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "ɐ m æ n s ɛ d t ə ð ə j uː n ɪ v ɚ s s ɚ aɪ ɛ ɡ z ɪ s t", + "s w ɛ t k ʌ v ɚ d b ɹ iː ɔ n z b ɑː d i t ɹ ɪ k l ɪ ŋ ɪ n t ə ð ə t aɪ t l oɪ n k l ɑː θ ð æ w ʌ z ð ɪ oʊ" + " n l i ɡ ɑːɹ m ə n t h iː w ɔːɹ", + "ð ə k aɪ t ɔ n h ɪ z tʃ ɛ s t s t ɪ l d ɹ ɪ p ɪ ŋ b l ʌ d ð ɪ eɪ k ʌ v h ɪ z oʊ v ɚ s t ɹ eɪ n d aɪ z iː" + " v ə n ð ə s ɔːɹ ɹ ɪ ŋ ɐ ɹ iː n ɐ ɚ ɹ aʊ n d h ɪ m w ɪ ð ə θ aʊ z ə n d z ʌ v s p ɛ k t eɪ ɾ ɚ z w ɜː t ɹ" + " ɪ v ɪ æ l ᵻ ɾ i z n ɑː t w ɜː θ θ ɪ ŋ k ɪ ŋ ɐ b aʊ t", + "h ɪ z ɪ n s t ə n t v p æ n ɪ k w ʌ z f ɑː l oʊ d b aɪ ɐ s m ɔː l ʃ ɑːɹ p b l oʊ h aɪ ɔ n h ɪ z tʃ ɛ s t", + ] + # should correspond to =>: + # [ + # "a man said to the universe sir i exist", + # "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore", + # "the cut on his chest still dripping blood the ache of his overstrained eyes even the soaring arena around him with the thousands of spectators were trivialities not worth thinking about", + # "his instant panic was followed by a small sharp blow high on his chest", + # ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + @require_pyctcdecode + @require_torchaudio + def test_wav2vec2_with_lm(self): + ds = load_dataset("mozilla-foundation/common_voice_11_0", "es", split="test", streaming=True) + sample = next(iter(ds)) + + resampled_audio = torchaudio.functional.resample( + torch.tensor(sample["audio"]["array"]), 48_000, 16_000 + ).numpy() + + model = Wav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm").to( + torch_device + ) + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(resampled_audio, return_tensors="pt").input_values + + with torch.no_grad(): + logits = model(input_values.to(torch_device)).logits + + transcription = processor.batch_decode(logits.cpu().numpy()).text + + self.assertEqual(transcription[0], "habitan aguas poco profundas y rocosas") + + @require_pyctcdecode + @require_torchaudio + def test_wav2vec2_with_lm_pool(self): + ds = load_dataset("mozilla-foundation/common_voice_11_0", "es", split="test", streaming=True) + sample = next(iter(ds)) + + resampled_audio = torchaudio.functional.resample( + torch.tensor(sample["audio"]["array"]), 48_000, 16_000 + ).numpy() + + model = Wav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm").to( + torch_device + ) + processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm") + + input_values = processor(resampled_audio, return_tensors="pt").input_values + + with torch.no_grad(): + logits = model(input_values.to(torch_device)).logits + + # test user-managed pool + with multiprocessing.get_context("fork").Pool(2) as pool: + transcription = processor.batch_decode(logits.cpu().numpy(), pool).text + + self.assertEqual(transcription[0], "habitan aguas poco profundas y rocosas") + + # user-managed pool + num_processes should trigger a warning + with CaptureLogger(processing_wav2vec2_with_lm.logger) as cl, multiprocessing.get_context("fork").Pool( + 2 + ) as pool: + transcription = processor.batch_decode(logits.cpu().numpy(), pool, num_processes=2).text + + self.assertIn("num_process", cl.out) + self.assertIn("it will be ignored", cl.out) + + self.assertEqual(transcription[0], "habitan aguas poco profundas y rocosas") + + @require_pyctcdecode + @require_torchaudio + def test_wav2vec2_with_lm_invalid_pool(self): + run_test_in_subprocess(test_case=self, target_func=_test_wav2vec2_with_lm_invalid_pool, inputs=None) + + def test_inference_diarization(self): + model = Wav2Vec2ForAudioFrameClassification.from_pretrained("anton-l/wav2vec2-base-superb-sd").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("anton-l/wav2vec2-base-superb-sd") + input_data = self._load_superb("sd", 4) + inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + with torch.no_grad(): + outputs = model(input_values, attention_mask=attention_mask) + # labels is a one-hot array of shape (num_frames, num_speakers) + labels = (outputs.logits > 0).long() + + # s3prl logits for the same batch + expected_logits = torch.tensor( + [ + [[-5.2807, -5.1272], [-5.4059, -4.7757], [-5.2764, -4.9621], [-5.0117, -4.5851]], + [[-1.7643, -0.5462], [-1.7369, -0.2649], [-1.5066, -0.6200], [-4.5703, -2.4863]], + [[-0.8656, -0.4783], [-0.8899, -0.3289], [-0.9267, -0.5781], [-0.7817, -0.4619]], + [[-4.8625, -2.5316], [-5.2339, -2.2155], [-4.9835, -2.0344], [-4.4727, -1.8421]], + ], + device=torch_device, + ) + self.assertEqual(labels[0, :, 0].sum(), 555) + self.assertEqual(labels[0, :, 1].sum(), 299) + # TODO: update the tolerance after the CI moves to torch 1.10 + self.assertTrue(torch.allclose(outputs.logits[:, :4], expected_logits, atol=1e-2)) + + def test_inference_speaker_verification(self): + model = Wav2Vec2ForXVector.from_pretrained("anton-l/wav2vec2-base-superb-sv").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("anton-l/wav2vec2-base-superb-sv") + input_data = self._load_superb("si", 4) + + inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000) + labels = torch.tensor([5, 1, 1, 3], device=torch_device).T + + with torch.no_grad(): + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + outputs = model(input_values, attention_mask=attention_mask, labels=labels) + embeddings = torch.nn.functional.normalize(outputs.embeddings, dim=-1).cpu() + + cosine_sim = torch.nn.CosineSimilarity(dim=-1) + # id10002 vs id10002 + self.assertAlmostEqual(cosine_sim(embeddings[1], embeddings[2]).numpy(), 0.9758, 3) + # id10006 vs id10002 + self.assertAlmostEqual(cosine_sim(embeddings[0], embeddings[1]).numpy(), 0.7579, 3) + # id10002 vs id10004 + self.assertAlmostEqual(cosine_sim(embeddings[2], embeddings[3]).numpy(), 0.7594, 3) + + # TODO: update the tolerance after the CI moves to torch 1.10 + self.assertAlmostEqual(outputs.loss.item(), 17.7963, 2) + + @require_torchaudio + def test_inference_mms_1b_all(self): + model = Wav2Vec2ForCTC.from_pretrained("facebook/mms-1b-all").to(torch_device) + processor = Wav2Vec2Processor.from_pretrained("facebook/mms-1b-all") + + LANG_MAP = {"it": "ita", "es": "spa", "fr": "fra", "en": "eng"} + + def run_model(lang): + ds = load_dataset("mozilla-foundation/common_voice_11_0", lang, split="test", streaming=True) + sample = next(iter(ds)) + + wav2vec2_lang = LANG_MAP[lang] + + model.load_adapter(wav2vec2_lang) + processor.tokenizer.set_target_lang(wav2vec2_lang) + + resampled_audio = torchaudio.functional.resample( + torch.tensor(sample["audio"]["array"]), 48_000, 16_000 + ).numpy() + + inputs = processor(resampled_audio, sampling_rate=16_000, return_tensors="pt") + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + + with torch.no_grad(): + outputs = model(input_values, attention_mask=attention_mask).logits + + ids = torch.argmax(outputs, dim=-1)[0] + + transcription = processor.decode(ids) + return transcription + + TRANSCRIPTIONS = { + "it": "il libro ha suscitato molte polemiche a causa dei suoi contenuti", + "es": "habitan aguas poco profundas y rocosas", + "fr": "ce dernier est volé tout au long de l'histoire romaine", + "en": "joe keton disapproved of films and buster also had reservations about the media", + } + + for lang in LANG_MAP.keys(): + assert run_model(lang) == TRANSCRIPTIONS[lang] diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_processor_wav2vec2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_processor_wav2vec2.py new file mode 100644 index 0000000000000000000000000000000000000000..67883618ca86e9c00358f7873cf8d7d640be8d4a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_processor_wav2vec2.py @@ -0,0 +1,151 @@ +# Copyright 2021 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 shutil +import tempfile +import unittest + +from transformers.models.wav2vec2 import Wav2Vec2CTCTokenizer, Wav2Vec2FeatureExtractor, Wav2Vec2Processor +from transformers.models.wav2vec2.tokenization_wav2vec2 import VOCAB_FILES_NAMES +from transformers.utils import FEATURE_EXTRACTOR_NAME + +from .test_feature_extraction_wav2vec2 import floats_list + + +class Wav2Vec2ProcessorTest(unittest.TestCase): + def setUp(self): + vocab = " | E T A O N I H S R D L U M W C F G Y P B V K ' X J Q Z".split(" ") + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + + self.add_kwargs_tokens_map = { + "pad_token": "", + "unk_token": "", + "bos_token": "", + "eos_token": "", + } + feature_extractor_map = { + "feature_size": 1, + "padding_value": 0.0, + "sampling_rate": 16000, + "return_attention_mask": False, + "do_normalize": True, + } + + self.tmpdirname = tempfile.mkdtemp() + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + self.feature_extraction_file = os.path.join(self.tmpdirname, FEATURE_EXTRACTOR_NAME) + with open(self.vocab_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(vocab_tokens) + "\n") + + with open(self.feature_extraction_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(feature_extractor_map) + "\n") + + def get_tokenizer(self, **kwargs_init): + kwargs = self.add_kwargs_tokens_map.copy() + kwargs.update(kwargs_init) + return Wav2Vec2CTCTokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def get_feature_extractor(self, **kwargs): + return Wav2Vec2FeatureExtractor.from_pretrained(self.tmpdirname, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_save_load_pretrained_default(self): + tokenizer = self.get_tokenizer() + feature_extractor = self.get_feature_extractor() + + processor = Wav2Vec2Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + processor.save_pretrained(self.tmpdirname) + processor = Wav2Vec2Processor.from_pretrained(self.tmpdirname) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) + self.assertIsInstance(processor.tokenizer, Wav2Vec2CTCTokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string()) + self.assertIsInstance(processor.feature_extractor, Wav2Vec2FeatureExtractor) + + def test_save_load_pretrained_additional_features(self): + processor = Wav2Vec2Processor(tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor()) + processor.save_pretrained(self.tmpdirname) + + tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)") + feature_extractor_add_kwargs = self.get_feature_extractor(do_normalize=False, padding_value=1.0) + + processor = Wav2Vec2Processor.from_pretrained( + self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0 + ) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) + self.assertIsInstance(processor.tokenizer, Wav2Vec2CTCTokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.feature_extractor, Wav2Vec2FeatureExtractor) + + def test_feature_extractor(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Wav2Vec2Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + raw_speech = floats_list((3, 1000)) + + input_feat_extract = feature_extractor(raw_speech, return_tensors="np") + input_processor = processor(raw_speech, return_tensors="np") + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_tokenizer(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Wav2Vec2Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + input_str = "This is a test string" + + encoded_processor = processor(text=input_str) + + encoded_tok = tokenizer(input_str) + + for key in encoded_tok.keys(): + self.assertListEqual(encoded_tok[key], encoded_processor[key]) + + def test_tokenizer_decode(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Wav2Vec2Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] + + decoded_processor = processor.batch_decode(predicted_ids) + decoded_tok = tokenizer.batch_decode(predicted_ids) + + self.assertListEqual(decoded_tok, decoded_processor) + + def test_model_input_names(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = Wav2Vec2Processor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + self.assertListEqual( + processor.model_input_names, + feature_extractor.model_input_names, + msg="`processor` and `feature_extractor` model input names do not match", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_tokenization_wav2vec2.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_tokenization_wav2vec2.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab8717d8199214540196cf8aa3370c294f8d7c2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2/test_tokenization_wav2vec2.py @@ -0,0 +1,826 @@ +# coding=utf-8 +# Copyright 2021 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. +"""Tests for the Wav2Vec2 tokenizer.""" +import inspect +import json +import os +import random +import shutil +import tempfile +import unittest + +import numpy as np + +from transformers import ( + WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, + AddedToken, + Wav2Vec2Config, + Wav2Vec2CTCTokenizer, + Wav2Vec2Tokenizer, +) +from transformers.models.wav2vec2.tokenization_wav2vec2 import VOCAB_FILES_NAMES, Wav2Vec2CTCTokenizerOutput +from transformers.testing_utils import require_torch, slow + +from ...test_tokenization_common import TokenizerTesterMixin + + +global_rng = random.Random() + + +# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +class Wav2Vec2TokenizerTest(unittest.TestCase): + tokenizer_class = Wav2Vec2Tokenizer + + def setUp(self): + super().setUp() + + vocab = " | E T A O N I H S R D L U M W C F G Y P B V K ' X J Q Z".split(" ") + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + + self.special_tokens_map = {"pad_token": "", "unk_token": "", "bos_token": "", "eos_token": ""} + + self.tmpdirname = tempfile.mkdtemp() + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(vocab_tokens) + "\n") + + def get_tokenizer(self, **kwargs): + kwargs.update(self.special_tokens_map) + return Wav2Vec2Tokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def test_tokenizer_decode(self): + # TODO(PVP) - change to facebook + tokenizer = Wav2Vec2Tokenizer.from_pretrained("facebook/wav2vec2-base-960h") + + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98], + [24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77], + ] + tokens = tokenizer.decode(sample_ids[0]) + batch_tokens = tokenizer.batch_decode(sample_ids) + self.assertEqual(tokens, batch_tokens[0]) + self.assertEqual(batch_tokens, ["HELLO", "BYE BYE"]) + + def test_tokenizer_decode_special(self): + # TODO(PVP) - change to facebook + tokenizer = Wav2Vec2Tokenizer.from_pretrained("facebook/wav2vec2-base-960h") + + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98], + [24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77], + ] + sample_ids_2 = [ + [11, 5, 5, 5, 5, 5, 15, 15, 15, tokenizer.pad_token_id, 15, 8, 98], + [ + 24, + 22, + 5, + tokenizer.pad_token_id, + tokenizer.pad_token_id, + tokenizer.pad_token_id, + tokenizer.word_delimiter_token_id, + 24, + 22, + 5, + 77, + tokenizer.word_delimiter_token_id, + ], + ] + + batch_tokens = tokenizer.batch_decode(sample_ids) + batch_tokens_2 = tokenizer.batch_decode(sample_ids_2) + self.assertEqual(batch_tokens, batch_tokens_2) + self.assertEqual(batch_tokens, ["HELLO", "BYE BYE"]) + + def test_tokenizer_decode_added_tokens(self): + tokenizer = Wav2Vec2Tokenizer.from_pretrained("facebook/wav2vec2-base-960h") + tokenizer.add_tokens(["!", "?"]) + tokenizer.add_special_tokens({"cls_token": "$$$"}) + + sample_ids = [ + [ + 11, + 5, + 15, + tokenizer.pad_token_id, + 15, + 8, + 98, + 32, + 32, + 33, + tokenizer.word_delimiter_token_id, + 32, + 32, + 33, + 34, + 34, + ], + [24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77, tokenizer.pad_token_id, 34, 34], + ] + batch_tokens = tokenizer.batch_decode(sample_ids) + + self.assertEqual(batch_tokens, ["HELLO!?!?$$$", "BYE BYE$$$"]) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + tokenizer = self.get_tokenizer() + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test not batched input + encoded_sequences_1 = tokenizer(speech_inputs[0], return_tensors="np").input_values + encoded_sequences_2 = tokenizer(np_speech_inputs[0], return_tensors="np").input_values + self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) + + # Test batched + encoded_sequences_1 = tokenizer(speech_inputs, return_tensors="np").input_values + encoded_sequences_2 = tokenizer(np_speech_inputs, return_tensors="np").input_values + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test 2-D numpy arrays are batched. + speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] + np_speech_inputs = np.asarray(speech_inputs) + encoded_sequences_1 = tokenizer(speech_inputs, return_tensors="np").input_values + encoded_sequences_2 = tokenizer(np_speech_inputs, return_tensors="np").input_values + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + def test_padding(self, max_length=50): + def _input_values_have_equal_length(input_values): + length = len(input_values[0]) + for input_values_slice in input_values[1:]: + if len(input_values_slice) != length: + return False + return True + + def _input_values_are_equal(input_values_1, input_values_2): + if len(input_values_1) != len(input_values_2): + return False + + for input_values_slice_1, input_values_slice_2 in zip(input_values_1, input_values_2): + if not np.allclose(np.asarray(input_values_slice_1), np.asarray(input_values_slice_2), atol=1e-3): + return False + return True + + tokenizer = self.get_tokenizer() + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + input_values_1 = tokenizer(speech_inputs).input_values + input_values_2 = tokenizer(speech_inputs, padding="longest").input_values + input_values_3 = tokenizer(speech_inputs, padding="longest", max_length=1600).input_values + + self.assertFalse(_input_values_have_equal_length(input_values_1)) + self.assertTrue(_input_values_have_equal_length(input_values_2)) + self.assertTrue(_input_values_have_equal_length(input_values_3)) + self.assertTrue(_input_values_are_equal(input_values_2, input_values_3)) + self.assertTrue(len(input_values_1[0]) == 800) + self.assertTrue(len(input_values_2[0]) == 1200) + # padding should be 0.0 + self.assertTrue(abs(sum(np.asarray(input_values_2[0])[800:])) < 1e-3) + self.assertTrue(abs(sum(np.asarray(input_values_2[1])[1000:])) < 1e-3) + + input_values_4 = tokenizer(speech_inputs, padding="max_length").input_values + input_values_5 = tokenizer(speech_inputs, padding="max_length", max_length=1600).input_values + + self.assertTrue(_input_values_are_equal(input_values_1, input_values_4)) + self.assertEqual(input_values_5.shape, (3, 1600)) + # padding should be 0.0 + self.assertTrue(abs(sum(np.asarray(input_values_5[0])[800:1200])) < 1e-3) + + input_values_6 = tokenizer(speech_inputs, pad_to_multiple_of=500).input_values + input_values_7 = tokenizer(speech_inputs, padding="longest", pad_to_multiple_of=500).input_values + input_values_8 = tokenizer( + speech_inputs, padding="max_length", pad_to_multiple_of=500, max_length=2400 + ).input_values + + self.assertTrue(_input_values_are_equal(input_values_1, input_values_6)) + self.assertEqual(input_values_7.shape, (3, 1500)) + self.assertEqual(input_values_8.shape, (3, 2500)) + # padding should be 0.0 + self.assertTrue(abs(sum(np.asarray(input_values_7[0])[800:])) < 1e-3) + self.assertTrue(abs(sum(np.asarray(input_values_7[1])[1000:])) < 1e-3) + self.assertTrue(abs(sum(np.asarray(input_values_7[2])[1200:])) < 1e-3) + self.assertTrue(abs(sum(np.asarray(input_values_8[0])[800:])) < 1e-3) + self.assertTrue(abs(sum(np.asarray(input_values_8[1])[1000:])) < 1e-3) + self.assertTrue(abs(sum(np.asarray(input_values_8[2])[1200:])) < 1e-3) + + def test_save_pretrained(self): + pretrained_name = list(self.tokenizer_class.pretrained_vocab_files_map["vocab_file"].keys())[0] + tokenizer = self.tokenizer_class.from_pretrained(pretrained_name) + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_files = tokenizer.save_pretrained(tmpdirname2) + self.assertSequenceEqual( + sorted(tuple(VOCAB_FILES_NAMES.values()) + ("special_tokens_map.json", "added_tokens.json")), + sorted(x.split(os.path.sep)[-1] for x in tokenizer_files), + ) + + # Checks everything loads correctly in the same way + tokenizer_p = self.tokenizer_class.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer.special_tokens_map: + self.assertTrue(key in tokenizer_p.special_tokens_map) + + shutil.rmtree(tmpdirname2) + + def test_get_vocab(self): + tokenizer = self.get_tokenizer() + vocab_dict = tokenizer.get_vocab() + self.assertIsInstance(vocab_dict, dict) + self.assertGreaterEqual(len(tokenizer), len(vocab_dict)) + + vocab = [tokenizer.convert_ids_to_tokens(i) for i in range(len(tokenizer))] + self.assertEqual(len(vocab), len(tokenizer)) + + tokenizer.add_tokens(["asdfasdfasdfasdf"]) + vocab = [tokenizer.convert_ids_to_tokens(i) for i in range(len(tokenizer))] + self.assertEqual(len(vocab), len(tokenizer)) + + def test_save_and_load_tokenizer(self): + tokenizer = self.get_tokenizer() + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + sample_ids = [0, 1, 4, 8, 9, 0, 12] + before_tokens = tokenizer.decode(sample_ids) + before_vocab = tokenizer.get_vocab() + tokenizer.save_pretrained(tmpdirname) + + after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname) + after_tokens = after_tokenizer.decode(sample_ids) + after_vocab = after_tokenizer.get_vocab() + + self.assertEqual(before_tokens, after_tokens) + self.assertDictEqual(before_vocab, after_vocab) + + shutil.rmtree(tmpdirname) + + tokenizer = self.get_tokenizer() + + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + before_len = len(tokenizer) + sample_ids = [0, 1, 4, 8, 9, 0, 12, before_len, before_len + 1, before_len + 2] + tokenizer.add_tokens(["?", "!"]) + additional_special_tokens = tokenizer.additional_special_tokens + additional_special_tokens.append("&") + tokenizer.add_special_tokens( + {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False + ) + before_tokens = tokenizer.decode(sample_ids) + before_vocab = tokenizer.get_vocab() + tokenizer.save_pretrained(tmpdirname) + + after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname) + after_tokens = after_tokenizer.decode(sample_ids) + after_vocab = after_tokenizer.get_vocab() + + self.assertEqual(before_tokens, after_tokens) + self.assertDictEqual(before_vocab, after_vocab) + + self.assertTrue(len(tokenizer), before_len + 3) + self.assertTrue(len(tokenizer), len(after_tokenizer)) + shutil.rmtree(tmpdirname) + + def test_tokenizer_slow_store_full_signature(self): + signature = inspect.signature(self.tokenizer_class.__init__) + tokenizer = self.get_tokenizer() + + for parameter_name, parameter in signature.parameters.items(): + if parameter.default != inspect.Parameter.empty: + self.assertIn(parameter_name, tokenizer.init_kwargs) + + def test_zero_mean_unit_variance_normalization(self): + tokenizer = self.get_tokenizer(do_normalize=True) + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + processed = tokenizer(speech_inputs, padding="longest") + input_values = processed.input_values + + def _check_zero_mean_unit_variance(input_vector): + self.assertTrue(np.abs(np.mean(input_vector)) < 1e-3) + self.assertTrue(np.abs(np.var(input_vector) - 1) < 1e-3) + + _check_zero_mean_unit_variance(input_values[0, :800]) + _check_zero_mean_unit_variance(input_values[1, :1000]) + _check_zero_mean_unit_variance(input_values[2]) + + def test_return_attention_mask(self): + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + + # default case -> no attention_mask is returned + tokenizer = self.get_tokenizer() + processed = tokenizer(speech_inputs) + self.assertNotIn("attention_mask", processed) + + # wav2vec2-lv60 -> return attention_mask + tokenizer = self.get_tokenizer(return_attention_mask=True) + processed = tokenizer(speech_inputs, padding="longest") + + self.assertIn("attention_mask", processed) + self.assertListEqual(list(processed.attention_mask.shape), list(processed.input_values.shape)) + self.assertListEqual(processed.attention_mask.sum(-1).tolist(), [800, 1000, 1200]) + + @slow + @require_torch + def test_pretrained_checkpoints_are_set_correctly(self): + # this test makes sure that models that are using + # group norm don't have their tokenizer return the + # attention_mask + for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST: + config = Wav2Vec2Config.from_pretrained(model_id) + tokenizer = Wav2Vec2Tokenizer.from_pretrained(model_id) + + # only "layer" feature extraction norm should make use of + # attention_mask + self.assertEqual(tokenizer.return_attention_mask, config.feat_extract_norm == "layer") + + +class Wav2Vec2CTCTokenizerTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = Wav2Vec2CTCTokenizer + test_rust_tokenizer = False + + def setUp(self): + super().setUp() + + vocab = " | E T A O N I H S R D L U M W C F G Y P B V K ' X J Q Z".split(" ") + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + + self.special_tokens_map = {"pad_token": "", "unk_token": "", "bos_token": "", "eos_token": ""} + + self.tmpdirname = tempfile.mkdtemp() + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(vocab_tokens) + "\n") + + def get_tokenizer(self, **kwargs): + kwargs.update(self.special_tokens_map) + return Wav2Vec2CTCTokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def test_tokenizer_add_token_chars(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h") + + # check adding a single token + tokenizer.add_tokens("x") + token_ids = tokenizer("C x A").input_ids + self.assertEqual(token_ids, [19, 4, 32, 4, 7]) + + tokenizer.add_tokens(["a", "b", "c"]) + token_ids = tokenizer("C a A c").input_ids + self.assertEqual(token_ids, [19, 4, 33, 4, 7, 4, 35]) + + tokenizer.add_tokens(["a", "b", "c"]) + token_ids = tokenizer("CaA c").input_ids + self.assertEqual(token_ids, [19, 33, 7, 4, 35]) + + def test_tokenizer_add_token_words(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h") + + # check adding a single token + tokenizer.add_tokens("xxx") + token_ids = tokenizer("C xxx A B").input_ids + self.assertEqual(token_ids, [19, 4, 32, 4, 7, 4, 24]) + + tokenizer.add_tokens(["aaa", "bbb", "ccc"]) + token_ids = tokenizer("C aaa A ccc B B").input_ids + self.assertEqual(token_ids, [19, 4, 33, 4, 7, 4, 35, 4, 24, 4, 24]) + + tokenizer.add_tokens(["aaa", "bbb", "ccc"]) + token_ids = tokenizer("CaaaA ccc B B").input_ids + self.assertEqual(token_ids, [19, 33, 7, 4, 35, 4, 24, 4, 24]) + + def test_tokenizer_decode(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h") + + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98], + [24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77], + ] + tokens = tokenizer.decode(sample_ids[0]) + batch_tokens = tokenizer.batch_decode(sample_ids) + self.assertEqual(tokens, batch_tokens[0]) + self.assertEqual(batch_tokens, ["HELLO", "BYE BYE"]) + + def test_tokenizer_decode_special(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h") + + # fmt: off + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98], + [24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77], + ] + sample_ids_2 = [ + [11, 5, 5, 5, 5, 5, 15, 15, 15, tokenizer.pad_token_id, 15, 8, 98], + [24, 22, 5, tokenizer.pad_token_id, tokenizer.pad_token_id, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 24, 22, 5, 77, tokenizer.word_delimiter_token_id], + ] + # fmt: on + + batch_tokens = tokenizer.batch_decode(sample_ids) + batch_tokens_2 = tokenizer.batch_decode(sample_ids_2) + self.assertEqual(batch_tokens, batch_tokens_2) + self.assertEqual(batch_tokens, ["HELLO", "BYE BYE"]) + + def test_tokenizer_decode_added_tokens(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h") + tokenizer.add_tokens(["!", "?"]) + tokenizer.add_special_tokens({"cls_token": "$$$"}) + + # fmt: off + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98, 32, 32, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34], + [24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77, tokenizer.pad_token_id, 34, 34], + ] + # fmt: on + batch_tokens = tokenizer.batch_decode(sample_ids) + + self.assertEqual(batch_tokens, ["HELLO!?!?$$$", "BYE BYE$$$"]) + + def test_special_characters_in_vocab(self): + sent = "ʈʰ æ æ̃ ˧ kʰ" + + vocab_dict = {k: v for v, k in enumerate(set(sent.split()))} + vocab_file = os.path.join(self.tmpdirname, "vocab_special.json") + + with open(vocab_file, "w") as f: + json.dump(vocab_dict, f) + + tokenizer = Wav2Vec2CTCTokenizer(vocab_file) # , unk_token="") + + expected_sent = tokenizer.decode(tokenizer(sent).input_ids, spaces_between_special_tokens=True) + self.assertEqual(sent, expected_sent) + + tokenizer.save_pretrained(os.path.join(self.tmpdirname, "special_tokenizer")) + tokenizer = Wav2Vec2CTCTokenizer.from_pretrained(os.path.join(self.tmpdirname, "special_tokenizer")) + + expected_sent = tokenizer.decode(tokenizer(sent).input_ids, spaces_between_special_tokens=True) + self.assertEqual(sent, expected_sent) + + @staticmethod + def get_from_offsets(offsets, key): + retrieved_list = [d[key] for d in offsets] + return retrieved_list + + def test_offsets(self): + tokenizer = self.get_tokenizer() + + # fmt: off + # HEEEEE||LLLLO => HE LLO + # 1H + 5E + 2| + 3L + 1 + 1L + 1O + 1 + sample_ids = [11, 5, 5, 5, 5, 5, 4, 4, 15, 15, 15, tokenizer.pad_token_id, 15, 8, 98] + # fmt: on + + outputs_char = tokenizer.decode(sample_ids, output_char_offsets=True) + # check Wav2Vec2CTCTokenizerOutput keys for char + self.assertEqual(len(outputs_char.keys()), 2) + self.assertTrue("text" in outputs_char) + self.assertTrue("char_offsets" in outputs_char) + self.assertTrue(isinstance(outputs_char, Wav2Vec2CTCTokenizerOutput)) + + outputs_word = tokenizer.decode(sample_ids, output_word_offsets=True) + # check Wav2Vec2CTCTokenizerOutput keys for word + self.assertEqual(len(outputs_word.keys()), 2) + self.assertTrue("text" in outputs_word) + self.assertTrue("word_offsets" in outputs_word) + self.assertTrue(isinstance(outputs_word, Wav2Vec2CTCTokenizerOutput)) + + outputs = tokenizer.decode(sample_ids, output_char_offsets=True, output_word_offsets=True) + # check Wav2Vec2CTCTokenizerOutput keys for both + self.assertEqual(len(outputs.keys()), 3) + self.assertTrue("text" in outputs) + self.assertTrue("char_offsets" in outputs) + self.assertTrue("word_offsets" in outputs) + self.assertTrue(isinstance(outputs, Wav2Vec2CTCTokenizerOutput)) + + # check that order of chars is correct and identical for both outputs + self.assertEqual("".join(self.get_from_offsets(outputs["char_offsets"], "char")), outputs.text) + self.assertEqual( + self.get_from_offsets(outputs["char_offsets"], "char"), ["H", "E", " ", "L", "L", "O", ""] + ) + self.assertListEqual( + self.get_from_offsets(outputs["char_offsets"], "char"), + self.get_from_offsets(outputs_char["char_offsets"], "char"), + ) + + # check that order of words is correct and identical to both outputs + self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"], "word")), outputs.text) + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "word"), ["HE", "LLO"]) + self.assertListEqual( + self.get_from_offsets(outputs["word_offsets"], "word"), + self.get_from_offsets(outputs_word["word_offsets"], "word"), + ) + + # check that offsets are actually correct for char + # 0 is H, 1 is E, 6 is | (" "), 8 is 1st L, 12 is 2nd L, 13 is O, 14 is + self.assertListEqual(self.get_from_offsets(outputs["char_offsets"], "start_offset"), [0, 1, 6, 8, 12, 13, 14]) + # 1 is H, 6 is E, 8 is | (" "), 11 is 1st L (note due to + # different begin of 2nd L), 13 is 2nd L, 14 is O, 15 is + self.assertListEqual(self.get_from_offsets(outputs["char_offsets"], "end_offset"), [1, 6, 8, 11, 13, 14, 15]) + + # check that offsets are actually correct for word + # H is at 1st position of first word, first L is at 8th position of second word + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "start_offset"), [0, 8]) + # last E is at 6th position of first word, first L is at last (15th) position of second word + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "end_offset"), [6, 15]) + + def test_word_offsets_from_char_offsets(self): + tokenizer = self.get_tokenizer() + + char_offsets = [ + {"char": "H", "start_offset": 0, "end_offset": 1}, + {"char": "I", "start_offset": 1, "end_offset": 2}, + {"char": " ", "start_offset": 2, "end_offset": 3}, + {"char": "L", "start_offset": 3, "end_offset": 4}, + {"char": "I", "start_offset": 4, "end_offset": 5}, + ] + word_offsets = tokenizer._get_word_offsets(char_offsets, tokenizer.replace_word_delimiter_char) + + self.assertEqual( + word_offsets, + [{"word": "HI", "start_offset": 0, "end_offset": 2}, {"word": "LI", "start_offset": 3, "end_offset": 5}], + ) + + # Double spaces don't get counted + char_offsets = [ + {"char": " ", "start_offset": 0, "end_offset": 1}, + {"char": "H", "start_offset": 1, "end_offset": 2}, + {"char": "I", "start_offset": 2, "end_offset": 3}, + {"char": " ", "start_offset": 3, "end_offset": 4}, + {"char": " ", "start_offset": 4, "end_offset": 5}, + {"char": "L", "start_offset": 5, "end_offset": 6}, + {"char": "I", "start_offset": 6, "end_offset": 7}, + {"char": "I", "start_offset": 7, "end_offset": 8}, + {"char": " ", "start_offset": 8, "end_offset": 9}, + {"char": " ", "start_offset": 9, "end_offset": 10}, + ] + word_offsets = tokenizer._get_word_offsets(char_offsets, tokenizer.replace_word_delimiter_char) + self.assertEqual( + word_offsets, + [{"word": "HI", "start_offset": 1, "end_offset": 3}, {"word": "LII", "start_offset": 5, "end_offset": 8}], + ) + + def test_offsets_batch(self): + tokenizer = self.get_tokenizer() + + def check_list_tuples_equal(outputs_batch, outputs_list): + self.assertTrue(isinstance(outputs_batch, Wav2Vec2CTCTokenizerOutput)) + self.assertTrue(isinstance(outputs_list[0], Wav2Vec2CTCTokenizerOutput)) + + # transform list to ModelOutput + outputs_batch_2 = Wav2Vec2CTCTokenizerOutput({k: [d[k] for d in outputs_list] for k in outputs_list[0]}) + + self.assertListEqual(outputs_batch["text"], outputs_batch_2["text"]) + + def recursive_check(list_or_dict_1, list_or_dict_2): + if isinstance(list_or_dict_1, list): + [recursive_check(l1, l2) for l1, l2 in zip(list_or_dict_1, list_or_dict_2)] + self.assertEqual(list_or_dict_1, list_or_dict_2) + + if "char_offsets" in outputs_batch: + recursive_check(outputs_batch["char_offsets"], outputs_batch_2["char_offsets"]) + + if "word_offsets" in outputs_batch: + recursive_check(outputs_batch["word_offsets"], outputs_batch_2["word_offsets"]) + + # fmt: off + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 4, 8, 98, 32, 32, 32, 32, 4, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34], + [24, 22, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 24, 22, 22, 22, 4, 5, 77, tokenizer.pad_token_id, 22, 22, 4, 34, 34, 34, 34], + ] + # fmt: on + + # We assume that `decode` works as expected. All we will check now is + # the output type is correct and the output is identical to `decode` + + # char + outputs_char_batch = tokenizer.batch_decode(sample_ids, output_char_offsets=True) + outputs_char = [tokenizer.decode(ids, output_char_offsets=True) for ids in sample_ids] + check_list_tuples_equal(outputs_char_batch, outputs_char) + + # word + outputs_word_batch = tokenizer.batch_decode(sample_ids, output_word_offsets=True) + outputs_word = [tokenizer.decode(ids, output_word_offsets=True) for ids in sample_ids] + check_list_tuples_equal(outputs_word_batch, outputs_word) + + # both + outputs_batch = tokenizer.batch_decode(sample_ids, output_char_offsets=True, output_word_offsets=True) + outputs = [tokenizer.decode(ids, output_word_offsets=True, output_char_offsets=True) for ids in sample_ids] + check_list_tuples_equal(outputs_batch, outputs) + + def test_offsets_integration(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h") + # pred_ids correspond to the following code + # ``` + # from transformers import AutoTokenizer, AutoFeatureExtractor, AutoModelForCTC + # from datasets import load_dataset + # import datasets + # import torch + # model = AutoModelForCTC.from_pretrained("facebook/wav2vec2-base-960h") + # feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h") + # + # ds = load_dataset("common_voice", "en", split="train", streaming=True) + # ds = ds.cast_column("audio", datasets.Audio(sampling_rate=16_000)) + # ds_iter = iter(ds) + # sample = next(ds_iter) + # + # input_values = feature_extractor(sample["audio"]["array"], return_tensors="pt").input_values + # logits = model(input_values).logits + # pred_ids = torch.argmax(logits, axis=-1).cpu().tolist() + # ``` + # fmt: off + pred_ids = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 11, 0, 0, 0, 22, 0, 0, 4, 4, 4, 14, 0, 0, 0, 0, 0, 8, 8, 0, 5, 5, 0, 12, 0, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 10, 0, 0, 0, 15, 0, 0, 10, 0, 0, 0, 12, 0, 0, 0, 0, 0, 7, 0, 9, 0, 0, 14, 0, 0, 0, 13, 0, 7, 0, 0, 4, 4, 0, 15, 8, 8, 0, 0, 8, 0, 26, 0, 0, 4, 4, 0, 0, 15, 0, 0, 0, 0, 0, 0, 10, 0, 26, 5, 5, 0, 4, 4, 0, 0, 12, 11, 0, 0, 5, 4, 4, 4, 0, 18, 0, 0, 0, 7, 9, 9, 0, 6, 0, 12, 12, 4, 4, 0, 6, 0, 0, 8, 0, 4, 4, 4, 0, 19, 0, 0, 8, 9, 9, 0, 0, 0, 0, 12, 12, 0, 0, 0, 0, 0, 0, 0, 16, 16, 0, 0, 17, 5, 5, 5, 0, 4, 4, 4, 0, 0, 29, 29, 0, 0, 0, 0, 8, 11, 0, 9, 9, 0, 0, 0, 4, 4, 0, 12, 12, 0, 0, 0, 9, 0, 0, 0, 0, 0, 8, 18, 0, 0, 0, 4, 4, 0, 0, 8, 9, 0, 4, 4, 0, 6, 11, 5, 0, 4, 4, 0, 13, 13, 0, 0, 0, 10, 0, 0, 25, 0, 0, 6, 0, 4, 4, 0, 0, 0, 0, 7, 0, 0, 23, 0, 0, 4, 4, 0, 0, 0, 6, 11, 0, 5, 4, 4, 18, 0, 0, 0, 0, 0, 0, 7, 15, 0, 0, 0, 15, 15, 0, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] + + # wav2vec2-base downsamples input audio by a factor of 320 + # sampling rate for wav2vec2-base is 16_000 + time_offset_wav2vec2_base = 320 / 16_000 + + expected_char_time_stamps_text = ['W', 'H', 'Y', ' ', 'D', 'O', 'E', 'S', ' ', 'M', 'I', 'L', 'I', 'S', 'A', 'N', 'D', 'R', 'A', ' ', 'L', 'O', 'O', 'K', ' ', 'L', 'I', 'K', 'E', ' ', 'S', 'H', 'E', ' ', 'W', 'A', 'N', 'T', 'S', ' ', 'T', 'O', ' ', 'C', 'O', 'N', 'S', 'U', 'M', 'E', ' ', 'J', 'O', 'H', 'N', ' ', 'S', 'N', 'O', 'W', ' ', 'O', 'N', ' ', 'T', 'H', 'E', ' ', 'R', 'I', 'V', 'T', ' ', 'A', 'P', ' ', 'T', 'H', 'E', ' ', 'W', 'A', 'L', 'L', ' '] + expected_char_time_stamps_start = [1.42, 1.44, 1.52, 1.58, 1.64, 1.76, 1.82, 1.88, 1.92, 2.26, 2.32, 2.4, 2.46, 2.54, 2.66, 2.7, 2.76, 2.84, 2.88, 2.94, 3.0, 3.02, 3.1, 3.14, 3.2, 3.28, 3.42, 3.46, 3.48, 3.54, 3.62, 3.64, 3.7, 3.72, 3.8, 3.88, 3.9, 3.96, 4.0, 4.04, 4.1, 4.16, 4.2, 4.28, 4.34, 4.36, 4.48, 4.66, 4.74, 4.76, 4.84, 4.94, 5.06, 5.08, 5.12, 5.22, 5.28, 5.38, 5.5, 5.52, 5.6, 5.68, 5.7, 5.74, 5.8, 5.82, 5.84, 5.88, 5.94, 6.04, 6.1, 6.16, 6.2, 6.32, 6.38, 6.44, 6.54, 6.56, 6.6, 6.62, 6.66, 6.8, 6.82, 6.9, 6.96] + expected_char_time_stamps_end = [1.44, 1.46, 1.54, 1.64, 1.66, 1.8, 1.86, 1.9, 2.06, 2.28, 2.34, 2.42, 2.48, 2.56, 2.68, 2.72, 2.78, 2.86, 2.9, 2.98, 3.02, 3.06, 3.12, 3.16, 3.24, 3.3, 3.44, 3.48, 3.52, 3.58, 3.64, 3.66, 3.72, 3.78, 3.82, 3.9, 3.94, 3.98, 4.04, 4.08, 4.12, 4.18, 4.26, 4.3, 4.36, 4.4, 4.52, 4.7, 4.76, 4.82, 4.9, 4.98, 5.08, 5.1, 5.16, 5.26, 5.32, 5.4, 5.52, 5.54, 5.64, 5.7, 5.72, 5.78, 5.82, 5.84, 5.86, 5.92, 5.98, 6.06, 6.12, 6.18, 6.24, 6.34, 6.4, 6.48, 6.56, 6.58, 6.62, 6.66, 6.68, 6.82, 6.84, 6.94, 7.02] + + expected_word_time_stamps_text = ['WHY', 'DOES', 'MILISANDRA', 'LOOK', 'LIKE', 'SHE', 'WANTS', 'TO', 'CONSUME', 'JOHN', 'SNOW', 'ON', 'THE', 'RIVT', 'AP', 'THE', 'WALL'] + expected_word_time_stamps_start = [1.42, 1.64, 2.26, 3.0, 3.28, 3.62, 3.8, 4.1, 4.28, 4.94, 5.28, 5.68, 5.8, 5.94, 6.32, 6.54, 6.66] + expected_word_time_stamps_end = [1.54, 1.9, 2.9, 3.16, 3.52, 3.72, 4.04, 4.18, 4.82, 5.16, 5.54, 5.72, 5.86, 6.18, 6.4, 6.62, 6.94] + # fmt: on + + output = tokenizer.batch_decode(pred_ids, output_char_offsets=True, output_word_offsets=True) + + char_offsets_text = self.get_from_offsets(output["char_offsets"][0], "char") + char_offsets_start = self.get_from_offsets(output["char_offsets"][0], "start_offset") + char_offsets_end = self.get_from_offsets(output["char_offsets"][0], "end_offset") + + word_offsets_text = self.get_from_offsets(output["word_offsets"][0], "word") + word_offsets_start = self.get_from_offsets(output["word_offsets"][0], "start_offset") + word_offsets_end = self.get_from_offsets(output["word_offsets"][0], "end_offset") + + # let's transform offsets to time stamps in seconds + char_time_stamps_start = [round(c * time_offset_wav2vec2_base, 2) for c in char_offsets_start] + char_time_stamps_end = [round(c * time_offset_wav2vec2_base, 2) for c in char_offsets_end] + + word_time_stamps_start = [round(w * time_offset_wav2vec2_base, 2) for w in word_offsets_start] + word_time_stamps_end = [round(w * time_offset_wav2vec2_base, 2) for w in word_offsets_end] + + # NOTE: you can verify the above results by checking out the dataset viewer + # on https://huggingface.co/datasets/common_voice/viewer/en/train and + # downloading / playing the sample `common_voice_en_100038.mp3`. As + # you can hear the time-stamps match more or less + + self.assertListEqual(expected_char_time_stamps_text, char_offsets_text) + self.assertListEqual(expected_char_time_stamps_start, char_time_stamps_start) + self.assertListEqual(expected_char_time_stamps_end, char_time_stamps_end) + + self.assertListEqual(expected_word_time_stamps_text, word_offsets_text) + self.assertListEqual(expected_word_time_stamps_start, word_time_stamps_start) + self.assertListEqual(expected_word_time_stamps_end, word_time_stamps_end) + + def test_pretrained_model_lists(self): + # Wav2Vec2Model has no max model length => no testing + pass + + # overwrite from test_tokenization_common + def test_add_tokens_tokenizer(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + vocab_size = tokenizer.vocab_size + all_size = len(tokenizer) + + self.assertNotEqual(vocab_size, 0) + + # We usually have added tokens from the start in tests because our vocab fixtures are + # smaller than the original vocabs - let's not assert this + # self.assertEqual(vocab_size, all_size) + + new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd"] + added_toks = tokenizer.add_tokens(new_toks) + vocab_size_2 = tokenizer.vocab_size + all_size_2 = len(tokenizer) + + self.assertNotEqual(vocab_size_2, 0) + self.assertEqual(vocab_size, vocab_size_2) + self.assertEqual(added_toks, len(new_toks)) + self.assertEqual(all_size_2, all_size + len(new_toks)) + + tokens = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False) + + self.assertGreaterEqual(len(tokens), 4) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-3], tokenizer.vocab_size - 1) + + new_toks_2 = { + "eos_token": AddedToken(">>>>|||<||<<|<<", lstrip=False, rstrip=False), + "pad_token": AddedToken("<<<<<|||>|>>>>|>", rstrip=False, lstrip=False), + } + added_toks_2 = tokenizer.add_special_tokens(new_toks_2) + vocab_size_3 = tokenizer.vocab_size + all_size_3 = len(tokenizer) + + self.assertNotEqual(vocab_size_3, 0) + self.assertEqual(vocab_size, vocab_size_3) + self.assertEqual(added_toks_2, len(new_toks_2)) + self.assertEqual(all_size_3, all_size_2 + len(new_toks_2)) + + tokens = tokenizer.encode( + ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", add_special_tokens=False + ) + + self.assertGreaterEqual(len(tokens), 6) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[0], tokens[1]) + self.assertGreater(tokens[-3], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-3], tokens[-4]) + self.assertEqual(tokens[0], tokenizer.eos_token_id) + self.assertEqual(tokens[-3], tokenizer.pad_token_id) + + @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.") + def test_tf_encode_plus_sent_to_model(self): + pass + + @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.") + def test_torch_encode_plus_sent_to_model(self): + pass + + def test_convert_tokens_to_string_format(self): + # The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which + # is not the case for Wav2vec2. + tokenizers = self.get_tokenizers(fast=True, do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokens = ["T", "H", "I", "S", "|", "I", "S", "|", "A", "|", "T", "E", "X", "T"] + output = tokenizer.convert_tokens_to_string(tokens) + + self.assertIsInstance(output["text"], str) + + def test_nested_vocab(self): + eng_vocab = {"a": 7, "b": 8} + spa_vocab = {"a": 23, "c": 88} + ita_vocab = {"a": 6, "d": 9} + + nested_vocab = {"eng": eng_vocab, "spa": spa_vocab, "ita": ita_vocab} + + def check_tokenizer(tokenizer, check_ita_first=False): + if check_ita_first: + self.assertEqual(tokenizer.decode([6, 9, 9]), "ad") + self.assertEqual(tokenizer.encoder, ita_vocab) + tokenizer.set_target_lang("eng") + + self.assertEqual(tokenizer.encoder, eng_vocab) + self.assertEqual(tokenizer.decode([7, 8, 7]), "aba") + + tokenizer.set_target_lang("spa") + self.assertEqual(tokenizer.decode([23, 88, 23]), "aca") + self.assertEqual(tokenizer.encoder, spa_vocab) + + tokenizer.set_target_lang("eng") + self.assertEqual(tokenizer.encoder, eng_vocab) + self.assertEqual(tokenizer.decode([7, 7, 8]), "ab") + + tokenizer.set_target_lang("ita") + self.assertEqual(tokenizer.decode([6, 9, 9]), "ad") + self.assertEqual(tokenizer.encoder, ita_vocab) + + with tempfile.TemporaryDirectory() as tempdir: + tempfile_path = os.path.join(tempdir, "vocab.json") + with open(tempfile_path, "w") as temp_file: + json.dump(nested_vocab, temp_file) + + tokenizer = Wav2Vec2CTCTokenizer.from_pretrained(tempdir, target_lang="eng") + + check_tokenizer(tokenizer) + + with tempfile.TemporaryDirectory() as tempdir: + # should have saved target lang as "ita" since it was last one + tokenizer.save_pretrained(tempdir) + tokenizer = Wav2Vec2CTCTokenizer.from_pretrained(tempdir) + + self.assertEqual(tokenizer.target_lang, "ita") + check_tokenizer(tokenizer, check_ita_first=True) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_conformer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_conformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_conformer/test_modeling_wav2vec2_conformer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_conformer/test_modeling_wav2vec2_conformer.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7bfd0a9beebbfefe0445058db8ea416729c3c7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_conformer/test_modeling_wav2vec2_conformer.py @@ -0,0 +1,986 @@ +# coding=utf-8 +# Copyright 2022 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 Wav2Vec2-Conformer model. """ +import math +import tempfile +import unittest + +import numpy as np +from datasets import load_dataset + +from transformers import Wav2Vec2ConformerConfig, is_torch_available +from transformers.testing_utils import ( + is_pt_flax_cross_test, + require_torch, + require_torch_accelerator, + require_torch_fp16, + slow, + torch_device, +) + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + Wav2Vec2ConformerForAudioFrameClassification, + Wav2Vec2ConformerForCTC, + Wav2Vec2ConformerForPreTraining, + Wav2Vec2ConformerForSequenceClassification, + Wav2Vec2ConformerForXVector, + Wav2Vec2ConformerModel, + Wav2Vec2FeatureExtractor, + Wav2Vec2Processor, + ) + from transformers.models.wav2vec2_conformer.modeling_wav2vec2_conformer import ( + Wav2Vec2ConformerGumbelVectorQuantizer, + _compute_mask_indices, + _sample_negative_indices, + ) + + +class Wav2Vec2ConformerModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=1024, # speech is longer + is_training=False, + hidden_size=16, + feat_extract_norm="group", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout_prob=0.1, + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + mask_time_prob=0.5, + mask_time_length=2, + vocab_size=32, + do_stable_layer_norm=False, + num_adapter_layers=1, + adapter_stride=2, + tdnn_dim=(32, 32), + tdnn_kernel=(5, 3), + tdnn_dilation=(1, 2), + xvector_output_dim=32, + position_embeddings_type="relative", + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout_prob = hidden_dropout_prob + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.num_adapter_layers = num_adapter_layers + self.adapter_stride = adapter_stride + self.mask_time_prob = mask_time_prob + self.mask_time_length = mask_time_length + self.scope = scope + self.tdnn_dim = tdnn_dim + self.tdnn_kernel = tdnn_kernel + self.tdnn_dilation = tdnn_dilation + self.xvector_output_dim = xvector_output_dim + self.position_embeddings_type = position_embeddings_type + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length + + self.adapter_output_seq_length = (self.output_seq_length - 1) // adapter_stride + 1 + + def prepare_config_and_inputs(self, position_embeddings_type="relative"): + input_values = floats_tensor([self.batch_size, self.seq_length], self.vocab_size) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config(position_embeddings_type=position_embeddings_type) + + return config, input_values, attention_mask + + def get_config(self, position_embeddings_type="relative"): + return Wav2Vec2ConformerConfig( + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + mask_time_prob=self.mask_time_prob, + mask_time_length=self.mask_time_length, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout_prob=self.hidden_dropout_prob, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + do_stable_layer_norm=self.do_stable_layer_norm, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + num_adapter_layers=self.num_adapter_layers, + adapter_stride=self.adapter_stride, + tdnn_dim=self.tdnn_dim, + tdnn_kernel=self.tdnn_kernel, + tdnn_dilation=self.tdnn_dilation, + xvector_output_dim=self.xvector_output_dim, + position_embeddings_type=position_embeddings_type, + ) + + def create_and_check_model(self, config, input_values, attention_mask): + model = Wav2Vec2ConformerModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_model_with_adapter(self, config, input_values, attention_mask): + config.add_adapter = True + model = Wav2Vec2ConformerModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.adapter_output_seq_length, self.hidden_size) + ) + + def create_and_check_model_with_adapter_for_ctc(self, config, input_values, attention_mask): + config.add_adapter = True + config.output_hidden_size = 2 * config.hidden_size + model = Wav2Vec2ConformerForCTC(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.logits.shape, (self.batch_size, self.adapter_output_seq_length, self.vocab_size) + ) + + def create_and_check_model_with_adapter_proj_dim(self, config, input_values, attention_mask): + config.add_adapter = True + config.output_hidden_size = 8 + model = Wav2Vec2ConformerModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, + (self.batch_size, self.adapter_output_seq_length, config.output_hidden_size), + ) + + def create_and_check_model_float16(self, config, input_values, attention_mask): + model = Wav2Vec2ConformerModel(config=config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = Wav2Vec2ConformerModel.from_pretrained(tmpdirname, torch_dtype=torch.float16) + + model.to(torch_device) + model.eval() + + with torch.no_grad(): + result = model(input_values.type(dtype=torch.float16), attention_mask=attention_mask) + + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_batch_inference(self, config, input_values, *args): + # test does not pass for models making use of `group_norm` + # check: https://github.com/pytorch/fairseq/issues/3227 + model = Wav2Vec2ConformerModel(config=config) + model.to(torch_device) + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0.0 + + batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state + + for i in range(input_values.shape[0]): + input_slice = input_values[i : i + 1, : input_lengths[i]] + output = model(input_slice).last_hidden_state + + batch_output = batch_outputs[i : i + 1, : output.shape[1]] + self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) + + def check_ctc_loss(self, config, input_values, *args): + model = Wav2Vec2ConformerForCTC(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + model.config.ctc_loss_reduction = "sum" + sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + model.config.ctc_loss_reduction = "mean" + mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(sum_loss, float)) + self.parent.assertTrue(isinstance(mean_loss, float)) + + def check_seq_classifier_loss(self, config, input_values, *args): + model = Wav2Vec2ConformerForSequenceClassification(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + unmasked_loss = model(input_values, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(masked_loss, float)) + self.parent.assertTrue(isinstance(unmasked_loss, float)) + self.parent.assertTrue(masked_loss != unmasked_loss) + + def check_ctc_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = Wav2Vec2ConformerForCTC(config=config) + model.to(torch_device) + model.train() + + # freeze feature encoder + model.freeze_feature_encoder() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + if max_length_labels[i] < labels.shape[-1]: + # it's important that we make sure that target lengths are at least + # one shorter than logit lengths to prevent -inf + labels[i, max_length_labels[i] - 1 :] = -100 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_seq_classifier_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = Wav2Vec2ConformerForSequenceClassification(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_xvector_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = Wav2Vec2ConformerForXVector(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_labels_out_of_vocab(self, config, input_values, *args): + model = Wav2Vec2ConformerForCTC(config) + model.to(torch_device) + model.train() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) + + with self.parent.assertRaises(ValueError): + model(input_values, labels=labels) + + def prepare_config_and_inputs_for_common(self): + config, input_values, attention_mask = self.prepare_config_and_inputs() + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class Wav2Vec2ConformerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + Wav2Vec2ConformerForCTC, + Wav2Vec2ConformerModel, + Wav2Vec2ConformerForSequenceClassification, + Wav2Vec2ConformerForPreTraining, + Wav2Vec2ConformerForAudioFrameClassification, + Wav2Vec2ConformerForXVector, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + { + "audio-classification": Wav2Vec2ConformerForSequenceClassification, + "automatic-speech-recognition": Wav2Vec2ConformerForCTC, + "feature-extraction": Wav2Vec2ConformerModel, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_headmasking = False + test_torchscript = False + + def setUp(self): + self.model_tester = Wav2Vec2ConformerModelTester(self) + self.config_tester = ConfigTester(self, config_class=Wav2Vec2ConformerConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_with_relative(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="relative") + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_with_rotary(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="rotary") + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_with_no_rel_pos(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type=None) + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_with_adapter(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_adapter(*config_and_inputs) + + def test_model_with_adapter_for_ctc(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_adapter_for_ctc(*config_and_inputs) + + def test_model_with_adapter_proj_dim(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_with_adapter_proj_dim(*config_and_inputs) + + @require_torch_accelerator + @require_torch_fp16 + def test_model_float16_with_relative(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="relative") + self.model_tester.create_and_check_model_float16(*config_and_inputs) + + @require_torch_accelerator + @require_torch_fp16 + def test_model_float16_with_rotary(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="rotary") + self.model_tester.create_and_check_model_float16(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_seq_classifier_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_seq_classifier_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_training(*config_and_inputs) + + def test_xvector_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_xvector_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # Wav2Vec2Conformer has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # Wav2Vec2Conformer cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # Wav2Vec2Conformer has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + @is_pt_flax_cross_test + # non-robust architecture does not exist in Flax + def test_equivalence_flax_to_pt(self): + pass + + @is_pt_flax_cross_test + # non-robust architecture does not exist in Flax + def test_equivalence_pt_to_flax(self): + pass + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + attentions = outputs.attentions[0] + + hidden_states.retain_grad() + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "pos_bias_v", + "pos_bias_u", + "pointwise_conv1", + "pointwise_conv2", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "objective.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "pos_bias_u") and module.pos_bias_u is not None: + module.pos_bias_u.data.fill_(3) + if hasattr(module, "pos_bias_v") and module.pos_bias_v is not None: + module.pos_bias_v.data.fill_(3) + if hasattr(module, "codevectors") and module.codevectors is not None: + module.codevectors.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + def test_mask_feature_prob_ctc(self): + model = Wav2Vec2ConformerForCTC.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2-conformer", mask_feature_prob=0.2, mask_feature_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2-conformer", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + def test_mask_time_prob_ctc(self): + model = Wav2Vec2ConformerForCTC.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2-conformer", mask_time_prob=0.2, mask_time_length=2 + ) + model.to(torch_device).train() + processor = Wav2Vec2Processor.from_pretrained( + "hf-internal-testing/tiny-random-wav2vec2-conformer", return_attention_mask=True + ) + + batch_duration_in_seconds = [1, 3, 2, 6] + input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] + + batch = processor( + input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" + ) + + logits = model( + input_values=batch["input_values"].to(torch_device), + attention_mask=batch["attention_mask"].to(torch_device), + ).logits + + self.assertEqual(logits.shape, (4, 1498, 32)) + + @unittest.skip(reason="Feed forward chunking is not implemented") + def test_feed_forward_chunking(self): + pass + + @slow + def test_model_from_pretrained(self): + model = Wav2Vec2ConformerModel.from_pretrained("facebook/wav2vec2-conformer-rel-pos-large") + self.assertIsNotNone(model) + + +@require_torch +class Wav2Vec2ConformerUtilsTest(unittest.TestCase): + def test_compute_mask_indices(self): + batch_size = 4 + sequence_length = 60 + mask_prob = 0.5 + mask_length = 1 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + self.assertListEqual(mask.sum(axis=-1).tolist(), [mask_prob * sequence_length for _ in range(batch_size)]) + + def test_compute_mask_indices_low_prob(self): + # with these settings num_masked_spans=0.5, which means probabilistic rounding + # ensures that in 5 out of 10 method calls, num_masked_spans=0, and in + # the other 5 out of 10, cases num_masked_spans=1 + n_trials = 100 + batch_size = 4 + sequence_length = 100 + mask_prob = 0.05 + mask_length = 10 + + count_dimensions_masked = 0 + count_dimensions_not_masked = 0 + + for _ in range(n_trials): + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + num_masks = torch.sum(mask).item() + + if num_masks > 0: + count_dimensions_masked += 1 + else: + count_dimensions_not_masked += 1 + + # as we test for at least 10 masked dimension and at least + # 10 non-masked dimension, this test could fail with probability: + # P(100 coin flips, at most 9 heads) = 1.66e-18 + self.assertGreater(count_dimensions_masked, int(n_trials * 0.1)) + self.assertGreater(count_dimensions_not_masked, int(n_trials * 0.1)) + + def test_compute_mask_indices_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) + mask = torch.from_numpy(mask).to(torch_device) + + # because of overlap mask don't have to add up exactly to `mask_prob * sequence_length`, but have to be smaller or equal + for batch_sum in mask.sum(axis=-1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + def test_compute_mask_indices_attn_mask_overlap(self): + batch_size = 4 + sequence_length = 80 + mask_prob = 0.5 + mask_length = 4 + + attention_mask = torch.ones((batch_size, sequence_length), dtype=torch.long, device=torch_device) + attention_mask[:2, sequence_length // 2 :] = 0 + + mask = _compute_mask_indices( + (batch_size, sequence_length), mask_prob, mask_length, attention_mask=attention_mask + ) + mask = torch.from_numpy(mask).to(torch_device) + + for batch_sum in mask.sum(axis=-1): + self.assertTrue(int(batch_sum) <= mask_prob * sequence_length) + + self.assertTrue(mask[:2, sequence_length // 2 :].sum() == 0) + + def test_compute_mask_indices_short_audio(self): + batch_size = 4 + sequence_length = 100 + mask_prob = 0.05 + mask_length = 10 + + attention_mask = torch.ones((batch_size, sequence_length), dtype=torch.long, device=torch_device) + # force one example to be heavily padded + attention_mask[0, 5:] = 0 + + mask = _compute_mask_indices( + (batch_size, sequence_length), mask_prob, mask_length, attention_mask=attention_mask, min_masks=2 + ) + + # make sure that non-padded examples cannot be padded + self.assertFalse(mask[0][attention_mask[0].to(torch.bool).cpu()].any()) + + def test_compute_perplexity(self): + probs = torch.arange(100, device=torch_device).reshape(2, 5, 10) / 100 + + ppl = Wav2Vec2ConformerGumbelVectorQuantizer._compute_perplexity(probs) + self.assertTrue(abs(ppl.item() - 141.4291) < 1e-3) + + # mask half of the input + mask = torch.ones((2,), device=torch_device, dtype=torch.bool) + mask[0] = 0 + + ppl = Wav2Vec2ConformerGumbelVectorQuantizer._compute_perplexity(probs, mask) + self.assertTrue(abs(ppl.item() - 58.6757) < 1e-3) + + def test_sample_negatives(self): + batch_size = 2 + sequence_length = 10 + hidden_size = 4 + num_negatives = 3 + + features = (torch.arange(sequence_length * hidden_size, device=torch_device) // hidden_size).view( + sequence_length, hidden_size + ) # each value in vector consits of same value + features = features[None, :].expand(batch_size, sequence_length, hidden_size).contiguous() + + # sample negative indices + sampled_negative_indices = _sample_negative_indices((batch_size, sequence_length), num_negatives, None) + sampled_negative_indices = torch.from_numpy(sampled_negative_indices).to(torch_device) + negatives = features.view(-1, hidden_size)[sampled_negative_indices.long().view(-1)] + negatives = negatives.view(batch_size, sequence_length, -1, hidden_size).permute(2, 0, 1, 3) + self.assertTrue(negatives.shape == (num_negatives, batch_size, sequence_length, hidden_size)) + + # make sure no negatively sampled vector is actually a positive one + for negative in negatives: + self.assertTrue(((negative - features) == 0).sum() == 0.0) + + # make sure that full vectors are sampled and not values of vectors => this means that `unique()` yields a single value for `hidden_size` dim + self.assertTrue(negatives.unique(dim=-1).shape, (num_negatives, batch_size, sequence_length, 1)) + + def test_sample_negatives_with_mask(self): + batch_size = 2 + sequence_length = 10 + hidden_size = 4 + num_negatives = 3 + + # second half of last input tensor is padded + mask = torch.ones((batch_size, sequence_length), dtype=torch.long, device=torch_device) + mask[-1, sequence_length // 2 :] = 0 + + features = (torch.arange(sequence_length * hidden_size, device=torch_device) // hidden_size).view( + sequence_length, hidden_size + ) # each value in vector consits of same value + features = features[None, :].expand(batch_size, sequence_length, hidden_size).contiguous() + + # replace masked feature vectors with -100 to test that those are not sampled + features = torch.where(mask[:, :, None].expand(features.shape).bool(), features, -100) + + # sample negative indices + sampled_negative_indices = _sample_negative_indices( + (batch_size, sequence_length), num_negatives, mask.cpu().numpy() + ) + sampled_negative_indices = torch.from_numpy(sampled_negative_indices).to(torch_device) + negatives = features.view(-1, hidden_size)[sampled_negative_indices.long().view(-1)] + negatives = negatives.view(batch_size, sequence_length, -1, hidden_size).permute(2, 0, 1, 3) + + self.assertTrue((negatives >= 0).all().item()) + + self.assertTrue(negatives.shape == (num_negatives, batch_size, sequence_length, hidden_size)) + + # make sure no negatively sampled vector is actually a positive one + for negative in negatives: + self.assertTrue(((negative - features) == 0).sum() == 0.0) + + # make sure that full vectors are sampled and not values of vectors => this means that `unique()` yields a single value for `hidden_size` dim + self.assertTrue(negatives.unique(dim=-1).shape, (num_negatives, batch_size, sequence_length, 1)) + + +@require_torch +@slow +class Wav2Vec2ConformerModelIntegrationTest(unittest.TestCase): + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter(lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)]) + speech_samples = speech_samples[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_inference_ctc_normal_batched_rel_pos(self): + model = Wav2Vec2ConformerForCTC.from_pretrained("facebook/wav2vec2-conformer-rel-pos-large-960h-ft") + model.to(torch_device) + processor = Wav2Vec2Processor.from_pretrained( + "facebook/wav2vec2-conformer-rel-pos-large-960h-ft", do_lower_case=True + ) + + input_speech = self._load_datasamples(2) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + + with torch.no_grad(): + logits = model(input_values).logits + + predicted_ids = torch.argmax(logits, dim=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "sweat covered brion's body trickling into the tight loincloth that was the only garment he wore", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + def test_inference_ctc_normal_batched_rope(self): + model = Wav2Vec2ConformerForCTC.from_pretrained("facebook/wav2vec2-conformer-rope-large-960h-ft") + model.to(torch_device) + processor = Wav2Vec2Processor.from_pretrained( + "facebook/wav2vec2-conformer-rope-large-960h-ft", do_lower_case=True + ) + + input_speech = self._load_datasamples(2) + + inputs = processor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + + with torch.no_grad(): + logits = model(input_values).logits + + predicted_ids = torch.argmax(logits, dim=-1) + predicted_trans = processor.batch_decode(predicted_ids) + + EXPECTED_TRANSCRIPTIONS = [ + "a man said to the universe sir i exist", + "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore", + ] + self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) + + def test_inference_pretrained(self): + model = Wav2Vec2ConformerForPreTraining.from_pretrained("facebook/wav2vec2-conformer-rel-pos-large") + model.to(torch_device) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( + "facebook/wav2vec2-conformer-rel-pos-large", return_attention_mask=True + ) + input_speech = self._load_datasamples(2) + + inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) + + batch_size = inputs_dict["input_values"].shape[0] + feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1])) + + features_shape = (batch_size, feature_seq_length) + + torch.manual_seed(0) + mask_time_indices = _compute_mask_indices( + features_shape, + model.config.mask_time_prob, + model.config.mask_time_length, + min_masks=2, + ) + mask_time_indices = torch.from_numpy(mask_time_indices).to(torch_device) + + with torch.no_grad(): + outputs = model( + inputs_dict.input_values.to(torch_device), + attention_mask=inputs_dict.attention_mask.to(torch_device), + mask_time_indices=mask_time_indices, + ) + + # compute cosine similarity + cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1) + + # retrieve cosine sim of masked features + cosine_sim_masked = cosine_sim[mask_time_indices] + + # ... now compare to randomly initialized model + + config = Wav2Vec2ConformerConfig.from_pretrained("facebook/wav2vec2-conformer-rel-pos-large") + model_rand = Wav2Vec2ConformerForPreTraining(config).to(torch_device).eval() + + with torch.no_grad(): + outputs_rand = model_rand( + inputs_dict.input_values.to(torch_device), + attention_mask=inputs_dict.attention_mask.to(torch_device), + mask_time_indices=mask_time_indices, + ) + + # compute cosine similarity + cosine_sim_rand = torch.cosine_similarity( + outputs_rand.projected_states, outputs_rand.projected_quantized_states, dim=-1 + ) + + # retrieve cosine sim of masked features + cosine_sim_masked_rand = cosine_sim_rand[mask_time_indices] + + # a pretrained wav2vec2_conformer model has learned to predict the quantized latent states + # => the cosine similarity between quantized states and predicted states > 0.5 + # a random wav2vec2_conformer model has not learned to predict the quantized latent states + # => the cosine similarity between quantized states and predicted states is very likely < 0.1 + self.assertTrue(cosine_sim_masked.mean().item() - 5 * cosine_sim_masked_rand.mean().item() > 0) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_phoneme/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_phoneme/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_phoneme/test_tokenization_wav2vec2_phoneme.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_phoneme/test_tokenization_wav2vec2_phoneme.py new file mode 100644 index 0000000000000000000000000000000000000000..0411a863bc723adfd6dcb54d8355f2e655ee90c7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_phoneme/test_tokenization_wav2vec2_phoneme.py @@ -0,0 +1,411 @@ +# coding=utf-8 +# Copyright 2021 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. +"""Tests for the Wav2Vec2Phoneme tokenizer.""" +import json +import os +import unittest +from typing import Tuple + +from transformers import Wav2Vec2PhonemeCTCTokenizer +from transformers.models.wav2vec2.tokenization_wav2vec2 import VOCAB_FILES_NAMES +from transformers.models.wav2vec2_phoneme.tokenization_wav2vec2_phoneme import Wav2Vec2PhonemeCTCTokenizerOutput +from transformers.testing_utils import require_phonemizer + +from ...test_tokenization_common import TokenizerTesterMixin + + +@require_phonemizer +class Wav2Vec2PhonemeCTCTokenizerTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = Wav2Vec2PhonemeCTCTokenizer + test_rust_tokenizer = False + + def setUp(self): + super().setUp() + + vocab = ( + " n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː " + "ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː " + "ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 " + "oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ " + "pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ " + "yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ " + 'əʊ S ɡʲ onɡ2 u" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ ' + "ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ " + "ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ " + "uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ " + "ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ " + "ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ " + "ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4" + ).split(" ") + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + + self.special_tokens_map = {"pad_token": "", "unk_token": "", "bos_token": "", "eos_token": ""} + + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + with open(self.vocab_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(vocab_tokens) + "\n") + + # overwrite since phonemes require specific creation + def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5) -> Tuple[str, list]: + toks = [(i, tokenizer.decode([i], clean_up_tokenization_spaces=False)) for i in range(len(tokenizer))] + toks = list(filter(lambda t: [t[0]] == tokenizer.encode(t[1], do_phonemize=False), toks)) + if max_length is not None and len(toks) > max_length: + toks = toks[:max_length] + if min_length is not None and len(toks) < min_length and len(toks) > 0: + while len(toks) < min_length: + toks = toks + toks + # toks_str = [t[1] for t in toks] + toks_ids = [t[0] for t in toks] + + # Ensure consistency + output_txt = tokenizer.decode(toks_ids, clean_up_tokenization_spaces=False) + if " " not in output_txt and len(toks_ids) > 1: + output_txt = ( + tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=False) + + " " + + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=False) + ) + if with_prefix_space: + output_txt = " " + output_txt + output_ids = tokenizer.encode(output_txt, add_special_tokens=False) + return output_txt, output_ids + + def get_tokenizer(self, **kwargs): + kwargs.update(self.special_tokens_map) + return Wav2Vec2PhonemeCTCTokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def test_tokenizer_add_new_tokens(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") + + # check adding a single token + tokenizer.add_tokens("xxx") + token_ids = tokenizer("m xxx ɪ", do_phonemize=False).input_ids + self.assertEqual(token_ids, [13, 392, 17]) # xxx should be last token + + tokenizer.add_tokens(["aaa", "bbb", "ccc"]) + token_ids = tokenizer("m aaa ɪ ccc", do_phonemize=False).input_ids + self.assertEqual(token_ids, [13, 393, 17, 395]) # aaa and ccc should be after xxx and 2 after aaa + + token_ids = tokenizer("maɪ c", do_phonemize=False).input_ids + self.assertEqual(token_ids, [3, 200]) # mai should be (=3) + + def test_phonemize(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") + + input_text = "Hello how are you" + phonemes = tokenizer.phonemize(input_text, phonemizer_lang="en-us") + self.assertEqual(phonemes, "h ə l oʊ h aʊ ɑːɹ j uː") + + def test_encode(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") + + input_text = "Hello how are you" + phonemes = tokenizer.phonemize(input_text, phonemizer_lang="en-us") + self.assertEqual(tokenizer(input_text).input_ids, tokenizer(phonemes, do_phonemize=False).input_ids) + + def test_encode_decode(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") + input_text = "Hello how are you" + phonemes = tokenizer.phonemize(input_text, phonemizer_lang="en-us") + + phonemes_enc_dec = tokenizer.decode(tokenizer(input_text).input_ids) + + self.assertEqual(phonemes, phonemes_enc_dec) + + def test_decode(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") + + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98], + [24, 22, 5, 24, 22, 5, 77], + ] + tokens = tokenizer.decode(sample_ids[0]) + batch_tokens = tokenizer.batch_decode(sample_ids) + self.assertEqual(tokens, batch_tokens[0]) + self.assertEqual(batch_tokens, ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"]) + + def test_phonemize_with_word_del(self): + tokenizer = self.tokenizer_class.from_pretrained( + "facebook/wav2vec2-lv-60-espeak-cv-ft", word_delimiter_token="|" + ) + tokenizer.add_tokens("|") + + input_text = "Hello how are you" + phonemes = tokenizer.phonemize(input_text, phonemizer_lang="en-us") + self.assertEqual(phonemes, "h ə l oʊ | h aʊ | ɑːɹ | j uː |") + + def test_encode_with_del(self): + tokenizer = self.tokenizer_class.from_pretrained( + "facebook/wav2vec2-lv-60-espeak-cv-ft", word_delimiter_token="|" + ) + tokenizer.add_tokens("|") + + input_text = "Hello how are you" + phonemes = tokenizer.phonemize(input_text, phonemizer_lang="en-us") + self.assertEqual(tokenizer(input_text).input_ids, tokenizer(phonemes, do_phonemize=False).input_ids) + + def test_decode_with_del(self): + tokenizer = self.tokenizer_class.from_pretrained( + "facebook/wav2vec2-lv-60-espeak-cv-ft", word_delimiter_token="|" + ) + tokenizer.add_tokens("|") + + # fmt: off + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 15, 8, tokenizer.word_delimiter_token_id, 98], + [tokenizer.word_delimiter_token_id, 24, 22, tokenizer.word_delimiter_token_id, 5, 24, 22, 5, 77], + ] + # fmt: on + + # decode with word_del_token filter + tokens = tokenizer.decode(sample_ids[0]) + batch_tokens = tokenizer.batch_decode(sample_ids) + self.assertEqual(tokens, batch_tokens[0]) + self.assertEqual(batch_tokens, ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"]) + + # decode with no word_del_token filter + tokens = tokenizer.decode(sample_ids[0], filter_word_delimiter_token=False) + batch_tokens = tokenizer.batch_decode(sample_ids, filter_word_delimiter_token=False) + self.assertEqual(tokens, batch_tokens[0]) + self.assertEqual(batch_tokens, ["k s ɾ | ɾ l | ɭʲ", "| j ð | s j ð s oːɹ"]) + + def test_encode_decode_with_del(self): + tokenizer = self.tokenizer_class.from_pretrained( + "facebook/wav2vec2-lv-60-espeak-cv-ft", word_delimiter_token="|" + ) + tokenizer.add_tokens("|") + + input_text = "Hello how are you" + phonemes = tokenizer.phonemize(input_text, phonemizer_lang="en-us") + + phonemes_enc_dec = tokenizer.decode(tokenizer(input_text).input_ids, filter_word_delimiter_token=False) + + self.assertEqual(phonemes, phonemes_enc_dec) + + def test_encode_decode_with_del_filter(self): + tokenizer = self.tokenizer_class.from_pretrained( + "facebook/wav2vec2-lv-60-espeak-cv-ft", word_delimiter_token="|" + ) + tokenizer.add_tokens("|") + + input_text = "Hello how are you" + phonemes = tokenizer.phonemize(input_text, phonemizer_lang="en-us") + + phonemes_enc_dec = tokenizer.decode(tokenizer(input_text).input_ids, filter_word_delimiter_token=True) + + self.assertEqual(" ".join([p.strip() for p in phonemes.split(" |")]).strip(), phonemes_enc_dec) + + def test_change_phonemizer_lang(self): + tokenizer = self.tokenizer_class.from_pretrained( + "facebook/wav2vec2-lv-60-espeak-cv-ft", word_delimiter_token=None + ) + input_text = "Hello how are you" + + input_ids_en = tokenizer(input_text, phonemizer_lang="en-us").input_ids + input_ids_fr = tokenizer(input_text, phonemizer_lang="fr-fr").input_ids + + self.assertNotEqual(input_ids_en, input_ids_fr) + + text_en = tokenizer.decode(input_ids_en) + text_fr = tokenizer.decode(input_ids_fr) + + self.assertEqual(text_en, "h ə l oʊ h aʊ ɑːɹ j uː") + self.assertEqual(text_fr, "ɛ l o h aʊ a ʁ j u") + + def test_case_insensitive(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") + input_text_up = "Hello how Are you" + input_text_low = "hello how are you" + + input_ids_up = tokenizer(input_text_up).input_ids + input_ids_low = tokenizer(input_text_low).input_ids + + self.assertEqual(input_ids_up, input_ids_low) + + def test_tokenizer_decode_added_tokens(self): + tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") + tokenizer.add_tokens(["!", "?"]) + tokenizer.add_special_tokens({"cls_token": "$$$"}) + + # fmt: off + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 8, 98, 392, 392, 393, 392, 392, 393, 394, 394], + [24, 22, 5, 24, 22, 5, 77, tokenizer.pad_token_id, 394, 394], + ] + # fmt: on + + batch_tokens = tokenizer.batch_decode(sample_ids) + self.assertEqual(batch_tokens, ["k s ɾ ɾ l ɭʲ!?!? $$$", "j ð s j ð s oːɹ $$$"]) + + @staticmethod + def get_from_offsets(offsets, key): + retrieved_list = [d[key] for d in offsets] + return retrieved_list + + def test_offsets(self): + tokenizer = self.get_tokenizer(word_delimiter_token="|") + tokenizer.add_tokens("|") + + # fmt: off + # ksssɾɾ|ɾɾɾɾ|ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ" + sample_ids = [11, 5, 5, 5, 15, 15, tokenizer.pad_token_id, 15, 15, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 15, 8, 8, 8, tokenizer.word_delimiter_token_id, 98] + # fmt: on + + outputs = tokenizer.decode(sample_ids, output_char_offsets=True, filter_word_delimiter_token=False) + # check Wav2Vec2CTCTokenizerOutput keys for char + self.assertEqual(len(outputs.keys()), 2) + self.assertTrue("text" in outputs) + self.assertTrue("char_offsets" in outputs) + self.assertTrue(isinstance(outputs, Wav2Vec2PhonemeCTCTokenizerOutput)) + + # check that order of chars is correct and identical for both outputs + self.assertEqual(" ".join(self.get_from_offsets(outputs["char_offsets"], "char")), outputs.text) + self.assertListEqual( + self.get_from_offsets(outputs["char_offsets"], "char"), ["k", "s", "ɾ", "ɾ", "|", "ɾ", "l", "|", "ɭʲ"] + ) + + # check that offsets are actually correct for char + # 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token, + # 10-11 is (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98 + self.assertListEqual( + self.get_from_offsets(outputs["char_offsets"], "start_offset"), [0, 1, 4, 7, 9, 11, 12, 15, 16] + ) + self.assertListEqual( + self.get_from_offsets(outputs["char_offsets"], "end_offset"), [1, 4, 6, 9, 10, 12, 15, 16, 17] + ) + + def test_offsets_batch(self): + tokenizer = self.get_tokenizer(word_delimiter_token="|") + + def check_list_tuples_equal(outputs_batch, outputs_list): + self.assertTrue(isinstance(outputs_batch, Wav2Vec2PhonemeCTCTokenizerOutput)) + self.assertTrue(isinstance(outputs_list[0], Wav2Vec2PhonemeCTCTokenizerOutput)) + + # transform list to ModelOutput + outputs_batch_2 = Wav2Vec2PhonemeCTCTokenizerOutput( + {k: [d[k] for d in outputs_list] for k in outputs_list[0]} + ) + + self.assertListEqual(outputs_batch["text"], outputs_batch_2["text"]) + + def recursive_check(list_or_dict_1, list_or_dict_2): + if isinstance(list_or_dict_1, list): + [recursive_check(l1, l2) for l1, l2 in zip(list_or_dict_1, list_or_dict_2)] + self.assertEqual(list_or_dict_1, list_or_dict_2) + + if "char_offsets" in outputs_batch: + recursive_check(outputs_batch["char_offsets"], outputs_batch_2["char_offsets"]) + + # fmt: off + sample_ids = [ + [11, 5, 15, tokenizer.pad_token_id, 15, 4, 8, 98, 32, 32, 32, 32, 4, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34], + [24, 22, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 24, 22, 22, 22, 4, 5, 77, tokenizer.pad_token_id, 22, 22, 4, 34, 34, 34, 34], + ] + # fmt: on + + # We assume that `decode` works as expected. All we will check now is + # the output type is correct and the output is identical to `decode` + + # char + outputs_char_batch = tokenizer.batch_decode(sample_ids, output_char_offsets=True) + outputs_char = [tokenizer.decode(ids, output_char_offsets=True) for ids in sample_ids] + check_list_tuples_equal(outputs_char_batch, outputs_char) + + @unittest.skip("Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes") + def test_added_tokens_do_lower_case(self): + pass + + @unittest.skip("Wav2Vec2PhonemeTokenizer always puts spaces between phonemes") + def test_encode_decode_with_spaces(self): + pass + + @unittest.skip("encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency") + def test_internal_consistency(self): + pass + + @unittest.skip("Wav2Vec2PhonemeModel has no max model length => no testing") + def test_pretrained_model_lists(self): + pass + + # overwrite common + def test_add_tokens_tokenizer(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + vocab_size = tokenizer.vocab_size + all_size = len(tokenizer) + + self.assertNotEqual(vocab_size, 0) + + # We usually have added tokens from the start in tests because our vocab fixtures are + # smaller than the original vocabs - let's not assert this + # self.assertEqual(vocab_size, all_size) + + new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd"] + added_toks = tokenizer.add_tokens(new_toks) + vocab_size_2 = tokenizer.vocab_size + all_size_2 = len(tokenizer) + + self.assertNotEqual(vocab_size_2, 0) + self.assertEqual(vocab_size, vocab_size_2) + self.assertEqual(added_toks, len(new_toks)) + self.assertEqual(all_size_2, all_size + len(new_toks)) + + tokens = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False) + + self.assertGreaterEqual(len(tokens), 4) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-3], tokenizer.vocab_size - 1) + + new_toks_2 = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} + added_toks_2 = tokenizer.add_special_tokens(new_toks_2) + vocab_size_3 = tokenizer.vocab_size + all_size_3 = len(tokenizer) + + self.assertNotEqual(vocab_size_3, 0) + self.assertEqual(vocab_size, vocab_size_3) + self.assertEqual(added_toks_2, len(new_toks_2)) + self.assertEqual(all_size_3, all_size_2 + len(new_toks_2)) + + tokens = tokenizer.encode( + ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", add_special_tokens=False + ) + + self.assertGreaterEqual(len(tokens), 6) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[0], tokens[1]) + self.assertGreater(tokens[-3], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-3], tokens[-4]) + self.assertEqual(tokens[0], tokenizer.eos_token_id) + self.assertEqual(tokens[-3], tokenizer.pad_token_id) + + @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.") + def test_tf_encode_plus_sent_to_model(self): + pass + + @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.") + def test_torch_encode_plus_sent_to_model(self): + pass + + def test_convert_tokens_to_string_format(self): + # The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which + # is not the case for Wav2Vec2PhonemeCTCTokenizer. + tokenizers = self.get_tokenizers(fast=True, do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokens = ["ð", "ɪ", "s", "ɪ", "z", "ɐ", "t", "ɛ", "k", "s", "t"] + output = tokenizer.convert_tokens_to_string(tokens) + + self.assertIsInstance(output["text"], str) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_with_lm/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_with_lm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_with_lm/test_processor_wav2vec2_with_lm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_with_lm/test_processor_wav2vec2_with_lm.py new file mode 100644 index 0000000000000000000000000000000000000000..2c52a921653c61a3f827f52d3a39d74f2cdebe43 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wav2vec2_with_lm/test_processor_wav2vec2_with_lm.py @@ -0,0 +1,479 @@ +# Copyright 2021 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 shutil +import tempfile +import unittest +from multiprocessing import get_context +from pathlib import Path + +import datasets +import numpy as np +from datasets import load_dataset +from parameterized import parameterized + +from transformers import AutoProcessor +from transformers.models.wav2vec2 import Wav2Vec2CTCTokenizer, Wav2Vec2FeatureExtractor +from transformers.models.wav2vec2.tokenization_wav2vec2 import VOCAB_FILES_NAMES +from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow +from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available + +from ..wav2vec2.test_feature_extraction_wav2vec2 import floats_list + + +if is_pyctcdecode_available(): + from huggingface_hub import snapshot_download + from pyctcdecode import BeamSearchDecoderCTC + + from transformers.models.wav2vec2_with_lm import Wav2Vec2ProcessorWithLM + from transformers.models.wav2vec2_with_lm.processing_wav2vec2_with_lm import Wav2Vec2DecoderWithLMOutput + +if is_torch_available(): + from transformers import Wav2Vec2ForCTC + + +@require_pyctcdecode +class Wav2Vec2ProcessorWithLMTest(unittest.TestCase): + def setUp(self): + vocab = "| a b c d e f g h i j k".split() + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + + self.add_kwargs_tokens_map = { + "unk_token": "", + "bos_token": "", + "eos_token": "", + } + feature_extractor_map = { + "feature_size": 1, + "padding_value": 0.0, + "sampling_rate": 16000, + "return_attention_mask": False, + "do_normalize": True, + } + + self.tmpdirname = tempfile.mkdtemp() + self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) + self.feature_extraction_file = os.path.join(self.tmpdirname, FEATURE_EXTRACTOR_NAME) + with open(self.vocab_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(vocab_tokens) + "\n") + + with open(self.feature_extraction_file, "w", encoding="utf-8") as fp: + fp.write(json.dumps(feature_extractor_map) + "\n") + + # load decoder from hub + self.decoder_name = "hf-internal-testing/ngram-beam-search-decoder" + + def get_tokenizer(self, **kwargs_init): + kwargs = self.add_kwargs_tokens_map.copy() + kwargs.update(kwargs_init) + return Wav2Vec2CTCTokenizer.from_pretrained(self.tmpdirname, **kwargs) + + def get_feature_extractor(self, **kwargs): + return Wav2Vec2FeatureExtractor.from_pretrained(self.tmpdirname, **kwargs) + + def get_decoder(self, **kwargs): + return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_save_load_pretrained_default(self): + tokenizer = self.get_tokenizer() + feature_extractor = self.get_feature_extractor() + decoder = self.get_decoder() + + processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) + + processor.save_pretrained(self.tmpdirname) + processor = Wav2Vec2ProcessorWithLM.from_pretrained(self.tmpdirname) + + # tokenizer + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) + self.assertIsInstance(processor.tokenizer, Wav2Vec2CTCTokenizer) + + # feature extractor + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string()) + self.assertIsInstance(processor.feature_extractor, Wav2Vec2FeatureExtractor) + + # decoder + self.assertEqual(processor.decoder._alphabet.labels, decoder._alphabet.labels) + self.assertEqual( + processor.decoder.model_container[decoder._model_key]._unigram_set, + decoder.model_container[decoder._model_key]._unigram_set, + ) + self.assertIsInstance(processor.decoder, BeamSearchDecoderCTC) + + def test_save_load_pretrained_additional_features(self): + processor = Wav2Vec2ProcessorWithLM( + tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor(), decoder=self.get_decoder() + ) + processor.save_pretrained(self.tmpdirname) + + # make sure that error is thrown when decoder alphabet doesn't match + processor = Wav2Vec2ProcessorWithLM.from_pretrained( + self.tmpdirname, alpha=5.0, beta=3.0, score_boundary=-7.0, unk_score_offset=3 + ) + + # decoder + self.assertEqual(processor.language_model.alpha, 5.0) + self.assertEqual(processor.language_model.beta, 3.0) + self.assertEqual(processor.language_model.score_boundary, -7.0) + self.assertEqual(processor.language_model.unk_score_offset, 3) + + def test_load_decoder_tokenizer_mismatch_content(self): + tokenizer = self.get_tokenizer() + # add token to trigger raise + tokenizer.add_tokens(["xx"]) + with self.assertRaisesRegex(ValueError, "include"): + Wav2Vec2ProcessorWithLM( + tokenizer=tokenizer, feature_extractor=self.get_feature_extractor(), decoder=self.get_decoder() + ) + + def test_feature_extractor(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + decoder = self.get_decoder() + + processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) + + raw_speech = floats_list((3, 1000)) + + input_feat_extract = feature_extractor(raw_speech, return_tensors="np") + input_processor = processor(raw_speech, return_tensors="np") + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_tokenizer(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + decoder = self.get_decoder() + + processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) + + input_str = "This is a test string" + + encoded_processor = processor(text=input_str) + + encoded_tok = tokenizer(input_str) + + for key in encoded_tok.keys(): + self.assertListEqual(encoded_tok[key], encoded_processor[key]) + + def _get_dummy_logits(self, shape=(2, 10, 16), seed=77): + np.random.seed(seed) + return np.random.rand(*shape) + + def test_decoder(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + decoder = self.get_decoder() + + processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) + + logits = self._get_dummy_logits(shape=(10, 16), seed=13) + + decoded_processor = processor.decode(logits) + + decoded_decoder = decoder.decode_beams(logits)[0] + + self.assertEqual(decoded_decoder[0], decoded_processor.text) + self.assertEqual(" ", decoded_processor.text) + self.assertEqual(decoded_decoder[-2], decoded_processor.logit_score) + self.assertEqual(decoded_decoder[-1], decoded_processor.lm_score) + + @parameterized.expand([[None], ["fork"], ["spawn"]]) + def test_decoder_batch(self, pool_context): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + decoder = self.get_decoder() + + processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) + + logits = self._get_dummy_logits() + + # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. + # otherwise, the LM won't be available to the pool's sub-processes. + # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) + if pool_context is None: + decoded_processor = processor.batch_decode(logits) + else: + with get_context(pool_context).Pool() as pool: + decoded_processor = processor.batch_decode(logits, pool) + + logits_list = list(logits) + + with get_context("fork").Pool() as p: + decoded_beams = decoder.decode_beams_batch(p, logits_list) + + texts_decoder, logit_scores_decoder, lm_scores_decoder = [], [], [] + for beams in decoded_beams: + texts_decoder.append(beams[0][0]) + logit_scores_decoder.append(beams[0][-2]) + lm_scores_decoder.append(beams[0][-1]) + + self.assertListEqual(texts_decoder, decoded_processor.text) + self.assertListEqual([" ", " "], decoded_processor.text) + self.assertListEqual(logit_scores_decoder, decoded_processor.logit_score) + self.assertListEqual(lm_scores_decoder, decoded_processor.lm_score) + + def test_decoder_with_params(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + decoder = self.get_decoder() + + processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) + + logits = self._get_dummy_logits() + + beam_width = 15 + beam_prune_logp = -20.0 + token_min_logp = -4.0 + + decoded_processor_out = processor.batch_decode( + logits, + beam_width=beam_width, + beam_prune_logp=beam_prune_logp, + token_min_logp=token_min_logp, + ) + decoded_processor = decoded_processor_out.text + + logits_list = list(logits) + + with get_context("fork").Pool() as pool: + decoded_decoder_out = decoder.decode_beams_batch( + pool, + logits_list, + beam_width=beam_width, + beam_prune_logp=beam_prune_logp, + token_min_logp=token_min_logp, + ) + + decoded_decoder = [d[0][0] for d in decoded_decoder_out] + logit_scores = [d[0][2] for d in decoded_decoder_out] + lm_scores = [d[0][3] for d in decoded_decoder_out] + + self.assertListEqual(decoded_decoder, decoded_processor) + self.assertListEqual([" ", " "], decoded_processor) + + self.assertTrue(np.array_equal(logit_scores, decoded_processor_out.logit_score)) + self.assertTrue(np.allclose([-20.054, -18.447], logit_scores, atol=1e-3)) + + self.assertTrue(np.array_equal(lm_scores, decoded_processor_out.lm_score)) + self.assertTrue(np.allclose([-15.554, -13.9474], lm_scores, atol=1e-3)) + + def test_decoder_with_params_of_lm(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + decoder = self.get_decoder() + + processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) + + logits = self._get_dummy_logits() + + alpha = 2.0 + beta = 5.0 + unk_score_offset = -20.0 + lm_score_boundary = True + + decoded_processor_out = processor.batch_decode( + logits, + alpha=alpha, + beta=beta, + unk_score_offset=unk_score_offset, + lm_score_boundary=lm_score_boundary, + ) + decoded_processor = decoded_processor_out.text + + logits_list = list(logits) + decoder.reset_params( + alpha=alpha, + beta=beta, + unk_score_offset=unk_score_offset, + lm_score_boundary=lm_score_boundary, + ) + + with get_context("fork").Pool() as pool: + decoded_decoder_out = decoder.decode_beams_batch( + pool, + logits_list, + ) + + decoded_decoder = [d[0][0] for d in decoded_decoder_out] + + self.assertListEqual(decoded_decoder, decoded_processor) + self.assertListEqual([" ", " "], decoded_processor) + lm_model = processor.decoder.model_container[processor.decoder._model_key] + self.assertEqual(lm_model.alpha, 2.0) + self.assertEqual(lm_model.beta, 5.0) + self.assertEqual(lm_model.unk_score_offset, -20.0) + self.assertEqual(lm_model.score_boundary, True) + + def test_decoder_download_ignores_files(self): + processor = Wav2Vec2ProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm") + + language_model = processor.decoder.model_container[processor.decoder._model_key] + path_to_cached_dir = Path(language_model._kenlm_model.path.decode("utf-8")).parent.parent.absolute() + + downloaded_decoder_files = os.listdir(path_to_cached_dir) + expected_decoder_files = ["alphabet.json", "language_model"] + + downloaded_decoder_files.sort() + expected_decoder_files.sort() + + # test that only decoder relevant files from + # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main + # are downloaded and none of the rest (e.g. README.md, ...) + self.assertListEqual(downloaded_decoder_files, expected_decoder_files) + + def test_decoder_local_files(self): + local_dir = snapshot_download("hf-internal-testing/processor_with_lm") + + processor = Wav2Vec2ProcessorWithLM.from_pretrained(local_dir) + + language_model = processor.decoder.model_container[processor.decoder._model_key] + path_to_cached_dir = Path(language_model._kenlm_model.path.decode("utf-8")).parent.parent.absolute() + + local_decoder_files = os.listdir(local_dir) + expected_decoder_files = os.listdir(path_to_cached_dir) + + local_decoder_files.sort() + expected_decoder_files.sort() + + # test that both decoder form hub and local files in cache are the same + self.assertListEqual(local_decoder_files, expected_decoder_files) + + def test_processor_from_auto_processor(self): + processor_wav2vec2 = Wav2Vec2ProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm") + processor_auto = AutoProcessor.from_pretrained("hf-internal-testing/processor_with_lm") + + raw_speech = floats_list((3, 1000)) + + input_wav2vec2 = processor_wav2vec2(raw_speech, return_tensors="np") + input_auto = processor_auto(raw_speech, return_tensors="np") + + for key in input_wav2vec2.keys(): + self.assertAlmostEqual(input_wav2vec2[key].sum(), input_auto[key].sum(), delta=1e-2) + + logits = self._get_dummy_logits() + + decoded_wav2vec2 = processor_wav2vec2.batch_decode(logits) + decoded_auto = processor_auto.batch_decode(logits) + + self.assertListEqual(decoded_wav2vec2.text, decoded_auto.text) + + def test_model_input_names(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + decoder = self.get_decoder() + + processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) + + self.assertListEqual( + processor.model_input_names, + feature_extractor.model_input_names, + msg="`processor` and `feature_extractor` model input names do not match", + ) + + @staticmethod + def get_from_offsets(offsets, key): + retrieved_list = [d[key] for d in offsets] + return retrieved_list + + def test_offsets_integration_fast(self): + processor = Wav2Vec2ProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm") + logits = self._get_dummy_logits()[0] + + outputs = processor.decode(logits, output_word_offsets=True) + # check Wav2Vec2CTCTokenizerOutput keys for word + self.assertEqual(len(outputs.keys()), 4) + self.assertTrue("text" in outputs) + self.assertTrue("word_offsets" in outputs) + self.assertTrue(isinstance(outputs, Wav2Vec2DecoderWithLMOutput)) + + self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"], "word")), outputs.text) + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "word"), ["", "", ""]) + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "start_offset"), [0, 2, 4]) + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "end_offset"), [1, 3, 5]) + + def test_offsets_integration_fast_batch(self): + processor = Wav2Vec2ProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm") + logits = self._get_dummy_logits() + + outputs = processor.batch_decode(logits, output_word_offsets=True) + + # check Wav2Vec2CTCTokenizerOutput keys for word + self.assertEqual(len(outputs.keys()), 4) + self.assertTrue("text" in outputs) + self.assertTrue("word_offsets" in outputs) + self.assertTrue(isinstance(outputs, Wav2Vec2DecoderWithLMOutput)) + + self.assertListEqual( + [" ".join(self.get_from_offsets(o, "word")) for o in outputs["word_offsets"]], outputs.text + ) + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0], "word"), ["", "", ""]) + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0], "start_offset"), [0, 2, 4]) + self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0], "end_offset"), [1, 3, 5]) + + @slow + @require_torch + @require_torchaudio + def test_word_time_stamp_integration(self): + import torch + + ds = load_dataset("mozilla-foundation/common_voice_11_0", "en", split="train", streaming=True) + ds = ds.cast_column("audio", datasets.Audio(sampling_rate=16_000)) + ds_iter = iter(ds) + sample = next(ds_iter) + + processor = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm") + model = Wav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm") + + input_values = processor(sample["audio"]["array"], return_tensors="pt").input_values + + with torch.no_grad(): + logits = model(input_values).logits.cpu().numpy() + + output = processor.decode(logits[0], output_word_offsets=True) + + time_offset = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate + word_time_stamps = [ + { + "start_time": d["start_offset"] * time_offset, + "end_time": d["end_offset"] * time_offset, + "word": d["word"], + } + for d in output["word_offsets"] + ] + + EXPECTED_TEXT = "WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL" + EXPECTED_TEXT = "THE TRACK APPEARS ON THE COMPILATION ALBUM CRAFT FORKS" + + # output words + self.assertEqual(" ".join(self.get_from_offsets(word_time_stamps, "word")), EXPECTED_TEXT) + self.assertEqual(" ".join(self.get_from_offsets(word_time_stamps, "word")), output.text) + + # output times + start_times = torch.tensor(self.get_from_offsets(word_time_stamps, "start_time")) + end_times = torch.tensor(self.get_from_offsets(word_time_stamps, "end_time")) + + # fmt: off + expected_start_tensor = torch.tensor([0.6800, 0.8800, 1.1800, 1.8600, 1.9600, 2.1000, 3.0000, 3.5600, 3.9800]) + expected_end_tensor = torch.tensor([0.7800, 1.1000, 1.6600, 1.9200, 2.0400, 2.8000, 3.3000, 3.8800, 4.2800]) + # fmt: on + + self.assertTrue(torch.allclose(start_times, expected_start_tensor, atol=0.01)) + self.assertTrue(torch.allclose(end_times, expected_end_tensor, atol=0.01)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wavlm/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wavlm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wavlm/test_modeling_wavlm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wavlm/test_modeling_wavlm.py new file mode 100644 index 0000000000000000000000000000000000000000..6db04e1841f16abde93dab02cbdd13277ef26f75 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/wavlm/test_modeling_wavlm.py @@ -0,0 +1,596 @@ +# coding=utf-8 +# 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 WavLM model. """ + +import math +import unittest + +import pytest +from datasets import load_dataset + +from transformers import WavLMConfig, is_torch_available +from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + Wav2Vec2FeatureExtractor, + WavLMForAudioFrameClassification, + WavLMForCTC, + WavLMForSequenceClassification, + WavLMForXVector, + WavLMModel, + ) + + +class WavLMModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=1024, # speech is longer + is_training=False, + hidden_size=16, + feat_extract_norm="group", + feat_extract_dropout=0.0, + feat_extract_activation="gelu", + conv_dim=(32, 32, 32), + conv_stride=(4, 4, 4), + conv_kernel=(8, 8, 8), + conv_bias=False, + num_conv_pos_embeddings=16, + num_conv_pos_embedding_groups=2, + num_hidden_layers=2, + num_attention_heads=2, + hidden_dropout_prob=0.1, # this is most likely not correctly set yet + intermediate_size=20, + layer_norm_eps=1e-5, + hidden_act="gelu", + initializer_range=0.02, + vocab_size=32, + do_stable_layer_norm=False, + tdnn_dim=(32, 32), + tdnn_kernel=(3, 3), + tdnn_dilation=(1, 1), + xvector_output_dim=32, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.hidden_size = hidden_size + self.feat_extract_norm = feat_extract_norm + self.feat_extract_dropout = feat_extract_dropout + self.feat_extract_activation = feat_extract_activation + self.conv_dim = conv_dim + self.conv_stride = conv_stride + self.conv_kernel = conv_kernel + self.conv_bias = conv_bias + self.num_conv_pos_embeddings = num_conv_pos_embeddings + self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout_prob = hidden_dropout_prob + self.intermediate_size = intermediate_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.vocab_size = vocab_size + self.do_stable_layer_norm = do_stable_layer_norm + self.tdnn_dim = tdnn_dim + self.tdnn_kernel = tdnn_kernel + self.tdnn_dilation = tdnn_dilation + self.xvector_output_dim = xvector_output_dim + self.scope = scope + + output_seq_length = self.seq_length + for kernel, stride in zip(self.conv_kernel, self.conv_stride): + output_seq_length = (output_seq_length - (kernel - 1)) / stride + self.output_seq_length = int(math.ceil(output_seq_length)) + self.encoder_seq_length = self.output_seq_length + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) + attention_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + + return config, input_values, attention_mask + + def get_config(self): + return WavLMConfig( + hidden_size=self.hidden_size, + feat_extract_norm=self.feat_extract_norm, + feat_extract_dropout=self.feat_extract_dropout, + feat_extract_activation=self.feat_extract_activation, + conv_dim=self.conv_dim, + conv_stride=self.conv_stride, + conv_kernel=self.conv_kernel, + conv_bias=self.conv_bias, + num_conv_pos_embeddings=self.num_conv_pos_embeddings, + num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + hidden_dropout_prob=self.hidden_dropout_prob, + intermediate_size=self.intermediate_size, + layer_norm_eps=self.layer_norm_eps, + hidden_act=self.hidden_act, + initializer_range=self.initializer_range, + vocab_size=self.vocab_size, + tdnn_dim=self.tdnn_dim, + tdnn_kernel=self.tdnn_kernel, + tdnn_dilation=self.tdnn_dilation, + xvector_output_dim=self.xvector_output_dim, + ) + + def create_and_check_model(self, config, input_values, attention_mask): + model = WavLMModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_values, attention_mask=attention_mask) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) + ) + + def create_and_check_batch_inference(self, config, input_values, *args): + # test does not pass for models making use of `group_norm` + # check: https://github.com/pytorch/fairseq/issues/3227 + model = WavLMModel(config=config) + model.to(torch_device) + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0.0 + + batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state + + for i in range(input_values.shape[0]): + input_slice = input_values[i : i + 1, : input_lengths[i]] + output = model(input_slice).last_hidden_state + + batch_output = batch_outputs[i : i + 1, : output.shape[1]] + self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) + + def check_ctc_loss(self, config, input_values, *args): + model = WavLMForCTC(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + model.config.ctc_loss_reduction = "sum" + sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + model.config.ctc_loss_reduction = "mean" + mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(sum_loss, float)) + self.parent.assertTrue(isinstance(mean_loss, float)) + + def check_seq_classifier_loss(self, config, input_values, *args): + model = WavLMForSequenceClassification(config=config) + model.to(torch_device) + + # make sure that dropout is disabled + model.eval() + + input_values = input_values[:3] + attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + attention_mask[i, input_lengths[i] :] = 0 + + masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() + unmasked_loss = model(input_values, labels=labels).loss.item() + + self.parent.assertTrue(isinstance(masked_loss, float)) + self.parent.assertTrue(isinstance(unmasked_loss, float)) + self.parent.assertTrue(masked_loss != unmasked_loss) + + def check_ctc_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = WavLMForCTC(config=config) + model.to(torch_device) + model.train() + + # freeze feature encoder + model.freeze_feature_encoder() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + if max_length_labels[i] < labels.shape[-1]: + # it's important that we make sure that target lengths are at least + # one shorter than logit lengths to prevent -inf + labels[i, max_length_labels[i] - 1 :] = -100 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_seq_classifier_training(self, config, input_values, *args): + config.ctc_zero_infinity = True + model = WavLMForSequenceClassification(config=config) + model.to(torch_device) + model.train() + + # freeze everything but the classification head + model.freeze_base_model() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) + + # pad input + for i in range(len(input_lengths)): + input_values[i, input_lengths[i] :] = 0.0 + + loss = model(input_values, labels=labels).loss + self.parent.assertFalse(torch.isinf(loss).item()) + + loss.backward() + + def check_labels_out_of_vocab(self, config, input_values, *args): + model = WavLMForCTC(config) + model.to(torch_device) + model.train() + + input_values = input_values[:3] + + input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] + max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) + labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) + + with pytest.raises(ValueError): + model(input_values, labels=labels) + + def prepare_config_and_inputs_for_common(self): + config, input_values, attention_mask = self.prepare_config_and_inputs() + inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} + return config, inputs_dict + + +@require_torch +class WavLMModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (WavLMForCTC, WavLMModel, WavLMForAudioFrameClassification, WavLMForSequenceClassification, WavLMForXVector) + if is_torch_available() + else () + ) + pipeline_model_mapping = ( + { + "audio-classification": WavLMForSequenceClassification, + "automatic-speech-recognition": WavLMForCTC, + "feature-extraction": WavLMModel, + } + if is_torch_available() + else {} + ) + test_pruning = False + test_headmasking = False + + def setUp(self): + self.model_tester = WavLMModelTester(self) + self.config_tester = ConfigTester(self, config_class=WavLMConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_ctc_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_loss(*config_and_inputs) + + def test_seq_classifier_loss_inference(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_loss(*config_and_inputs) + + def test_ctc_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_ctc_training(*config_and_inputs) + + def test_seq_classifier_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_seq_classifier_training(*config_and_inputs) + + def test_labels_out_of_vocab(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_labels_out_of_vocab(*config_and_inputs) + + # WavLM has no inputs_embeds + def test_inputs_embeds(self): + pass + + # `input_ids` is renamed to `input_values` + def test_forward_signature(self): + pass + + # WavLM cannot resize token embeddings + # since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # WavLM has no inputs_embeds + # and thus the `get_input_embeddings` fn + # is not implemented + def test_model_common_attributes(self): + pass + + # WavLM uses PyTorch's multi-head-attention class + # and thus can't retain gradients on attentions + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + # set layer drop to 0 + model.config.layerdrop = 0.0 + + input_values = inputs_dict["input_values"] + + input_lengths = torch.tensor( + [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device + ) + output_lengths = model._get_feat_extract_output_lengths(input_lengths) + + labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) + inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) + inputs_dict["labels"] = labels + + outputs = model(**inputs_dict) + + output = outputs[0] + + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + hidden_states.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + uniform_init_parms = [ + "conv.weight", + "conv.parametrizations.weight", + "masked_spec_embed", + "codevectors", + "quantizer.weight_proj.weight", + "project_hid.weight", + "project_hid.bias", + "project_q.weight", + "project_q.bias", + "feature_projection.projection.weight", + "feature_projection.projection.bias", + "label_embeddings_concat", + "rel_attn_embed", + "objective.weight", + ] + if param.requires_grad: + if any(x in name for x in uniform_init_parms): + self.assertTrue( + -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "weight_g") and module.weight_g is not None: + module.weight_g.data.fill_(3) + if hasattr(module, "weight_v") and module.weight_v is not None: + module.weight_v.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + if hasattr(module, "codevectors") and module.codevectors is not None: + module.codevectors.data.fill_(3) + if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: + module.masked_spec_embed.data.fill_(3) + + @unittest.skip(reason="Feed forward chunking is not implemented for WavLM") + def test_feed_forward_chunking(self): + pass + + @slow + def test_model_from_pretrained(self): + model = WavLMModel.from_pretrained("microsoft/wavlm-base-plus") + self.assertIsNotNone(model) + + +@require_torch +@require_torchaudio +@slow +class WavLMModelIntegrationTest(unittest.TestCase): + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").filter( + lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] + )[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def _load_superb(self, task, num_samples): + ds = load_dataset("anton-l/superb_dummy", task, split="test") + + return ds[:num_samples] + + def test_inference_base(self): + model = WavLMModel.from_pretrained("microsoft/wavlm-base-plus").to(torch_device) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( + "microsoft/wavlm-base-plus", return_attention_mask=True + ) + + input_speech = self._load_datasamples(2) + + inputs = feature_extractor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + + with torch.no_grad(): + hidden_states_slice = ( + model(input_values, attention_mask=attention_mask).last_hidden_state[:, -2:, -2:].cpu() + ) + + EXPECTED_HIDDEN_STATES_SLICE = torch.tensor( + [[[0.0577, 0.1161], [0.0579, 0.1165]], [[0.0199, 0.1237], [0.0059, 0.0605]]] + ) + # TODO: update the tolerance after the CI moves to torch 1.10 + self.assertTrue(torch.allclose(hidden_states_slice, EXPECTED_HIDDEN_STATES_SLICE, atol=5e-2)) + + def test_inference_large(self): + model = WavLMModel.from_pretrained("microsoft/wavlm-large").to(torch_device) + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( + "microsoft/wavlm-large", return_attention_mask=True + ) + + input_speech = self._load_datasamples(2) + + inputs = feature_extractor(input_speech, return_tensors="pt", padding=True) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + + with torch.no_grad(): + hidden_states_slice = ( + model(input_values, attention_mask=attention_mask).last_hidden_state[:, -2:, -2:].cpu() + ) + + EXPECTED_HIDDEN_STATES_SLICE = torch.tensor( + [[[0.2122, 0.0500], [0.2118, 0.0563]], [[0.1353, 0.1818], [0.2453, 0.0595]]] + ) + + self.assertTrue(torch.allclose(hidden_states_slice, EXPECTED_HIDDEN_STATES_SLICE, rtol=5e-2)) + + def test_inference_diarization(self): + model = WavLMForAudioFrameClassification.from_pretrained("microsoft/wavlm-base-plus-sd").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sd") + input_data = self._load_superb("sd", 4) + inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000) + + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + with torch.no_grad(): + outputs = model(input_values, attention_mask=attention_mask) + # labels is a one-hot array of shape (num_frames, num_speakers) + labels = (outputs.logits > 0).long() + + # s3prl logits for the same batch + expected_logits = torch.tensor( + [ + [[-5.9566, -8.6554], [-5.7137, -8.9386], [-5.7906, -7.0973], [-5.7829, -5.9999]], + [[-5.2086, -7.7878], [-4.8890, -7.9312], [-4.2004, -3.9101], [-5.4480, -4.6932]], + [[-4.6105, -6.7178], [-5.1930, -6.1635], [-2.6228, -4.1123], [-2.7646, -3.1576]], + [[-4.4477, -7.9206], [-3.9339, -7.3707], [-4.9528, -4.8242], [-3.6921, -2.9687]], + ], + device=torch_device, + ) + self.assertEqual(labels[0, :, 0].sum(), 258) + self.assertEqual(labels[0, :, 1].sum(), 647) + # TODO: update the tolerance after the CI moves to torch 1.10 + self.assertTrue(torch.allclose(outputs.logits[:, :4], expected_logits, atol=1e-2)) + + def test_inference_speaker_verification(self): + model = WavLMForXVector.from_pretrained("microsoft/wavlm-base-plus-sv").to(torch_device) + processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sv") + input_data = self._load_superb("si", 4) + + inputs = processor(input_data["speech"], return_tensors="pt", padding=True) + labels = torch.tensor([5, 1, 1, 3], device=torch_device).T + + with torch.no_grad(): + input_values = inputs.input_values.to(torch_device) + attention_mask = inputs.attention_mask.to(torch_device) + outputs = model(input_values, attention_mask=attention_mask, labels=labels) + embeddings = torch.nn.functional.normalize(outputs.embeddings, dim=-1) + + cosine_sim = torch.nn.CosineSimilarity(dim=-1) + # id10002 vs id10002 + self.assertAlmostEqual(cosine_sim(embeddings[1], embeddings[2]).item(), 0.9787, 3) + # id10006 vs id10002 + self.assertAlmostEqual(cosine_sim(embeddings[0], embeddings[1]).item(), 0.5064, 3) + # id10002 vs id10004 + self.assertAlmostEqual(cosine_sim(embeddings[2], embeddings[3]).item(), 0.4780, 3) + + # TODO: update the tolerance after the CI moves to torch 1.10 + self.assertAlmostEqual(outputs.loss.item(), 18.4154, 2) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_feature_extraction_whisper.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_feature_extraction_whisper.py new file mode 100644 index 0000000000000000000000000000000000000000..90cbfc21c04f3594ab60c582e3a9ae1931488267 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_feature_extraction_whisper.py @@ -0,0 +1,241 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. +# +# 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 itertools +import os +import random +import tempfile +import unittest + +import numpy as np +from datasets import load_dataset + +from transformers import is_speech_available +from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio +from transformers.utils.import_utils import is_torch_available + +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +if is_speech_available(): + from transformers import WhisperFeatureExtractor + +if is_torch_available(): + import torch + +global_rng = random.Random() + + +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +@require_torch +@require_torchaudio +class WhisperFeatureExtractionTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + min_seq_length=400, + max_seq_length=2000, + feature_size=10, + hop_length=160, + chunk_length=8, + padding_value=0.0, + sampling_rate=4_000, + return_attention_mask=False, + do_normalize=True, + ): + self.parent = parent + self.batch_size = batch_size + self.min_seq_length = min_seq_length + self.max_seq_length = max_seq_length + self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) + self.padding_value = padding_value + self.sampling_rate = sampling_rate + self.return_attention_mask = return_attention_mask + self.do_normalize = do_normalize + self.feature_size = feature_size + self.chunk_length = chunk_length + self.hop_length = hop_length + + def prepare_feat_extract_dict(self): + return { + "feature_size": self.feature_size, + "hop_length": self.hop_length, + "chunk_length": self.chunk_length, + "padding_value": self.padding_value, + "sampling_rate": self.sampling_rate, + "return_attention_mask": self.return_attention_mask, + "do_normalize": self.do_normalize, + } + + def prepare_inputs_for_common(self, equal_length=False, numpify=False): + def _flatten(list_of_lists): + return list(itertools.chain(*list_of_lists)) + + if equal_length: + speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] + else: + # make sure that inputs increase in size + speech_inputs = [ + floats_list((x, self.feature_size)) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + return speech_inputs + + +@require_torch +@require_torchaudio +class WhisperFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = WhisperFeatureExtractor if is_speech_available() else None + + def setUp(self): + self.feat_extract_tester = WhisperFeatureExtractionTester(self) + + def test_feat_extract_from_and_save_pretrained(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = feat_extract_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + mel_1 = feat_extract_first.mel_filters + mel_2 = feat_extract_second.mel_filters + self.assertTrue(np.allclose(mel_1, mel_2)) + self.assertEqual(dict_first, dict_second) + + def test_feat_extract_to_json_file(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "feat_extract.json") + feat_extract_first.to_json_file(json_file_path) + feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path) + + dict_first = feat_extract_first.to_dict() + dict_second = feat_extract_second.to_dict() + mel_1 = feat_extract_first.mel_filters + mel_2 = feat_extract_second.mel_filters + self.assertTrue(np.allclose(mel_1, mel_2)) + self.assertEqual(dict_first, dict_second) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + # create three inputs of length 800, 1000, and 1200 + speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + # Test feature size + input_features = feature_extractor(np_speech_inputs, padding="max_length", return_tensors="np").input_features + self.assertTrue(input_features.ndim == 3) + self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames) + self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size) + + # Test not batched input + encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_features + self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) + + # Test batched + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test 2-D numpy arrays are batched. + speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] + np_speech_inputs = np.asarray(speech_inputs) + encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + # Test truncation required + speech_inputs = [floats_list((1, x))[0] for x in range(200, (feature_extractor.n_samples + 500), 200)] + np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] + + speech_inputs_truncated = [x[: feature_extractor.n_samples] for x in speech_inputs] + np_speech_inputs_truncated = [np.asarray(speech_input) for speech_input in speech_inputs_truncated] + + encoded_sequences_1 = feature_extractor(np_speech_inputs, return_tensors="np").input_features + encoded_sequences_2 = feature_extractor(np_speech_inputs_truncated, return_tensors="np").input_features + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) + + def test_double_precision_pad(self): + import torch + + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + np_speech_inputs = np.random.rand(100, 32).astype(np.float64) + py_speech_inputs = np_speech_inputs.tolist() + + for inputs in [py_speech_inputs, np_speech_inputs]: + np_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="np") + self.assertTrue(np_processed.input_features.dtype == np.float32) + pt_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="pt") + self.assertTrue(pt_processed.input_features.dtype == torch.float32) + + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_integration(self): + # fmt: off + EXPECTED_INPUT_FEATURES = torch.tensor( + [ + 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, + 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, + 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, + -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 + ] + ) + # fmt: on + + input_speech = self._load_datasamples(1) + feature_extractor = WhisperFeatureExtractor() + input_features = feature_extractor(input_speech, return_tensors="pt").input_features + self.assertEqual(input_features.shape, (1, 80, 3000)) + self.assertTrue(torch.allclose(input_features[0, 0, :30], EXPECTED_INPUT_FEATURES, atol=1e-4)) + + def test_zero_mean_unit_variance_normalization_trunc_np_longest(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + audio = self._load_datasamples(1)[0] + audio = ((audio - audio.min()) / (audio.max() - audio.min())) * 65535 # Rescale to [0, 65535] to show issue + audio = feat_extract.zero_mean_unit_var_norm([audio], attention_mask=None)[0] + + self.assertTrue(np.all(np.mean(audio) < 1e-3)) + self.assertTrue(np.all(np.abs(np.var(audio) - 1) < 1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_flax_whisper.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_flax_whisper.py new file mode 100644 index 0000000000000000000000000000000000000000..d0616637692925722233c709f6cf3500a6989c47 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_flax_whisper.py @@ -0,0 +1,923 @@ +# coding=utf-8 +# Copyright 2022 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 functools +import inspect +import tempfile +import unittest + +import transformers +from transformers import WhisperConfig, is_flax_available +from transformers.testing_utils import is_pt_flax_cross_test, require_flax, slow +from transformers.utils import cached_property +from transformers.utils.import_utils import is_datasets_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor + + +if is_datasets_available(): + import datasets + from datasets import load_dataset + +if is_flax_available(): + import jax + import numpy as np + from flax.core.frozen_dict import unfreeze + from flax.traverse_util import flatten_dict + + from transformers import ( + FLAX_MODEL_MAPPING, + FlaxWhisperForAudioClassification, + FlaxWhisperForConditionalGeneration, + FlaxWhisperModel, + WhisperFeatureExtractor, + WhisperProcessor, + ) + from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model + from transformers.models.whisper.modeling_flax_whisper import sinusoidal_embedding_init + + +@require_flax +class FlaxWhisperModelTester: + config_cls = WhisperConfig + config_updates = {} + hidden_act = "gelu" + + def __init__( + self, + parent, + batch_size=13, + seq_length=60, + is_training=True, + use_labels=False, + vocab_size=99, + d_model=16, + decoder_attention_heads=4, + decoder_ffn_dim=16, + decoder_layers=2, + encoder_attention_heads=4, + encoder_ffn_dim=16, + encoder_layers=2, + input_channels=1, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=70, + max_source_positions=30, + max_target_positions=40, + bos_token_id=98, + eos_token_id=98, + pad_token_id=0, + num_mel_bins=80, + decoder_start_token_id=85, + num_conv_layers=1, + suppress_tokens=None, + begin_suppress_tokens=None, + ): + 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.d_model = d_model + self.hidden_size = d_model + self.num_hidden_layers = encoder_layers + self.num_attention_heads = encoder_attention_heads + self.decoder_attention_heads = decoder_attention_heads + self.decoder_ffn_dim = decoder_ffn_dim + self.decoder_layers = decoder_layers + self.encoder_attention_heads = encoder_attention_heads + self.encoder_ffn_dim = encoder_ffn_dim + self.encoder_layers = encoder_layers + self.encoder_seq_length = seq_length // 2 + self.decoder_seq_length = 1 + self.input_channels = input_channels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.num_mel_bins = num_mel_bins + self.max_position_embeddings = max_position_embeddings + self.max_source_positions = max_source_positions + self.max_target_positions = max_target_positions + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.bos_token_id = bos_token_id + self.decoder_start_token_id = decoder_start_token_id + self.num_conv_layers = num_conv_layers + self.suppress_tokens = suppress_tokens + self.begin_suppress_tokens = begin_suppress_tokens + + def prepare_config_and_inputs_for_common(self): + input_features = floats_tensor([self.batch_size, self.num_mel_bins, self.seq_length], self.vocab_size) + + decoder_input_ids = np.array(self.batch_size * [[self.decoder_start_token_id]]) + + config = WhisperConfig( + vocab_size=self.vocab_size, + num_mel_bins=self.num_mel_bins, + decoder_start_token_id=self.decoder_start_token_id, + is_encoder_decoder=True, + activation_function=self.hidden_act, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_source_positions=self.max_source_positions, + max_target_positions=self.max_target_positions, + pad_token_id=self.pad_token_id, + bos_token_id=self.bos_token_id, + eos_token_id=self.eos_token_id, + tie_word_embeddings=True, + d_model=self.d_model, + decoder_attention_heads=self.decoder_attention_heads, + decoder_ffn_dim=self.decoder_ffn_dim, + decoder_layers=self.decoder_layers, + encoder_attention_heads=self.encoder_attention_heads, + encoder_ffn_dim=self.encoder_ffn_dim, + encoder_layers=self.encoder_layers, + suppress_tokens=self.suppress_tokens, + begin_suppress_tokens=self.begin_suppress_tokens, + ) + inputs_dict = prepare_whisper_inputs_dict(config, input_features, decoder_input_ids) + return config, inputs_dict + + +def prepare_whisper_inputs_dict( + config, + input_ids, + decoder_input_ids, + attention_mask=None, + decoder_attention_mask=None, +): + if decoder_attention_mask is None: + decoder_attention_mask = np.concatenate( + [ + np.ones(decoder_input_ids[:, :1].shape, dtype=np.int8), + np.not_equal(decoder_input_ids[:, 1:], config.pad_token_id).astype(np.int8), + ], + axis=-1, + ) + return { + "input_features": input_ids, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + + +def partialclass(cls, *args, **kwargs): + class NewCls(cls): + __init__ = functools.partialmethod(cls.__init__, *args, **kwargs) + + return NewCls + + +def make_partial_class(full_class, *args, **kwargs): + partial_class = partialclass(full_class, *args, **kwargs) + partial_class.__name__ = full_class.__name__ + partial_class.__module__ = full_class.__module__ + + return partial_class + + +@require_flax +class FlaxWhisperModelTest(FlaxModelTesterMixin, unittest.TestCase): + all_model_classes = (FlaxWhisperForConditionalGeneration, FlaxWhisperModel) if is_flax_available() else () + all_generative_model_classes = (FlaxWhisperForConditionalGeneration,) if is_flax_available() else () + is_encoder_decoder = True + test_pruning = False + test_head_masking = False + test_onnx = False + + def setUp(self): + self.model_tester = FlaxWhisperModelTester(self) + _, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + self.init_shape = (1,) + inputs_dict["input_features"].shape[1:] + + self.all_model_classes = ( + make_partial_class(model_class, input_shape=self.init_shape) for model_class in self.all_model_classes + ) + self.config_tester = ConfigTester(self, config_class=WhisperConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + # overwrite because of `input_features` + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.__call__) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["input_features", "decoder_input_ids"] + self.assertListEqual(arg_names[:2], expected_arg_names) + + # overwrite because of `input_features` + def test_jit_compilation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def model_jitted(input_features, decoder_input_ids, **kwargs): + return model(input_features=input_features, decoder_input_ids=decoder_input_ids, **kwargs) + + with self.subTest("JIT Enabled"): + jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + def check_pt_flax_outputs(self, fx_outputs, pt_outputs, model_class, tol=5e-5, name="outputs", attributes=None): + # We override with a slightly higher tol value, as test recently became flaky + super().check_pt_flax_outputs(fx_outputs, pt_outputs, model_class, tol, name, attributes) + + # overwrite because of `input_features` + @is_pt_flax_cross_test + def test_save_load_bf16_to_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = make_partial_class(FLAX_MODEL_MAPPING[config.__class__], input_shape=self.init_shape) + + for model_class in self.all_model_classes: + if model_class.__name__ == base_class.__name__: + continue + + model = model_class(config) + model.params = model.to_bf16(model.params) + base_params_from_head = flatten_dict(unfreeze(model.params[model.base_model_prefix])) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname, from_pt=True) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite because of `input_features` + @is_pt_flax_cross_test + def test_save_load_from_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = make_partial_class(FLAX_MODEL_MAPPING[config.__class__], input_shape=self.init_shape) + + for model_class in self.all_model_classes: + if model_class.__name__ == base_class.__name__: + continue + + model = base_class(config) + base_params = flatten_dict(unfreeze(model.params)) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, base_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + # save pt model + pt_model.save_pretrained(tmpdirname) + head_model = model_class.from_pretrained(tmpdirname, from_pt=True) + + base_param_from_head = flatten_dict(unfreeze(head_model.params[head_model.base_model_prefix])) + + for key in base_param_from_head.keys(): + max_diff = (base_params[key] - base_param_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite because of `input_features` + @is_pt_flax_cross_test + def test_save_load_to_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = make_partial_class(FLAX_MODEL_MAPPING[config.__class__], input_shape=self.init_shape) + + for model_class in self.all_model_classes: + if model_class.__name__ == base_class.__name__: + continue + + model = model_class(config) + base_params_from_head = flatten_dict(unfreeze(model.params[model.base_model_prefix])) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname, from_pt=True) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite because of `input_features` + def test_save_load_from_base(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = make_partial_class(FLAX_MODEL_MAPPING[config.__class__], input_shape=self.init_shape) + + for model_class in self.all_model_classes: + if model_class.__name__ == base_class.__name__: + continue + + model = base_class(config) + base_params = flatten_dict(unfreeze(model.params)) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + head_model = model_class.from_pretrained(tmpdirname) + + base_param_from_head = flatten_dict(unfreeze(head_model.params[head_model.base_model_prefix])) + + for key in base_param_from_head.keys(): + max_diff = (base_params[key] - base_param_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # overwrite because of `input_features` + def test_save_load_to_base(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = make_partial_class(FLAX_MODEL_MAPPING[config.__class__], input_shape=self.init_shape) + + for model_class in self.all_model_classes: + if model_class.__name__ == base_class.__name__: + continue + + model = model_class(config) + base_params_from_head = flatten_dict(unfreeze(model.params[model.base_model_prefix])) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname) + + base_params = flatten_dict(unfreeze(base_model.params)) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + def test_encoder_sinusoidal_embed_positions(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + params = model.params + if model.base_model_prefix in params: + params = model.params[model.base_model_prefix] + + embeds = params["encoder"]["embed_positions"]["embedding"] + sinusoids = sinusoidal_embedding_init(None, embeds.shape) + self.assertTrue(jax.numpy.allclose(embeds, sinusoids)) + + +@slow +@require_flax +class FlaxWhisperModelIntegrationTest(unittest.TestCase): + @cached_property + def default_processor(self): + return WhisperProcessor.from_pretrained("openai/whisper-base") + + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + def test_tiny_logits_librispeech(self): + model = FlaxWhisperModel.from_pretrained("openai/whisper-tiny", from_pt=True) + input_speech = self._load_datasamples(1) + feature_extractor = WhisperFeatureExtractor() + input_features = feature_extractor(input_speech, return_tensors="np").input_features + + logits = model( + input_features, + decoder_input_ids=np.array([[50258, 50259, 50359]]), + output_hidden_states=False, + output_attentions=False, + return_dict=False, + ) + + # fmt: off + EXPECTED_LOGITS = np.array( + [ + 2.9892, -6.7607, 5.7348, 3.6096, 0.2152, -5.7321, 4.8855, -1.6407, + 0.2823, -1.5718, 10.4269, 3.4427, 0.0219, -8.0612, 3.4784, 8.4246, + 4.0575, -2.2864, 11.1084, 0.9963, 0.9884, -8.5154, -3.5469, -9.3713, + 0.9786, 3.5435, 7.4850, -5.2579, -1.4366, 10.4841 + ] + ) + # fmt: on + self.assertTrue(np.allclose(logits[0][0, 0, :30], EXPECTED_LOGITS, atol=1e-4)) + + def test_small_en_logits_librispeech(self): + model = FlaxWhisperModel.from_pretrained("openai/whisper-small.en", from_pt=True) + input_speech = self._load_datasamples(1) + feature_extractor = WhisperFeatureExtractor() + input_features = feature_extractor(input_speech, return_tensors="np").input_features + + logits = model( + input_features, + decoder_input_ids=np.array([model.config.decoder_start_token_id]), + output_hidden_states=False, + output_attentions=False, + return_dict=False, + ) + + logits = logits[0] @ model.params["model"]["decoder"]["embed_tokens"]["embedding"].T + + # fmt: off + EXPECTED_LOGITS = np.array( + [ + -3.6784, -7.7211, -9.5070, -11.9286, -7.6489, -9.7026, -5.6188, + -8.0104, -4.6238, -5.1833, -9.0485, -3.4079, -5.4874, -2.6935, + -6.3479, -7.3398, -6.9558, -7.6867, -7.4748, -8.3463, -9.9781, + -10.8389, -10.3105, -11.7201, -9.7261, -7.1590, -5.9272, -12.4509, + -11.1146, -8.1918 + ] + ) + # fmt: on + self.assertTrue(np.allclose(logits[0, 0, :30], EXPECTED_LOGITS, atol=1e-4)) + + def test_large_logits_librispeech(self): + model = FlaxWhisperModel.from_pretrained("openai/whisper-large", from_pt=True) + input_speech = self._load_datasamples(1) + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + processed_inputs = processor( + audio=input_speech, text="This part of the speech", add_special_tokens=False, return_tensors="np" + ) + input_features = processed_inputs.input_features + decoder_input_ids = processed_inputs.labels + + logits = model( + input_features, + decoder_input_ids=decoder_input_ids, + output_hidden_states=False, + output_attentions=False, + return_dict=False, + ) + + logits = logits[0] @ model.params["model"]["decoder"]["embed_tokens"]["embedding"].T + + # fmt: off + EXPECTED_LOGITS = np.array( + [ + 2.1382, 0.9381, 4.4671, 3.5589, 2.4022, 3.8576, -0.6521, 2.5472, + 1.8301, 1.9957, 2.3432, 1.4678, 0.5459, 2.2597, 1.5179, 2.5357, + 1.1624, 0.6194, 1.0757, 1.8259, 2.4076, 1.6601, 2.3503, 1.3376, + 1.9891, 1.8635, 3.8931, 5.3699, 4.4772, 3.9184 + ] + ) + # fmt: on + self.assertTrue(np.allclose(logits[0, 0, :30], EXPECTED_LOGITS, atol=1e-4)) + + def test_tiny_en_generation(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en", from_pt=True) + model.config.decoder_start_token_id = 50257 + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor( + raw_speech=input_speech, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="jax" + ).input_features + + generated_ids = model.generate(input_features, num_beams=5, max_length=20).sequences + transcript = processor.tokenizer.decode(generated_ids[0]) + + EXPECTED_TRANSCRIPT = ( + "<|startoftranscript|><|en|><|transcribe|><|notimestamps|> Mr. Quilter is the apostle of the middle" + " classes and we are glad to" + ) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + def test_tiny_generation(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny", from_pt=True) + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor( + raw_speech=input_speech, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="jax" + ).input_features + + generated_ids = model.generate(input_features, num_beams=5, max_length=20).sequences + transcript = processor.tokenizer.decode(generated_ids[0]) + + EXPECTED_TRANSCRIPT = ( + "<|startoftranscript|><|en|><|transcribe|><|notimestamps|> Mr. Quilter is the apostle of the middle" + " classes and we are glad" + ) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + def test_large_generation(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-large", from_pt=True) + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor( + raw_speech=input_speech, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="jax" + ).input_features + + model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe") + + generated_ids = model.generate(input_features, num_beams=5, max_length=20).sequences + transcript = processor.tokenizer.decode(generated_ids[0], skip_special_tokens=True) + + EXPECTED_TRANSCRIPT = " Mr. Quilter is the apostle of the middle classes and we are glad" + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + def test_large_generation_multilingual(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-large", from_pt=True) + + ds = load_dataset("common_voice", "ja", split="test", streaming=True) + ds = ds.cast_column("audio", datasets.Audio(sampling_rate=16_000)) + input_speech = next(iter(ds))["audio"]["array"] + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="np") + + model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(language="ja", task="transcribe") + generated_ids = model.generate(input_features, do_sample=False, max_length=20).sequences + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = "木村さんに電話を貸してもらいました" + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe") + generated_ids = model.generate( + input_features, + do_sample=False, + max_length=20, + ).sequences + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = " Kimura-san called me." + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(language="ja", task="translate") + generated_ids = model.generate(input_features, do_sample=False, max_length=20).sequences + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = " I borrowed a phone from Kimura san" + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + def test_large_batched_generation(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-large", from_pt=True) + + input_speech = self._load_datasamples(4) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="np").input_features + generated_ids = model.generate(input_features, max_length=20).sequences + + # fmt: off + EXPECTED_LOGITS = np.array( + [ + [50258, 50358, 50363, 2221, 13, 2326, 388, 391, 307, 264, 50244, 295, 264, 2808, 5359, 293, 321, 366, 5404, 281], + [50258, 50358, 50363, 6966, 307, 2221, 13, 2326, 388, 391, 311, 9060, 1570, 1880, 813, 702, 1871, 13, 50257, 50257], + [50258, 50358, 50363, 634, 5112, 505, 300, 412, 341, 42729, 3196, 295, 264, 1064, 11, 365, 5272, 293, 12904, 9256], + [50258, 50358, 50363, 634, 575, 12525, 22618, 1968, 6144, 35617, 20084, 1756, 311, 589, 307, 534, 10281, 934, 439, 11] + ] + ) + # fmt: on + + self.assertTrue(np.allclose(generated_ids, EXPECTED_LOGITS)) + + # fmt: off + EXPECTED_TRANSCRIPT = [ + " Mr. Quilter is the apostle of the middle classes and we are glad to", + " Nor is Mr. Quilter's manner less interesting than his matter.", + " He tells us that at this festive season of the year, with Christmas and roast beef", + " He has grave doubts whether Sir Frederick Layton's work is really Greek after all,", + ] + # fmt: on + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + self.assertListEqual(transcript, EXPECTED_TRANSCRIPT) + + def test_tiny_en_batched_generation(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en", from_pt=True) + + input_speech = self._load_datasamples(4) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="np").input_features + generated_ids = model.generate(input_features, max_length=20).sequences + + # fmt: off + EXPECTED_LOGITS = np.array( + [ + [50257, 50362, 1770, 13, 2264, 346, 353, 318, 262, 46329, 286, 262, 3504, 6097, 11, 290, 356, 389, 9675, 284], + [50257, 50362, 5414, 318, 1770, 13, 2264, 346, 353, 338, 5642, 1342, 3499, 621, 465, 2300, 13, 50256, 50256, 50256], + [50257, 50362, 679, 4952, 514, 326, 379, 428, 43856, 1622, 286, 262, 614, 11, 351, 6786, 290, 32595, 12023, 28236], + [50257, 50362, 679, 468, 12296, 17188, 1771, 7361, 26113, 18881, 1122, 338, 670, 318, 1107, 8312, 706, 477, 290, 460] + ] + + ) + # fmt: on + + self.assertTrue(np.allclose(generated_ids, EXPECTED_LOGITS)) + + # fmt: off + EXPECTED_TRANSCRIPT = [ + " Mr. Quilter is the apostle of the middle classes, and we are glad to", + " Nor is Mr. Quilter's manner less interesting than his matter.", + " He tells us that at this festive season of the year, with Christmas and roast beef looming", + " He has grave doubts whether Sir Frederick Layton's work is really Greek after all and can", + ] + # fmt: on + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + self.assertListEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_tiny_timestamp_generation(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = FlaxWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + + input_speech = np.concatenate(self._load_datasamples(4)) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="jax").input_features + + generate_fn = jax.jit(functools.partial(model.generate, max_length=448, return_timestamps=True)) + + generated_ids = generate_fn(input_features) + + EXPECTED_OUTPUT = np.array([50258, 50259, 50359, 50364, 2221, 13, 2326, 388, 391, 307, 264, 50244, 295, 264, 2808, 5359, 11, 293, 321, 366, 5404, 281, 2928, 702, 14943, 13, 50692, 50692, 6966, 307, 2221, 13, 2326, 388, 391, 311, 9060, 1570, 1880, 813, 702, 1871, 13, 50926, 50926, 634, 5112, 505, 300, 412, 341, 42729, 3196, 295, 264, 1064, 11, 365, 5272, 293, 12904, 9256, 450, 10539, 51208, 51208, 949, 505, 11, 14138, 10117, 490, 3936, 293, 1080, 3542, 5160, 881, 26336, 281, 264, 1575, 13, 51552, 51552, 634, 575, 12525, 22618, 1968, 6144, 35617, 7354, 1292, 6, 589, 307, 534, 10281, 934, 439, 11, 293, 51836, 51836, 50257]) # fmt: skip + + self.assertTrue(np.allclose(generated_ids, EXPECTED_OUTPUT)) + + EXPECTED_TRANSCRIPT = [ + { + "text": ( + " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel. Nor is" + " Mr. Quilter's manner less interesting than his matter. He tells us that at this festive season" + " of the year, with Christmas and roast beef looming before us, similarly drawn from eating and" + " its results occur most readily to the mind. He has grave doubts whether Sir Frederick Latins'" + " work is really Greek after all, and" + ), + "offsets": [ + { + "text": ( + " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel." + ), + "timestamp": (0.0, 6.5600000000000005), + }, + { + "text": " Nor is Mr. Quilter's manner less interesting than his matter.", + "timestamp": (6.5600000000000005, 11.24), + }, + { + "text": ( + " He tells us that at this festive season of the year, with Christmas and roast beef" + " looming" + ), + "timestamp": (11.24, 16.88), + }, + { + "text": ( + " before us, similarly drawn from eating and its results occur most readily to the mind." + ), + "timestamp": (16.88, 23.76), + }, + { + "text": ( + " He has grave doubts whether Sir Frederick Latins' work is really Greek after all, and" + ), + "timestamp": (23.76, 29.44), + }, + ], + } + ] + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True, output_offsets=True) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + +class FlaxWhisperEncoderModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=60, + is_training=True, + use_labels=True, + hidden_size=16, + num_hidden_layers=2, + num_attention_heads=4, + input_channels=1, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=20, + max_source_positions=30, + num_mel_bins=80, + num_conv_layers=1, + suppress_tokens=None, + begin_suppress_tokens=None, + classifier_proj_size=4, + num_labels=2, + is_encoder_decoder=False, + is_decoder=False, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_labels = use_labels + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.input_channels = input_channels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.num_mel_bins = num_mel_bins + self.max_position_embeddings = max_position_embeddings + self.max_source_positions = max_source_positions + self.num_conv_layers = num_conv_layers + self.suppress_tokens = suppress_tokens + self.begin_suppress_tokens = begin_suppress_tokens + self.classifier_proj_size = classifier_proj_size + self.num_labels = num_labels + self.is_encoder_decoder = is_encoder_decoder + self.is_decoder = is_decoder + + def get_config(self): + return WhisperConfig( + 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, + input_channels=self.input_channels, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + max_source_positions=self.max_source_positions, + decoder_ffn_dim=self.hidden_size, + encoder_ffn_dim=self.hidden_size, + suppress_tokens=self.suppress_tokens, + begin_suppress_tokens=self.begin_suppress_tokens, + classifier_proj_size=self.classifier_proj_size, + num_labels=self.num_labels, + is_encoder_decoder=self.is_encoder_decoder, + is_decoder=self.is_decoder, + ) + + def prepare_whisper_encoder_inputs_dict( + self, + input_features, + ): + return { + "input_features": input_features, + } + + def prepare_config_and_inputs(self): + input_features = floats_tensor([self.batch_size, self.num_mel_bins, self.seq_length]) + + config = self.get_config() + inputs_dict = self.prepare_whisper_encoder_inputs_dict( + input_features=input_features, + ) + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_subsampled_output_lengths(self, input_lengths): + """ + Computes the output length of the convolutional layers + """ + + for i in range(self.num_conv_layers): + input_lengths = (input_lengths - 1) // 2 + 1 + + return input_lengths + + @property + def encoder_seq_length(self): + return self.get_subsampled_output_lengths(self.seq_length) + + +@require_flax +class WhisperEncoderModelTest(FlaxModelTesterMixin, unittest.TestCase): + all_model_classes = (FlaxWhisperForAudioClassification,) if is_flax_available() else () + is_encoder_decoder = False + fx_compatible = False + test_pruning = False + test_missing_keys = False + + input_name = "input_features" + + def setUp(self): + self.model_tester = FlaxWhisperEncoderModelTester(self) + _, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + self.init_shape = (1,) + inputs_dict["input_features"].shape[1:] + + self.all_model_classes = ( + make_partial_class(model_class, input_shape=self.init_shape) for model_class in self.all_model_classes + ) + self.config_tester = ConfigTester(self, config_class=WhisperConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + # overwrite because of `input_features` + def test_jit_compilation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def model_jitted(input_features, **kwargs): + return model(input_features=input_features, **kwargs) + + with self.subTest("JIT Enabled"): + jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + # overwrite because of `input_features` + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.__call__) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["input_features", "attention_mask", "output_attentions"] + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_inputs_embeds(self): + pass + + # WhisperEncoder has no inputs_embeds and thus the `get_input_embeddings` fn is not implemented + def test_model_common_attributes(self): + pass + + # WhisperEncoder cannot resize token embeddings since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + # WhisperEncoder does not have any base model + def test_save_load_to_base(self): + pass + + # WhisperEncoder does not have any base model + def test_save_load_from_base(self): + pass + + # WhisperEncoder does not have any base model + @is_pt_flax_cross_test + def test_save_load_from_base_pt(self): + pass + + # WhisperEncoder does not have any base model + @is_pt_flax_cross_test + def test_save_load_to_base_pt(self): + pass + + # WhisperEncoder does not have any base model + @is_pt_flax_cross_test + def test_save_load_bf16_to_base_pt(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_tf_whisper.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_tf_whisper.py new file mode 100644 index 0000000000000000000000000000000000000000..75c62ae1ad07e6da35fcc118a7f3c43c50d56dac --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_tf_whisper.py @@ -0,0 +1,1119 @@ +# coding=utf-8 +# Copyright 2022 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 TensorFlow Whisper model. """ + +from __future__ import annotations + +import inspect +import tempfile +import traceback +import unittest + +import numpy as np + +from transformers import WhisperConfig, WhisperFeatureExtractor, WhisperProcessor +from transformers.testing_utils import is_tf_available, require_tf, require_tokenizers, run_test_in_subprocess, slow +from transformers.utils import cached_property +from transformers.utils.import_utils import is_datasets_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_datasets_available(): + import datasets + from datasets import load_dataset + + +if is_tf_available(): + import tensorflow as tf + + from transformers import TFWhisperForConditionalGeneration, TFWhisperModel, set_seed + from transformers.models.whisper.modeling_tf_whisper import ( + TFWhisperDecoder, + TFWhisperEncoder, + sinusoidal_embedding_init, + ) + + +def prepare_whisper_inputs_dict( + config, + input_features, + decoder_input_ids, + attention_mask=None, + decoder_attention_mask=None, + head_mask=None, + decoder_head_mask=None, + cross_attn_head_mask=None, +): + if decoder_attention_mask is None: + decoder_attention_mask = tf.where(decoder_input_ids != config.pad_token_id, 1, 0) + if head_mask is None: + head_mask = tf.ones((config.encoder_layers, config.encoder_attention_heads)) + if decoder_head_mask is None: + decoder_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads)) + if cross_attn_head_mask is None: + cross_attn_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads)) + return { + "input_features": input_features, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "head_mask": head_mask, + "decoder_head_mask": decoder_head_mask, + "cross_attn_head_mask": cross_attn_head_mask, + } + + +@require_tf +class TFWhisperModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=60, + is_training=True, + use_labels=False, + vocab_size=200, + hidden_size=16, + num_hidden_layers=2, + num_attention_heads=4, + input_channels=1, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=20, + max_source_positions=30, + max_target_positions=60, + bos_token_id=98, + eos_token_id=98, + pad_token_id=0, + num_mel_bins=80, + decoder_start_token_id=85, + num_conv_layers=1, + suppress_tokens=None, + begin_suppress_tokens=None, + ): + 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.input_channels = input_channels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.num_mel_bins = num_mel_bins + self.max_position_embeddings = max_position_embeddings + self.max_source_positions = max_source_positions + self.max_target_positions = max_target_positions + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.bos_token_id = bos_token_id + self.decoder_start_token_id = decoder_start_token_id + self.num_conv_layers = num_conv_layers + self.suppress_tokens = suppress_tokens + self.begin_suppress_tokens = begin_suppress_tokens + + def prepare_config_and_inputs(self): + input_features = floats_tensor([self.batch_size, self.num_mel_bins, self.seq_length], self.vocab_size) + + decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + config = self.get_config() + inputs_dict = prepare_whisper_inputs_dict( + config, + attention_mask=None, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + ) + return config, inputs_dict + + def get_config(self): + return WhisperConfig( + 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, + input_channels=self.input_channels, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + max_source_positions=self.max_source_positions, + max_target_positions=self.max_target_positions, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + decoder_ffn_dim=self.hidden_size, + encoder_ffn_dim=self.hidden_size, + decoder_start_token_id=self.decoder_start_token_id, + suppress_tokens=self.suppress_tokens, + begin_suppress_tokens=self.begin_suppress_tokens, + ) + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_subsampled_output_lengths(self, input_lengths): + """ + Computes the output length of the convolutional layers + """ + + for i in range(self.num_conv_layers): + input_lengths = (input_lengths - 1) // 2 + 1 + + return input_lengths + + def create_and_check_model_forward(self, config, inputs_dict): + model = TFWhisperModel(config=config) + + input_features = inputs_dict["input_features"] + decoder_input_ids = inputs_dict["decoder_input_ids"] + + # first forward pass + last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state + + self.parent.assertTrue(last_hidden_state.shape, (13, 7, 16)) + + def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): + model = TFWhisperModel(config=config).get_decoder() + # take a slice so we're shorter than the seqeuence length and can append later + input_ids = inputs_dict["decoder_input_ids"][:, :-10] + attention_mask = inputs_dict["decoder_attention_mask"][:, :-10] + + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_token = ids_tensor((self.batch_size, 3), config.vocab_size) + next_tokens = tf.where(next_token <= 2, 2, next_token) + next_attn_mask = ids_tensor((self.batch_size, 3), 2) + + # append to next input_ids and + next_input_ids = tf.concat([input_ids, next_tokens], axis=-1) + next_attention_mask = tf.concat([attention_mask, next_attn_mask], axis=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # select random slice + random_slice_idx = np.random.randint(0, output_from_past.shape[-1]) + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx] + output_from_past_slice = output_from_past[:, :, random_slice_idx] + + self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) + + # test that outputs are equal for slice + self.parent.assertTrue(np.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-2)) + + def check_encoder_decoder_model_standalone(self, config, inputs_dict): + model = TFWhisperModel(config=config) + outputs = model(**inputs_dict) + + encoder_last_hidden_state = outputs.encoder_last_hidden_state + last_hidden_state = outputs.last_hidden_state + + with tempfile.TemporaryDirectory() as tmpdirname: + encoder = model.get_encoder() + encoder.save_pretrained(tmpdirname) + encoder = TFWhisperEncoder.from_pretrained(tmpdirname) + + encoder_last_hidden_state_2 = encoder(inputs_dict["input_features"])[0] + + self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max() < 1e-3) + + with tempfile.TemporaryDirectory() as tmpdirname: + decoder = model.get_decoder() + decoder.save_pretrained(tmpdirname) + decoder = TFWhisperDecoder.from_pretrained(tmpdirname) + + last_hidden_state_2 = decoder( + input_ids=inputs_dict["decoder_input_ids"], + attention_mask=inputs_dict["decoder_attention_mask"], + encoder_hidden_states=encoder_last_hidden_state, + )[0] + + self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max() < 1e-3) + + +@require_tf +class TFWhisperModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (TFWhisperModel, TFWhisperForConditionalGeneration) if is_tf_available() else () + all_generative_model_classes = (TFWhisperForConditionalGeneration,) if is_tf_available() else () + pipeline_model_mapping = {"feature-extraction": TFWhisperModel} if is_tf_available() else {} + is_encoder_decoder = True + fx_compatible = False + test_pruning = False + test_missing_keys = False + test_onnx = False + + input_name = "input_features" + + # TODO (ydshieh): undo skip once a fix is done on TF side. + @unittest.skip("Skip for now as TF 2.13 breaks it on GPU") + def test_xla_generate_slow(self): + super().test_xla_generate_slow() + + def setUp(self): + self.model_tester = TFWhisperModelTester(self) + self.config_tester = ConfigTester(self, config_class=WhisperConfig) + self.maxDiff = 3000 + + def test_config(self): + self.config_tester.run_common_tests() + + def test_save_load_strict(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + model = model_class(config) + + model.build() + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, saved_model=False) + model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) + self.assertEqual(info["missing_keys"], []) + + def test_model_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + def test_requires_grad_encoder_embed_positions(self): + config = self.model_tester.get_config() + for model_class in self.all_model_classes: + model = model_class(config) + encoder = model.get_encoder() + self.assertFalse(encoder.embed_positions.trainable) + + def test_encoder_sinusoidal_embed_positions(self): + config = self.model_tester.get_config() + for model_class in self.all_model_classes: + model = model_class(config) + model.build() + + embeds = model.get_encoder().embed_positions.get_weights()[0] + sinusoids = sinusoidal_embedding_init(embeds.shape).numpy() + self.assertTrue(np.allclose(embeds, sinusoids)) + + 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 _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] + + # cut to half length & take max batch_size 3 + max_batch_size = 3 + input_ids = input_ids[:max_batch_size, :, :] + + # generate max 3 tokens + max_length = 4 + 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, None, max_length + + # not implemented currently + def test_inputs_embeds(self): + pass + + @unittest.skip("Training is not yet supported") + def test_training(self): + pass + + def test_generate_with_head_masking(self): + pass + + @unittest.skip("fp16 is not yet supported for TF models") + def test_generate_fp16(self): + config, input_dict = self.model_tester.prepare_config_and_inputs() + config.max_target_positions = 400 + input_features = input_dict["input_features"] + model = TFWhisperForConditionalGeneration(config) + model.generate(input_features) + model.generate(input_features, num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_features", + "decoder_input_ids", + "decoder_attention_mask", + ] + expected_arg_names.extend( + ["decoder_position_ids", "head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + else: + seq_length = self.model_tester.seq_length + + subsampled_seq_length = model._get_feat_extract_output_lengths(seq_length) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [subsampled_seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_length) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=5e-5, name="outputs", attributes=None): + # We override with a slightly higher tol value, as test recently became flaky + super().check_pt_tf_outputs(tf_outputs, pt_outputs, model_class, tol, name, attributes) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", encoder_key_length) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + + subsampled_encoder_seq_length = model._get_feat_extract_output_lengths(encoder_seq_length) + subsampled_encoder_key_length = model._get_feat_extract_output_lengths(encoder_key_length) + + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + out_len = len(outputs) + + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + subsampled_encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + + def test_generate_without_input_ids(self): + pass + + @staticmethod + def _get_encoder_outputs( + model, input_ids, attention_mask, output_attentions=None, output_hidden_states=None, num_interleave=1 + ): + encoder = model.get_encoder() + encoder_outputs = encoder( + input_ids, + 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 = input_ids[:, :, 0] + input_ids = tf.zeros_like(input_ids[:, :1], dtype=tf.int64) + tf.convert_to_tensor( + [model._get_decoder_start_token_id()] + ) + attention_mask = None + return encoder_outputs, input_ids, attention_mask + + def _check_outputs(self, output, input_ids, config, use_cache=False, num_return_sequences=1): + batch_size, mel, seq_length = input_ids.shape + subsampled_seq_length = self.model_tester.get_subsampled_output_lengths(seq_length) + num_sequences_in_output = batch_size * num_return_sequences + gen_len = ( + output.sequences.shape[-1] - 1 if config.is_encoder_decoder else output.sequences.shape[-1] - seq_length + ) + + # scores + self._check_scores(num_sequences_in_output, output.scores, length=gen_len, config=config) + + # Attentions + # encoder + self._check_encoder_attention_for_generate( + output.encoder_attentions, batch_size, config, subsampled_seq_length + ) + # decoder + self._check_attentions_for_generate( + num_sequences_in_output, + output.decoder_attentions, + min_length=1, + max_length=output.sequences.shape[-1], + config=config, + use_cache=use_cache, + ) + + # Hidden States + # encoder + self._check_encoder_hidden_states_for_generate( + output.encoder_hidden_states, batch_size, config, subsampled_seq_length + ) + + # decoder + self._check_hidden_states_for_generate( + num_sequences_in_output, + output.decoder_hidden_states, + min_length=1, + max_length=output.sequences.shape[-1], + config=config, + use_cache=use_cache, + ) + + # overwritten from parent due to the inability to work when non-text inputs are not passed AND because the input is + # `input_features` + def test_lm_head_model_random_no_beam_search_generate(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_features = inputs_dict.get("input_features", None) + + # iterate over all generative models + for model_class in self.all_generative_model_classes: + model = model_class(config) + + if config.bos_token_id is None: + # if bos token id is not defined model needs input_features + with self.assertRaises(AssertionError): + model.generate(do_sample=True, max_length=5) + # num_return_sequences = 1 + self._check_generated_ids(model.generate(input_features, do_sample=True)) + + with self.assertRaises(ValueError): + # generating multiple sequences when no beam search generation + # is not allowed as it would always generate the same sequences + model.generate(input_features, do_sample=False, num_return_sequences=2) + + # num_return_sequences > 1, sample + self._check_generated_ids(model.generate(input_features, do_sample=True, num_return_sequences=2)) + + # check bad words tokens language generation + # create list of 1-seq bad token and list of 2-seq of bad tokens + bad_words_ids = [self._generate_random_bad_tokens(1, model), self._generate_random_bad_tokens(2, model)] + output_tokens = model.generate( + input_features, do_sample=True, bad_words_ids=bad_words_ids, num_return_sequences=2 + ) + # only count generated tokens + generated_ids = output_tokens[:, input_features.shape[-1] :] + self.assertFalse(self._check_match_tokens(generated_ids.numpy().tolist(), bad_words_ids)) + + # overwritten from parent due to the inability to work when non-text inputs are not passed AND because the input is + # `input_features` + def test_lm_head_model_random_beam_search_generate(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_features = inputs_dict.get("input_features", None) + + for model_class in self.all_generative_model_classes: + model = model_class(config) + + if config.bos_token_id is None: + # if bos token id is not defined model needs input_ids, num_return_sequences = 1 + self._check_generated_ids(model.generate(input_features, do_sample=True, num_beams=2)) + + with self.assertRaises(ValueError): + # generating more sequences than having beams leads is not possible + model.generate(input_features, do_sample=False, num_return_sequences=3, num_beams=2) + + # num_return_sequences > 1, sample + self._check_generated_ids( + model.generate( + input_features, + do_sample=True, + num_beams=2, + num_return_sequences=2, + ) + ) + # num_return_sequences > 1, greedy + self._check_generated_ids( + model.generate(input_features, do_sample=False, num_beams=2, num_return_sequences=2) + ) + + # check bad words tokens language generation + # create list of 1-seq bad token and list of 2-seq of bad tokens + bad_words_ids = [self._generate_random_bad_tokens(1, model), self._generate_random_bad_tokens(2, model)] + output_tokens = model.generate( + input_features, do_sample=False, bad_words_ids=bad_words_ids, num_beams=2, num_return_sequences=2 + ) + # only count generated tokens + generated_ids = output_tokens[:, input_features.shape[-1] :] + self.assertFalse(self._check_match_tokens(generated_ids.numpy().tolist(), bad_words_ids)) + + def test_generate_with_prompt_ids_and_task_and_language(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = TFWhisperForConditionalGeneration(config) + input_features = input_dict["input_features"] + prompt_ids = np.arange(5) + language = "<|de|>" + task = "translate" + lang_id = 6 + task_id = 7 + model.generation_config.__setattr__("lang_to_id", {language: lang_id}) + model.generation_config.__setattr__("task_to_id", {task: task_id}) + + output = model.generate(input_features, max_new_tokens=5, task=task, language=language, prompt_ids=prompt_ids) + + expected_output_start = [ + *prompt_ids.tolist(), + model.generation_config.decoder_start_token_id, + lang_id, + task_id, + ] + for row in output.numpy().tolist(): + self.assertListEqual(row[: len(expected_output_start)], expected_output_start) + + def test_generate_with_prompt_ids_and_forced_decoder_ids(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = TFWhisperForConditionalGeneration(config) + input_features = input_dict["input_features"] + prompt_ids = np.asarray(range(5)) + forced_decoder_ids = [(1, 6), (2, 7), (3, 8)] + + output = model.generate( + input_features, max_new_tokens=5, forced_decoder_ids=forced_decoder_ids, prompt_ids=prompt_ids + ) + + expected_output_start = [ + *prompt_ids.tolist(), + model.generation_config.decoder_start_token_id, + *[token for _rank, token in forced_decoder_ids], + ] + for row in output.numpy().tolist(): + self.assertListEqual(row[: len(expected_output_start)], expected_output_start) + + +def _load_datasamples(num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + +def _test_large_logits_librispeech(in_queue, out_queue, timeout): + error = None + try: + _ = in_queue.get(timeout=timeout) + + set_seed(0) + + model = TFWhisperModel.from_pretrained("openai/whisper-large") + + input_speech = _load_datasamples(1) + + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + processed_inputs = processor( + audio=input_speech, text="This part of the speech", add_special_tokens=False, return_tensors="tf" + ) + input_features = processed_inputs.input_features + decoder_input_ids = processed_inputs.labels + + logits = model( + input_features, + decoder_input_ids=decoder_input_ids, + output_hidden_states=False, + output_attentions=False, + use_cache=False, + ) + + logits = logits.last_hidden_state @ tf.transpose(model.model.decoder.embed_tokens.weights[0]) + + # fmt: off + EXPECTED_LOGITS = tf.convert_to_tensor( + [ + 2.1382, 0.9381, 4.4671, 3.5589, 2.4022, 3.8576, -0.6521, 2.5472, + 1.8301, 1.9957, 2.3432, 1.4678, 0.5459, 2.2597, 1.5179, 2.5357, + 1.1624, 0.6194, 1.0757, 1.8259, 2.4076, 1.6601, 2.3503, 1.3376, + 1.9891, 1.8635, 3.8931, 5.3699, 4.4772, 3.9184 + ] + ) + # fmt: on + + unittest.TestCase().assertTrue(np.allclose(logits[0, 0, :30], EXPECTED_LOGITS, atol=1e-4)) + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +def _test_large_generation(in_queue, out_queue, timeout): + error = None + try: + _ = in_queue.get(timeout=timeout) + + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-large") + + input_speech = _load_datasamples(1) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="tf").input_features + + generated_ids = model.generate( + input_features, do_sample=False, max_length=20, language="<|en|>", task="transcribe" + ) + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = " Mr. Quilter is the apostle of the middle classes and we are glad" + unittest.TestCase().assertEqual(transcript, EXPECTED_TRANSCRIPT) + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +def _test_large_generation_multilingual(in_queue, out_queue, timeout): + error = None + try: + _ = in_queue.get(timeout=timeout) + + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-large") + + ds = load_dataset("common_voice", "ja", split="test", streaming=True) + ds = ds.cast_column("audio", datasets.Audio(sampling_rate=16_000)) + input_speech = next(iter(ds))["audio"]["array"] + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="tf").input_features + + generated_ids = model.generate( + input_features, do_sample=False, max_length=20, language="<|ja|>", task="transcribe" + ) + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = "木村さんに電話を貸してもらいました" + unittest.TestCase().assertEqual(transcript, EXPECTED_TRANSCRIPT) + + generated_ids = model.generate( + input_features, do_sample=False, max_length=20, language="<|en|>", task="transcribe" + ) + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = " Kimura-san called me." + unittest.TestCase().assertEqual(transcript, EXPECTED_TRANSCRIPT) + + generated_ids = model.generate( + input_features, do_sample=False, max_length=20, language="<|ja|>", task="translate" + ) + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = " I borrowed a phone from Kimura san" + unittest.TestCase().assertEqual(transcript, EXPECTED_TRANSCRIPT) + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +def _test_large_batched_generation(in_queue, out_queue, timeout): + error = None + try: + _ = in_queue.get(timeout=timeout) + + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-large") + + input_speech = _load_datasamples(4) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="tf").input_features + generated_ids_1 = model.generate(input_features[0:2], max_length=20) + generated_ids_2 = model.generate(input_features[2:4], max_length=20) + generated_ids = np.concatenate([generated_ids_1, generated_ids_2]) + + # fmt: off + EXPECTED_IDS = [ + [50258, 50358, 50363, 2221, 13, 2326, 388, 391, 307, 264, 50244, 295, 264, 2808, 5359, 293, 321, 366, 5404, 281], + [50258, 50358, 50363, 6966, 307, 2221, 13, 2326, 388, 391, 311, 9060, 1570, 1880, 813, 702, 1871, 13, 50257, 50257], + [50258, 50358, 50363, 634, 5112, 505, 300, 412, 341, 42729, 3196, 295, 264, 1064, 11, 365, 5272, 293, 12904, 9256], + [50258, 50358, 50363, 634, 575, 12525, 22618, 1968, 6144, 35617, 20084, 1756, 311, 589, 307, 534, 10281, 934, 439, 11] + ] + # fmt: on + + unittest.TestCase().assertEqual(generated_ids.tolist(), EXPECTED_IDS) + + # fmt: off + EXPECTED_TRANSCRIPT = [ + " Mr. Quilter is the apostle of the middle classes and we are glad to", + " Nor is Mr. Quilter's manner less interesting than his matter.", + " He tells us that at this festive season of the year, with Christmas and roast beef", + " He has grave doubts whether Sir Frederick Layton's work is really Greek after all," + ] + # fmt: on + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + unittest.TestCase().assertListEqual(transcript, EXPECTED_TRANSCRIPT) + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +@require_tf +@require_tokenizers +class TFWhisperModelIntegrationTests(unittest.TestCase): + @cached_property + def default_processor(self): + return WhisperProcessor.from_pretrained("openai/whisper-base") + + def _load_datasamples(self, num_samples): + return _load_datasamples(num_samples) + + @slow + def test_tiny_logits_librispeech(self): + set_seed(0) + model = TFWhisperModel.from_pretrained("openai/whisper-tiny") + input_speech = self._load_datasamples(1) + feature_extractor = WhisperFeatureExtractor() + input_features = feature_extractor(input_speech, return_tensors="tf").input_features + + logits = model( + input_features, + decoder_input_ids=tf.convert_to_tensor([[50258, 50259, 50359]]), + output_hidden_states=False, + output_attentions=False, + return_dict=False, + use_cache=False, + ) + + # fmt: off + EXPECTED_LOGITS = tf.convert_to_tensor( + [ + 2.9892, -6.7607, 5.7348, 3.6096, 0.2152, -5.7321, 4.8855, -1.6407, + 0.2823, -1.5718, 10.4269, 3.4427, 0.0219, -8.0612, 3.4784, 8.4246, + 4.0575, -2.2864, 11.1084, 0.9963, 0.9884, -8.5154, -3.5469, -9.3713, + 0.9786, 3.5435, 7.4850, -5.2579, -1.4366, 10.4841 + ] + ) + # fmt: on + self.assertTrue(np.allclose(logits[0][0, 0, :30], EXPECTED_LOGITS, atol=1e-4)) + + # fmt: off + EXPECTED_GENERATION = tf.convert_to_tensor( + [ + -1.4651, -2.6944, 2.7821, 2.3793, 4.0738, 0.0188, -3.3203, 1.9836, + 0.0520, 0.7095, 1.1063, 0.2952, -3.6786, -0.5249, 0.3105, 4.7691, + 1.1562, 1.3046, 0.5810, -0.3624, 1.7006, 1.3424, 0.9817, 2.1958, + 1.8775, -5.7046, -0.7679, 4.0113, 2.6848, 2.8609 + ] + ) + # fmt: on + + head_logits = logits[0] @ tf.transpose(model.model.decoder.embed_tokens.weights[0]) + self.assertTrue(np.allclose(head_logits[0, 0, :30], EXPECTED_GENERATION, atol=1e-4)) + + @slow + def test_small_en_logits_librispeech(self): + set_seed(0) + model = TFWhisperModel.from_pretrained("openai/whisper-small.en") + + input_speech = self._load_datasamples(1) + + feaure_extractor = WhisperFeatureExtractor() + input_features = feaure_extractor(input_speech, return_tensors="tf").input_features + + logits = model( + input_features, + decoder_input_ids=tf.convert_to_tensor([[model.config.decoder_start_token_id]]), + output_hidden_states=False, + output_attentions=False, + use_cache=False, + ) + + logits = logits.last_hidden_state @ tf.transpose(model.model.decoder.embed_tokens.weights[0]) + + # fmt: off + EXPECTED_LOGITS = tf.convert_to_tensor( + [ + -3.6784, -7.7211, -9.5070, -11.9286, -7.6489, -9.7026, -5.6188, + -8.0104, -4.6238, -5.1833, -9.0485, -3.4079, -5.4874, -2.6935, + -6.3479, -7.3398, -6.9558, -7.6867, -7.4748, -8.3463, -9.9781, + -10.8389, -10.3105, -11.7201, -9.7261, -7.1590, -5.9272, -12.4509, + -11.1146, -8.1918 + ] + ) + # fmt: on + self.assertTrue(np.allclose(logits[0, 0, :30], EXPECTED_LOGITS, atol=1e-4)) + + @slow + def test_large_logits_librispeech(self): + run_test_in_subprocess(test_case=self, target_func=_test_large_logits_librispeech, inputs=None) + + @slow + def test_tiny_en_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + model.config.decoder_start_token_id = 50257 + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="tf").input_features + + generated_ids = model.generate(input_features, num_beams=5, max_length=20) + transcript = processor.tokenizer.batch_decode(generated_ids)[0] + + EXPECTED_TRANSCRIPT = ( + "<|startoftranscript|><|notimestamps|> Mr. Quilter is the apostle of the middle" + " classes, and we are glad to" + ) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_tiny_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="tf").input_features + + generated_ids = model.generate(input_features, num_beams=5, max_length=20) + transcript = processor.tokenizer.decode(generated_ids[0]) + + EXPECTED_TRANSCRIPT = ( + "<|startoftranscript|><|en|><|transcribe|><|notimestamps|> Mr. Quilter is the apostle of the middle" + " classes and we are glad" + ) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_tiny_xla_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="tf").input_features + + xla_generate = tf.function(model.generate, jit_compile=True) + + generated_ids = model.generate(input_features, num_beams=5, max_length=20) + generated_ids_xla = xla_generate(input_features, num_beams=5, max_length=20) + + transcript = processor.tokenizer.decode(generated_ids[0]) + transcript_xla = processor.tokenizer.decode(generated_ids_xla[0]) + + EXPECTED_TRANSCRIPT = ( + "<|startoftranscript|><|en|><|transcribe|><|notimestamps|> Mr. Quilter is the apostle of the middle" + " classes and we are glad" + ) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + self.assertEqual(transcript_xla, EXPECTED_TRANSCRIPT) + + @slow + def test_large_generation(self): + run_test_in_subprocess(test_case=self, target_func=_test_large_generation, inputs=None) + + @slow + def test_large_generation_multilingual(self): + run_test_in_subprocess(test_case=self, target_func=_test_large_generation_multilingual, inputs=None) + + @slow + def test_large_batched_generation(self): + run_test_in_subprocess(test_case=self, target_func=_test_large_batched_generation, inputs=None) + + @slow + def test_tiny_en_batched_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + + input_speech = self._load_datasamples(4) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="tf").input_features + generated_ids = model.generate(input_features, max_length=20) + + # fmt: off + EXPECTED_LOGITS = tf.convert_to_tensor( + [ + [50257, 50362, 1770, 13, 2264, 346, 353, 318, 262, 46329, 286, 262, 3504, 6097, 11, 290, 356, 389, 9675, 284], + [50257, 50362, 5414, 318, 1770, 13, 2264, 346, 353, 338, 5642, 1342, 3499, 621, 465, 2300, 13, 50256, 50256, 50256], + [50257, 50362, 679, 4952, 514, 326, 379, 428, 43856, 1622, 286, 262, 614, 11, 351, 6786, 290, 32595, 12023, 28236], + [50257, 50362, 679, 468, 12296, 17188, 1771, 7361, 26113, 18881, 1122, 338, 670, 318, 1107, 8312, 706, 477, 290, 460] + ] + + ) + # fmt: on + + self.assertTrue(np.allclose(generated_ids, EXPECTED_LOGITS)) + + # fmt: off + EXPECTED_TRANSCRIPT = [ + " Mr. Quilter is the apostle of the middle classes, and we are glad to", + " Nor is Mr. Quilter's manner less interesting than his matter.", + " He tells us that at this festive season of the year, with Christmas and roast beef looming", + " He has grave doubts whether Sir Frederick Layton's work is really Greek after all and can", + ] + # fmt: on + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + self.assertListEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_tiny_en_batched_xla_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = TFWhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + + input_speech = self._load_datasamples(4) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="tf").input_features + + xla_generate = tf.function(model.generate, jit_compile=True) + + generated_ids = model.generate(input_features, max_length=20) + generated_ids_xla = xla_generate(input_features, max_length=20) + + # fmt: off + EXPECTED_LOGITS = tf.convert_to_tensor( + [ + [50257, 50362, 1770, 13, 2264, 346, 353, 318, 262, 46329, 286, 262, 3504, 6097, 11, 290, 356, 389, 9675, 284], + [50257, 50362, 5414, 318, 1770, 13, 2264, 346, 353, 338, 5642, 1342, 3499, 621, 465, 2300, 13, 50256, 50256, 50256], + [50257, 50362, 679, 4952, 514, 326, 379, 428, 43856, 1622, 286, 262, 614, 11, 351, 6786, 290, 32595, 12023, 28236], + [50257, 50362, 679, 468, 12296, 17188, 1771, 7361, 26113, 18881, 1122, 338, 670, 318, 1107, 8312, 706, 477, 290, 460] + ] + + ) + # fmt: on + + self.assertTrue(np.allclose(generated_ids, EXPECTED_LOGITS)) + self.assertTrue(np.allclose(generated_ids_xla, EXPECTED_LOGITS)) + + # fmt: off + EXPECTED_TRANSCRIPT = [ + " Mr. Quilter is the apostle of the middle classes, and we are glad to", + " Nor is Mr. Quilter's manner less interesting than his matter.", + " He tells us that at this festive season of the year, with Christmas and roast beef looming", + " He has grave doubts whether Sir Frederick Layton's work is really Greek after all and can", + ] + # fmt: on + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + transcript_xla = processor.batch_decode(generated_ids_xla, skip_special_tokens=True) + self.assertListEqual(transcript, EXPECTED_TRANSCRIPT) + self.assertListEqual(transcript_xla, EXPECTED_TRANSCRIPT) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_whisper.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_whisper.py new file mode 100644 index 0000000000000000000000000000000000000000..9de3b8ff2c21b678b667be45b11357c0f51892f8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_modeling_whisper.py @@ -0,0 +1,2769 @@ +# coding=utf-8 +# Copyright 2022 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 Whisper model. """ + +import copy +import inspect +import os +import random +import tempfile +import time +import unittest + +import numpy as np +import pytest + +import transformers +from transformers import WhisperConfig +from transformers.testing_utils import ( + is_pt_flax_cross_test, + require_flash_attn, + require_torch, + require_torch_fp16, + require_torch_gpu, + require_torchaudio, + slow, + torch_device, +) +from transformers.utils import cached_property, is_flax_available, is_torch_available +from transformers.utils.import_utils import is_datasets_available + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_datasets_available(): + import datasets + from datasets import Audio, load_dataset + +if is_torch_available(): + import torch + + from transformers import ( + WhisperFeatureExtractor, + WhisperForAudioClassification, + WhisperForCausalLM, + WhisperForConditionalGeneration, + WhisperModel, + WhisperProcessor, + set_seed, + ) + from transformers.generation.logits_process import LogitsProcessor + from transformers.models.whisper.modeling_whisper import WhisperDecoder, WhisperEncoder, sinusoids + + class DummyTimestampLogitProcessor(LogitsProcessor): + """This processor fakes the correct timestamps tokens pattern [TOK_1] [TOK_2] ... [TOK_N] [TIME_STAMP_TOK_1] [TIME_STAMP_TOK_2] [TOK_N+1] ...""" + + def __init__( + self, timestamp_begin, vocab_size, batch_size, max_length, min_space=3, seed=0, is_length_ascending=True + ): + self.timestamp_begin = timestamp_begin + self.vocab_size = vocab_size + + self.min_space_between_timestamps = min_space + self.timestamp_tokens = torch.arange(self.timestamp_begin, self.vocab_size) + self.timestamp_tokens.to(torch_device) + self.is_length_ascending = is_length_ascending + + self.no_time_stamp_counter = batch_size * [0] + self.prev_highest_timestamp = batch_size * [0] + self.batch_size = batch_size + self.max_length = max_length + self.count = 0 + + self.let_pass = [[] for _ in range(batch_size)] + for k in range(batch_size): + random.seed(seed + k) + for _ in range(10000): + self.let_pass[k].append(random.randint(1, 10) <= 3) + + def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: + # we don't want to randomely sample timestamp tokens + if input_ids.shape[-1] > 1: + scores[:, self.timestamp_begin :] = -float("inf") + + self.no_time_stamp_counter = [x + 1 for x in self.no_time_stamp_counter] + for k in range(input_ids.shape[0]): + # make sure to use correct index if a batch was removed + if self.is_length_ascending and input_ids.shape[0] < self.batch_size: + prev_k = k + self.batch_size - input_ids.shape[0] + else: + prev_k = k + + if input_ids[k, -1] == self.timestamp_begin: + self.no_time_stamp_counter[prev_k] = 0 + + can_produce = self.no_time_stamp_counter[prev_k] > self.min_space_between_timestamps + must_produce = ( + input_ids[k][2:].le(self.timestamp_begin).all() and input_ids.shape[-1] == self.max_length - 1 + ) + # produce timestamp with 30% + if (can_produce and self.let_pass[prev_k][self.count]) or must_produce: + self.no_time_stamp_counter[prev_k] = 0 + self.prev_highest_timestamp[prev_k] = max(input_ids[k].max() + 1, self.timestamp_tokens[0].item()) + + # force a timestamp + scores[k, :] = -float("inf") + scores[k, self.prev_highest_timestamp[prev_k]] = 10.0 + + if ( + input_ids.shape[-1] > 3 + and input_ids[k, -1].item() in self.timestamp_tokens + and input_ids[k, -2].item() not in self.timestamp_tokens + ): + # force the same as before + scores[k, :] = -float("inf") + scores[k, input_ids[k, -1].item()] = 10.0 + + self.count += 1 + + if torch.isinf(scores).all(): + raise ValueError("Dummy logit processor is incorrectly set up. Scores should not be all inf.") + + return scores + + +if is_flax_available(): + import jax.numpy as jnp + + from transformers.modeling_flax_pytorch_utils import ( + convert_pytorch_state_dict_to_flax, + load_flax_weights_in_pytorch_model, + ) + + +def prepare_whisper_inputs_dict( + config, + input_features, + decoder_input_ids, + attention_mask=None, + decoder_attention_mask=None, + head_mask=None, + decoder_head_mask=None, + cross_attn_head_mask=None, +): + if decoder_attention_mask is None: + decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) + if head_mask is None: + head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device) + if decoder_head_mask is None: + decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) + if cross_attn_head_mask is None: + cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) + return { + # "input_ids": input_features, + "input_features": input_features, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "head_mask": head_mask, + "decoder_head_mask": decoder_head_mask, + "cross_attn_head_mask": cross_attn_head_mask, + } + + +@require_torch +class WhisperModelTester: + def __init__( + self, + parent, + batch_size=2, + seq_length=60, + is_training=True, + use_labels=False, + vocab_size=200, + hidden_size=16, + num_hidden_layers=2, + num_attention_heads=4, + input_channels=1, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=20, + max_source_positions=30, + max_target_positions=40, + bos_token_id=98, + eos_token_id=98, + pad_token_id=0, + num_mel_bins=80, + decoder_start_token_id=85, + num_conv_layers=1, + suppress_tokens=None, + begin_suppress_tokens=None, + ): + 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.input_channels = input_channels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.num_mel_bins = num_mel_bins + self.max_position_embeddings = max_position_embeddings + self.max_source_positions = max_source_positions + self.max_target_positions = max_target_positions + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.bos_token_id = bos_token_id + self.decoder_start_token_id = decoder_start_token_id + self.num_conv_layers = num_conv_layers + self.suppress_tokens = suppress_tokens + self.begin_suppress_tokens = begin_suppress_tokens + + def prepare_config_and_inputs(self): + input_features = floats_tensor([self.batch_size, self.num_mel_bins, self.seq_length], self.vocab_size) + + decoder_input_ids = torch.tensor(self.batch_size * [[self.decoder_start_token_id]], device=torch_device) + + config = self.get_config() + inputs_dict = prepare_whisper_inputs_dict( + config, + attention_mask=None, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + ) + return config, inputs_dict + + def get_config(self): + return WhisperConfig( + 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, + input_channels=self.input_channels, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + max_source_positions=self.max_source_positions, + max_target_positions=self.max_target_positions, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + decoder_ffn_dim=self.hidden_size, + encoder_ffn_dim=self.hidden_size, + decoder_start_token_id=self.decoder_start_token_id, + suppress_tokens=self.suppress_tokens, + begin_suppress_tokens=self.begin_suppress_tokens, + ) + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_subsampled_output_lengths(self, input_lengths): + """ + Computes the output length of the convolutional layers + """ + + for i in range(self.num_conv_layers): + input_lengths = (input_lengths - 1) // 2 + 1 + + return input_lengths + + def create_and_check_model_forward(self, config, inputs_dict, freeze_encoder=False): + model = WhisperModel(config=config).to(torch_device).eval() + + if freeze_encoder: + model.freeze_encoder() + + input_features = inputs_dict["input_features"] + decoder_input_ids = inputs_dict["decoder_input_ids"] + + # first forward pass + last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state + + self.parent.assertTrue(last_hidden_state.shape, (13, 7, 16)) + + def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): + model = WhisperModel(config=config).get_decoder().to(torch_device).eval() + input_ids = inputs_dict["decoder_input_ids"] + attention_mask = inputs_dict["decoder_attention_mask"] + + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size).clamp(2) + next_attn_mask = ids_tensor((self.batch_size, 3), 2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # 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-2)) + + def check_encoder_decoder_model_standalone(self, config, inputs_dict): + model = WhisperModel(config=config).to(torch_device).eval() + outputs = model(**inputs_dict) + + encoder_last_hidden_state = outputs.encoder_last_hidden_state + last_hidden_state = outputs.last_hidden_state + + with tempfile.TemporaryDirectory() as tmpdirname: + encoder = model.get_encoder() + encoder.save_pretrained(tmpdirname) + encoder = WhisperEncoder.from_pretrained(tmpdirname).to(torch_device) + + encoder_last_hidden_state_2 = encoder(inputs_dict["input_features"])[0] + + self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3) + + with tempfile.TemporaryDirectory() as tmpdirname: + decoder = model.get_decoder() + decoder.save_pretrained(tmpdirname) + decoder = WhisperDecoder.from_pretrained(tmpdirname).to(torch_device) + + last_hidden_state_2 = decoder( + input_ids=inputs_dict["decoder_input_ids"], + attention_mask=inputs_dict["decoder_attention_mask"], + encoder_hidden_states=encoder_last_hidden_state, + )[0] + + self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3) + + +@require_torch +class WhisperModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (WhisperModel, WhisperForConditionalGeneration) if is_torch_available() else () + all_generative_model_classes = (WhisperForConditionalGeneration,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "audio-classification": WhisperForAudioClassification, + "automatic-speech-recognition": WhisperForConditionalGeneration, + "feature-extraction": WhisperModel, + "text-generation": WhisperForCausalLM, + } + if is_torch_available() + else {} + ) + is_encoder_decoder = True + fx_compatible = False + test_pruning = False + test_missing_keys = False + # Needs higher percentages after model tester's vocab_size is changed to 200 (PR #21222) + # `0.5` is for `test_disk_offload` (which also works for `test_model_parallelism`) + model_split_percents = [0.5, 0.8, 0.9] + + input_name = "input_features" + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name in [ + "AutomaticSpeechRecognitionPipelineTests", + "AudioClassificationPipelineTests", + ]: + # RuntimeError: The size of tensor a (1500) must match the size of tensor b (30) at non-singleton + # dimension 1 + return True + + return False + + def setUp(self): + self.model_tester = WhisperModelTester(self) + self.config_tester = ConfigTester(self, config_class=WhisperConfig) + self.maxDiff = 3000 + + def test_config(self): + self.config_tester.run_common_tests() + + def test_save_load_strict(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) + self.assertEqual(info["missing_keys"], []) + + def test_model_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + def test_model_forward_with_frozen_encoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs, freeze_encoder=True) + + def test_requires_grad_with_frozen_encoder(self): + config = self.model_tester.get_config() + for model_class in self.all_model_classes: + model = model_class(config) + model.freeze_encoder() + + try: + encoder_grads = [param.requires_grad for param in model.encoder.parameters()] + decoder_grads = [param.requires_grad for param in model.decoder.parameters()] + except AttributeError: + encoder_grads = [param.requires_grad for param in model.model.encoder.parameters()] + decoder_grads = [param.requires_grad for param in model.model.decoder.parameters()] + + self.assertFalse(all(encoder_grads)) + self.assertTrue(all(decoder_grads)) + + def test_requires_grad_encoder_embed_positions(self): + config = self.model_tester.get_config() + for model_class in self.all_model_classes: + model = model_class(config) + encoder = model.get_encoder() + self.assertFalse(encoder.embed_positions.weight.requires_grad) + + def test_encoder_sinusoidal_embed_positions(self): + config = self.model_tester.get_config() + for model_class in self.all_model_classes: + model = model_class(config) + embeds = model.get_encoder().embed_positions.weight + self.assertTrue(torch.allclose(embeds, sinusoids(*embeds.shape))) + + 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 _get_input_ids_and_config(self, batch_size=3): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_ids = inputs_dict[self.input_name] + + # cut to half length & take max batch_size=batch_size + input_ids = input_ids[:batch_size, :, :] + + # generate max 3 tokens + max_length = 4 + 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, None, max_length + + def test_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + + decoder_input_ids = inputs.pop("decoder_input_ids", None) + inputs.pop("decoder_attention_mask", None) + + wte = model.get_input_embeddings() + inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) + + with torch.no_grad(): + model(**inputs)[0] + + # training is not supported yet + def test_training(self): + pass + + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + def test_generate_with_head_masking(self): + pass + + @require_torch_fp16 + def test_generate_fp16(self): + config, input_dict = self.model_tester.prepare_config_and_inputs() + config.max_target_positions = 400 + input_features = input_dict["input_features"] + model = WhisperForConditionalGeneration(config).eval().to(torch_device) + input_features = input_features.half() + model.half() + model.generate(input_features) + model.generate(input_features, num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3) + + def test_generate_language(self): + config, input_dict = self.model_tester.prepare_config_and_inputs() + input_features = input_dict["input_features"] + model = WhisperForConditionalGeneration(config).to(torch_device) + # Hack to keep the test fast and not require downloading a model with a generation_config + model.generation_config.__setattr__("lang_to_id", {"<|en|>": 1}) + model.generation_config.__setattr__("task_to_id", {"transcribe": 2}) + + # test language code + model.generate(input_features, language="en") + # test tokenizer code + model.generate(input_features, language="<|en|>") + # test language name + model.generate(input_features, language="English") + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = [ + "input_features", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + ] + expected_arg_names.extend( + ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + else: + seq_length = self.model_tester.seq_length + + subsampled_seq_length = model._get_feat_extract_output_lengths(seq_length) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [subsampled_seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", 1) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", 1) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", 1) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + + subsampled_encoder_seq_length = model._get_feat_extract_output_lengths(encoder_seq_length) + subsampled_encoder_key_length = model._get_feat_extract_output_lengths(encoder_key_length) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + out_len = len(outputs) + + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + subsampled_encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + + def test_resize_tokens_embeddings(self): + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + return + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + + if self.model_tester.is_training is False: + model.eval() + + model_vocab_size = config.vocab_size + # Retrieve the embeddings and clone theme + model_embed = model.resize_token_embeddings(model_vocab_size) + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.vocab_size, model_vocab_size + 10) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15) + + # make sure that decoder_input_ids are resized + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that adding and removing tokens has not modified the first part of the embedding matrix. + models_equal = True + for p1, p2 in zip(cloned_embeddings, model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + def test_resize_embeddings_untied(self): + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + return + + original_config.tie_word_embeddings = False + + # if model cannot untied embeddings -> leave test + if original_config.tie_word_embeddings: + return + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config).to(torch_device) + + # if no output embeddings -> leave test + if model.get_output_embeddings() is None: + continue + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_vocab_size = config.vocab_size + model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.vocab_size, model_vocab_size + 10) + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size + 10) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size - 15) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size - 15) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + def test_generate_without_input_ids(self): + pass + + @staticmethod + def _get_encoder_outputs( + model, input_ids, attention_mask, output_attentions=None, output_hidden_states=None, num_interleave=1 + ): + encoder = model.get_encoder() + encoder_outputs = encoder( + input_ids, + 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 = input_ids[:, :, 0] + input_ids = torch.zeros_like(input_ids[:, :1], dtype=torch.long) + torch.tensor( + [model._get_decoder_start_token_id()], device=input_ids.device + ) + attention_mask = None + return encoder_outputs, input_ids, attention_mask + + def _check_outputs(self, output, input_ids, config, use_cache=False, num_return_sequences=1): + batch_size, mel, seq_length = input_ids.shape + subsampled_seq_length = self.model_tester.get_subsampled_output_lengths(seq_length) + num_sequences_in_output = batch_size * num_return_sequences + gen_len = ( + output.sequences.shape[-1] - 1 if config.is_encoder_decoder else output.sequences.shape[-1] - seq_length + ) + + # scores + self._check_scores(num_sequences_in_output, output.scores, length=gen_len, config=config) + + # Attentions + # encoder + self._check_encoder_attention_for_generate( + output.encoder_attentions, batch_size, config, subsampled_seq_length + ) + # decoder + self._check_attentions_for_generate( + num_sequences_in_output, + output.decoder_attentions, + min_length=1, + max_length=output.sequences.shape[-1], + config=config, + use_cache=use_cache, + ) + + # Hidden States + # encoder + self._check_encoder_hidden_states_for_generate( + output.encoder_hidden_states, batch_size, config, subsampled_seq_length + ) + + # decoder + self._check_hidden_states_for_generate( + num_sequences_in_output, + output.decoder_hidden_states, + min_length=1, + max_length=output.sequences.shape[-1], + config=config, + use_cache=use_cache, + ) + + @require_flash_attn + @require_torch_gpu + @pytest.mark.flash_attn_test + @slow + def test_flash_attn_2_inference(self): + import torch + + for model_class in self.all_model_classes: + if not model_class._supports_flash_attn_2: + return + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_fa = model_class.from_pretrained( + tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2" + ) + model_fa.to(torch_device) + + model = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.bfloat16, + ) + model.to(torch_device) + + dummy_input = inputs_dict[model.main_input_name][:1] + if dummy_input.dtype in [torch.float32, torch.float16]: + dummy_input = dummy_input.to(torch.bfloat16) + + decoder_input_ids = inputs_dict.get("decoder_input_ids", dummy_input)[:1] + + outputs = model(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + outputs_fa = model_fa(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + + logits = outputs.decoder_hidden_states[-1] + logits_fa = outputs_fa.decoder_hidden_states[-1] + + # whisper FA2 needs very high tolerance + assert torch.allclose(logits_fa, logits, atol=4e-1) + + # check with inference + dropout + model.train() + _ = model_fa(dummy_input, decoder_input_ids=decoder_input_ids) + + @require_flash_attn + @require_torch_gpu + @pytest.mark.flash_attn_test + @slow + def test_flash_attn_2_inference_padding_right(self): + import torch + + for model_class in self.all_model_classes: + if not model_class._supports_flash_attn_2: + return + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_fa = model_class.from_pretrained( + tmpdirname, torch_dtype=torch.float16, attn_implementation="flash_attention_2" + ) + model_fa.to(torch_device) + + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16) + model.to(torch_device) + + dummy_input = inputs_dict[model.main_input_name][:1] + dummy_input = dummy_input.to(torch.float16) + + decoder_input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]], device=dummy_input.device, dtype=torch.long) + decoder_attention_mask = torch.tensor( + [[0, 0, 0, 1, 1, 1]], device=dummy_input.device, dtype=torch.long + ) + + outputs = model(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + outputs_fa = model_fa(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + + logits = outputs.decoder_hidden_states[-1] + logits_fa = outputs_fa.decoder_hidden_states[-1] + + # whisper FA2 needs very high tolerance + assert torch.allclose(logits_fa, logits, atol=4e-1) + + other_inputs = { + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + "output_hidden_states": True, + } + + outputs = model(dummy_input, **other_inputs) + outputs_fa = model_fa(dummy_input, **other_inputs) + + logits = outputs.decoder_hidden_states[-1] + logits_fa = outputs_fa.decoder_hidden_states[-1] + + # whisper FA2 needs very high tolerance + assert torch.allclose(logits_fa[:, -2:], logits[:, -2:], atol=4e-1) + + def _create_and_check_torchscript(self, config, inputs_dict): + if not self.test_torchscript: + return + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.torchscript = True + configs_no_init._attn_implementation = "eager" + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class) + + try: + model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward + input_features = inputs["input_features"] + decoder_input_ids = inputs["decoder_input_ids"] + decoder_attention_mask = inputs["decoder_attention_mask"] + # prepare `attention_mask` with shape (batch_size, sequence_length) + attention_mask = torch.ones( + input_features.shape[0], + input_features.shape[-1], + device=input_features.device, + dtype=input_features.dtype, + ) + traced_model = torch.jit.trace( + model, (input_features, attention_mask, decoder_input_ids, decoder_attention_mask) + ) + + except RuntimeError: + self.fail("Couldn't trace module.") + + with tempfile.TemporaryDirectory() as tmp_dir_name: + pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt") + + try: + torch.jit.save(traced_model, pt_file_name) + except Exception: + self.fail("Couldn't save module.") + + try: + loaded_model = torch.jit.load(pt_file_name) + except Exception: + self.fail("Couldn't load module.") + + model.to(torch_device) + model.eval() + + loaded_model.to(torch_device) + loaded_model.eval() + + model_state_dict = model.state_dict() + loaded_model_state_dict = loaded_model.state_dict() + + non_persistent_buffers = {} + for key in loaded_model_state_dict.keys(): + if key not in model_state_dict.keys(): + non_persistent_buffers[key] = loaded_model_state_dict[key] + + loaded_model_state_dict = { + key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers + } + + self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys())) + + model_buffers = list(model.buffers()) + for non_persistent_buffer in non_persistent_buffers.values(): + found_buffer = False + for i, model_buffer in enumerate(model_buffers): + if torch.equal(non_persistent_buffer, model_buffer): + found_buffer = True + break + + self.assertTrue(found_buffer) + model_buffers.pop(i) + + models_equal = True + for layer_name, p1 in model_state_dict.items(): + p2 = loaded_model_state_dict[layer_name] + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=5e-5, name="outputs", attributes=None): + # We override with a slightly higher tol value, as test recently became flaky + super().check_pt_tf_outputs(tf_outputs, pt_outputs, model_class, tol, name, attributes) + + def check_pt_flax_outputs(self, fx_outputs, pt_outputs, model_class, tol=5e-5, name="outputs", attributes=None): + # We override with a slightly higher tol value, as test recently became flaky + super().check_pt_flax_outputs(fx_outputs, pt_outputs, model_class, tol, name, attributes) + + @is_pt_flax_cross_test + def test_equivalence_pt_to_flax(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + init_shape = (1,) + inputs_dict["input_features"].shape[1:] + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + fx_model_class_name = "Flax" + model_class.__name__ + + if not hasattr(transformers, fx_model_class_name): + # no flax model exists for this class + return + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + fx_model_class = getattr(transformers, fx_model_class_name) + + # load PyTorch class + pt_model = model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + + # load Flax class + fx_model = fx_model_class(config, input_shape=init_shape, dtype=jnp.float32) + + # make sure only flax inputs are forward that actually exist in function args + fx_input_keys = inspect.signature(fx_model.__call__).parameters.keys() + + # prepare inputs + pt_inputs = self._prepare_for_class(inputs_dict, model_class) + + # remove function args that don't exist in Flax + pt_inputs = {k: v for k, v in pt_inputs.items() if k in fx_input_keys} + + # send pytorch inputs to the correct device + pt_inputs = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs.items() + } + + # convert inputs to Flax + fx_inputs = {k: np.array(v.to("cpu")) for k, v in pt_inputs.items() if torch.is_tensor(v)} + + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + # send pytorch model to the correct device + pt_model.to(torch_device) + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + fx_outputs = fx_model(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs, model_class) + + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = fx_model_class.from_pretrained(tmpdirname, input_shape=init_shape, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs_loaded.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs_loaded, pt_outputs, model_class) + + @is_pt_flax_cross_test + def test_equivalence_flax_to_pt(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + init_shape = (1,) + inputs_dict["input_features"].shape[1:] + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + fx_model_class_name = "Flax" + model_class.__name__ + + if not hasattr(transformers, fx_model_class_name): + # no flax model exists for this class + return + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + fx_model_class = getattr(transformers, fx_model_class_name) + + # load PyTorch class + pt_model = model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + + # load Flax class + fx_model = fx_model_class(config, input_shape=init_shape, dtype=jnp.float32) + + # make sure only flax inputs are forward that actually exist in function args + fx_input_keys = inspect.signature(fx_model.__call__).parameters.keys() + + # prepare inputs + pt_inputs = self._prepare_for_class(inputs_dict, model_class) + + # remove function args that don't exist in Flax + pt_inputs = {k: v for k, v in pt_inputs.items() if k in fx_input_keys} + + # send pytorch inputs to the correct device + pt_inputs = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs.items() + } + + # convert inputs to Flax + fx_inputs = {k: np.array(v.to("cpu")) for k, v in pt_inputs.items() if torch.is_tensor(v)} + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + + # make sure weights are tied in PyTorch + pt_model.tie_weights() + + # send pytorch model to the correct device + pt_model.to(torch_device) + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + fx_outputs = fx_model(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs, model_class) + + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = model_class.from_pretrained(tmpdirname, from_flax=True) + + # send pytorch model to the correct device + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs_loaded.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs_loaded, model_class) + + def test_mask_feature_prob(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.mask_feature_prob = 0.2 + config.mask_feature_length = 2 + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.train() + + # forward pass + encoder_last_hidden_state = model(**input_dict).encoder_last_hidden_state + self.assertTrue(encoder_last_hidden_state.shape, (13, 30, 16)) + + def test_mask_time_prob(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.mask_time_prob = 0.2 + config.mask_time_length = 2 + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.train() + + # forward pass + encoder_last_hidden_state = model(**input_dict).encoder_last_hidden_state + self.assertTrue(encoder_last_hidden_state.shape, (13, 30, 16)) + + def test_generate_with_prompt_ids_and_task_and_language(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = WhisperForConditionalGeneration(config).eval().to(torch_device) + input_features = input_dict["input_features"] + prompt_ids = np.arange(5) + language = "<|de|>" + task = "translate" + lang_id = 6 + task_id = 7 + model.generation_config.__setattr__("lang_to_id", {language: lang_id}) + model.generation_config.__setattr__("task_to_id", {task: task_id}) + + output = model.generate(input_features, max_new_tokens=5, task=task, language=language, prompt_ids=prompt_ids) + + expected_output_start = [ + *prompt_ids.tolist(), + model.generation_config.decoder_start_token_id, + lang_id, + task_id, + ] + for row in output.tolist(): + self.assertListEqual(row[: len(expected_output_start)], expected_output_start) + + def test_generate_with_prompt_ids_and_forced_decoder_ids(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = WhisperForConditionalGeneration(config).eval().to(torch_device) + input_features = input_dict["input_features"] + prompt_ids = np.asarray(range(5)) + forced_decoder_ids = [(1, 6), (2, 7), (3, 8)] + + output = model.generate( + input_features, max_new_tokens=5, forced_decoder_ids=forced_decoder_ids, prompt_ids=prompt_ids + ) + + expected_output_start = [ + *prompt_ids.tolist(), + model.generation_config.decoder_start_token_id, + *[token for _rank, token in forced_decoder_ids], + ] + for row in output.tolist(): + self.assertListEqual(row[: len(expected_output_start)], expected_output_start) + + def test_generate_with_prompt_ids_max_length(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.max_target_positions = 5 + + model = WhisperForConditionalGeneration(config).eval().to(torch_device) + input_features = input_dict["input_features"] + prompt_ids = np.asarray(range(4)) + sliced_prompt_ids = prompt_ids[1:] + sliced_prompt_ids = sliced_prompt_ids[-config.max_target_positions // 2 - 1 :] + max_new_tokens = 5 + + with self.assertRaisesRegex( + ValueError, + f"The length of the sliced `prompt_ids` is {len(sliced_prompt_ids)}, and the `max_new_tokens` " + f"{max_new_tokens}. Thus, the combined length of the sliced `prompt_ids` and `max_new_tokens` is: " + f"{len(sliced_prompt_ids) + max_new_tokens}. This exceeds the `max_target_positions` of the Whisper model: " + f"{config.max_target_positions}. You should either reduce the length of your prompt, or reduce the " + f"value of `max_new_tokens`, so that their combined length is less that {config.max_target_positions}.", + ): + model.generate(input_features, max_new_tokens=max_new_tokens, prompt_ids=prompt_ids) + + model.generate(input_features, max_new_tokens=1, prompt_ids=prompt_ids) + + def test_longform_generate_single_batch(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + + model = WhisperForConditionalGeneration(config).eval().to(torch_device) + input_features = input_dict["input_features"] + + # len = 250 with num_input_frames = 60 + long_input_features = torch.cat([input_features.repeat(1, 1, 4), input_features[:, :, :10]], dim=-1) + + # force bsz=1 + long_input_features = long_input_features[:1] + vocab_size = model.config.vocab_size + + batch_size = 1 + num_timestamp_tokens = 20 + max_length = 16 + logits_processor = [ + DummyTimestampLogitProcessor( + vocab_size - num_timestamp_tokens, + vocab_size, + batch_size=batch_size, + max_length=max_length, + min_space=4, + ) + ] + + # each chunk should not be longer than 10 + model.generation_config.max_length = max_length + + # if input features are long can't set return_timestamps to False + with self.assertRaises(ValueError): + _ = model.generate(long_input_features, logits_processor=logits_processor, return_timestamps=False) + + # if input features are long need to set generation config + with self.assertRaises(ValueError): + _ = model.generate(long_input_features, logits_processor=logits_processor) + + timestamp_begin = vocab_size - num_timestamp_tokens + model.generation_config.no_timestamps_token_id = timestamp_begin - 1 + model.generation_config.eos_token_id = None + model.generation_config._detect_timestamp_from_logprob = False + # make sure that we only have the same begin token + model.generation_config.max_initial_timestamp_index = 0 + + outputs = model.generate(long_input_features, logits_processor=logits_processor, return_segments=True) + + segments = outputs["segments"][0] + + for i, segment in enumerate(segments): + assert segment["start"] <= segment["end"], "start has to be smaller equal end" + assert ( + segment["tokens"][0] == model.generation_config.decoder_start_token_id + or segment["tokens"][0] >= timestamp_begin + ), "First segment token should be a timestamp token" + assert any( + s > timestamp_begin for s in segment["tokens"][1:] + ), f"At least one segment token should be a timestamp token, but not first., {segment['tokens']}" + assert ( + segment["tokens"].shape[-1] <= max_length + ), "make sure that no segment is larger than max generation length" + + def test_longform_generate_multi_batch(self): + config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() + + model = WhisperForConditionalGeneration(config).eval().to(torch_device) + input_features = input_dict["input_features"].to(torch_device) + + # len = 250 with num_input_frames = 60 + long_input_features = torch.cat([input_features.repeat(1, 1, 4), input_features[:, :, :10]], dim=-1) + long_input_features[:1, :, :200] + input_features_2 = long_input_features[1:] + attention_mask = torch.ones( + (2, long_input_features.shape[-1]), dtype=input_features.dtype, device=input_features.device + ) + attention_mask[0, 200:] = 0 + + # force bsz=1 + vocab_size = model.config.vocab_size + + batch_size = 1 + num_timestamp_tokens = 20 + max_length = 16 + timestamp_begin = vocab_size - num_timestamp_tokens + model.generation_config.no_timestamps_token_id = timestamp_begin - 1 + model.generation_config.eos_token_id = None + model.generation_config._detect_timestamp_from_logprob = False + # make sure that we only have the same begin token + model.generation_config.max_initial_timestamp_index = 0 + + logits_processor = [ + DummyTimestampLogitProcessor( + vocab_size - num_timestamp_tokens, + vocab_size, + batch_size=batch_size, + max_length=max_length, + min_space=4, + seed=1, + ) + ] + outputs_2 = model.generate(input_features_2, logits_processor=logits_processor, return_segments=True) + tokens_2 = outputs_2["sequences"][0] + segments_2 = outputs_2["segments"][0] + + batch_size = 2 + logits_processor = [ + DummyTimestampLogitProcessor( + vocab_size - num_timestamp_tokens, + vocab_size, + batch_size=batch_size, + max_length=max_length, + min_space=4, + seed=0, + ) + ] + outputs = model.generate( + long_input_features, attention_mask=attention_mask, logits_processor=logits_processor, return_segments=True + ) + tokens = outputs["sequences"][1] + segments = outputs["segments"][1] + + assert tokens_2.tolist() == tokens.tolist() + + for seg1, seg2 in zip(segments_2, segments): + assert seg1["start"] == seg2["start"] + assert seg1["end"] == seg2["end"] + assert seg1["tokens"].tolist() == seg2["tokens"].tolist() + + +@require_torch +@require_torchaudio +class WhisperModelIntegrationTests(unittest.TestCase): + @cached_property + def default_processor(self): + return WhisperProcessor.from_pretrained("openai/whisper-base") + + def _load_datasamples(self, num_samples): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + # automatic decoding with librispeech + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + + return [x["array"] for x in speech_samples] + + @slow + def test_tiny_logits_librispeech(self): + torch_device = "cpu" + set_seed(0) + model = WhisperModel.from_pretrained("openai/whisper-tiny") + model.to(torch_device) + input_speech = self._load_datasamples(1) + feature_extractor = WhisperFeatureExtractor() + input_features = feature_extractor(input_speech, return_tensors="pt").input_features + + with torch.no_grad(): + logits = model( + input_features, + decoder_input_ids=torch.tensor([[50258, 50259, 50359]]), + output_hidden_states=False, + output_attentions=False, + return_dict=False, + use_cache=False, + ) + + # fmt: off + EXPECTED_LOGITS = torch.tensor( + [ + 2.9892, -6.7607, 5.7348, 3.6096, 0.2152, -5.7321, 4.8855, -1.6407, + 0.2823, -1.5718, 10.4269, 3.4427, 0.0219, -8.0612, 3.4784, 8.4246, + 4.0575, -2.2864, 11.1084, 0.9963, 0.9884, -8.5154, -3.5469, -9.3713, + 0.9786, 3.5435, 7.4850, -5.2579, -1.4366, 10.4841 + ] + ) + # fmt: on + self.assertTrue(torch.allclose(logits[0][0, 0, :30].cpu(), EXPECTED_LOGITS, atol=1e-4)) + + # fmt: off + EXPECTED_GENERATION = torch.tensor( + [ + -1.4651, -2.6944, 2.7821, 2.3793, 4.0738, 0.0188, -3.3203, 1.9836, + 0.0520, 0.7095, 1.1063, 0.2952, -3.6786, -0.5249, 0.3105, 4.7691, + 1.1562, 1.3046, 0.5810, -0.3624, 1.7006, 1.3424, 0.9817, 2.1958, + 1.8775, -5.7046, -0.7679, 4.0113, 2.6848, 2.8609 + ] + ) + # fmt: on + + head_logits = logits[0] @ model.decoder.embed_tokens.weight.T + self.assertTrue(torch.allclose(head_logits[0, 0, :30].cpu(), EXPECTED_GENERATION, atol=1e-4)) + + @slow + def test_small_en_logits_librispeech(self): + set_seed(0) + torch_device = "cpu" + model = WhisperModel.from_pretrained("openai/whisper-small.en") + model.to(torch_device) + + input_speech = self._load_datasamples(1) + + feaure_extractor = WhisperFeatureExtractor() + input_features = feaure_extractor(input_speech, return_tensors="pt").input_features.to(torch_device) + + logits = model( + input_features, + decoder_input_ids=torch.tensor([[model.config.decoder_start_token_id]]), + output_hidden_states=False, + output_attentions=False, + use_cache=False, + ) + + logits = logits.last_hidden_state @ model.decoder.embed_tokens.weight.T + + # fmt: off + EXPECTED_LOGITS = torch.tensor( + [ + -3.6784, -7.7211, -9.5070, -11.9286, -7.6489, -9.7026, -5.6188, + -8.0104, -4.6238, -5.1833, -9.0485, -3.4079, -5.4874, -2.6935, + -6.3479, -7.3398, -6.9558, -7.6867, -7.4748, -8.3463, -9.9781, + -10.8389, -10.3105, -11.7201, -9.7261, -7.1590, -5.9272, -12.4509, + -11.1146, -8.1918 + ] + ) + # fmt: on + self.assertTrue(torch.allclose(logits[0, 0, :30].cpu(), EXPECTED_LOGITS, atol=1e-4)) + + @slow + def test_large_logits_librispeech(self): + set_seed(0) + + torch_device = "cpu" + model = WhisperModel.from_pretrained("openai/whisper-large") + model.to(torch_device) + + input_speech = self._load_datasamples(1) + + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + processed_inputs = processor( + audio=input_speech, text="This part of the speech", add_special_tokens=False, return_tensors="pt" + ) + input_features = processed_inputs.input_features.to(torch_device) + decoder_input_ids = processed_inputs.labels.to(torch_device) + + logits = model( + input_features, + decoder_input_ids=decoder_input_ids, + output_hidden_states=False, + output_attentions=False, + use_cache=False, + ) + + logits = logits.last_hidden_state @ model.decoder.embed_tokens.weight.T + + # fmt: off + EXPECTED_LOGITS = torch.tensor( + [ + 2.1382, 0.9381, 4.4671, 3.5589, 2.4022, 3.8576, -0.6521, 2.5472, + 1.8301, 1.9957, 2.3432, 1.4678, 0.5459, 2.2597, 1.5179, 2.5357, + 1.1624, 0.6194, 1.0757, 1.8259, 2.4076, 1.6601, 2.3503, 1.3376, + 1.9891, 1.8635, 3.8931, 5.3699, 4.4772, 3.9184 + ] + ) + # fmt: on + + self.assertTrue(torch.allclose(logits[0, 0, :30].cpu(), EXPECTED_LOGITS, atol=1e-4)) + + @slow + def test_tiny_en_generation(self): + torch_device = "cpu" + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + model.to(torch_device) + model.config.decoder_start_token_id = 50257 + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="pt").input_features.to( + torch_device + ) + + generated_ids = model.generate(input_features, num_beams=5, max_length=20) + transcript = processor.tokenizer.batch_decode(generated_ids)[0] + + EXPECTED_TRANSCRIPT = ( + "<|startoftranscript|><|notimestamps|> Mr. Quilter is the apostle of the middle" + " classes, and we are glad to" + ) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_tiny_generation(self): + torch_device = "cpu" + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + model.to(torch_device) + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="pt").input_features.to( + torch_device + ) + + generated_ids = model.generate(input_features, num_beams=5, max_length=20) + transcript = processor.tokenizer.decode(generated_ids[0]) + + EXPECTED_TRANSCRIPT = ( + "<|startoftranscript|><|en|><|transcribe|><|notimestamps|> Mr. Quilter is the apostle of the middle" + " classes and we are glad" + ) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_large_generation(self): + torch_device = "cpu" + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large") + model.to(torch_device) + + input_speech = self._load_datasamples(1) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="pt").input_features.to( + torch_device + ) + + generated_ids = model.generate( + input_features, do_sample=False, max_length=20, language="<|en|>", task="transcribe" + ) + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = " Mr. Quilter is the apostle of the middle classes and we are glad" + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_large_generation_multilingual(self): + torch_device = "cpu" + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large") + model.to(torch_device) + + ds = load_dataset("common_voice", "ja", split="test", streaming=True) + ds = ds.cast_column("audio", datasets.Audio(sampling_rate=16_000)) + input_speech = next(iter(ds))["audio"]["array"] + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="pt").input_features.to( + torch_device + ) + + generated_ids = model.generate( + input_features, do_sample=False, max_length=20, language="<|ja|>", task="transcribe" + ) + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = "木村さんに電話を貸してもらいました" + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + generated_ids = model.generate( + input_features, do_sample=False, max_length=20, language="<|en|>", task="transcribe" + ) + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = " Kimura-san called me." + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + generated_ids = model.generate( + input_features, do_sample=False, max_length=20, language="<|ja|>", task="translate" + ) + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + + EXPECTED_TRANSCRIPT = " I borrowed a phone from Kimura san" + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_large_batched_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-large") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large") + + input_speech = self._load_datasamples(4) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="pt").input_features + generated_ids = model.generate(input_features, max_length=20, task="translate") + + # fmt: off + EXPECTED_LOGITS = torch.tensor( + [ + [50258, 50259, 50358, 50363, 2221, 13, 2326, 388, 391, 307, 264, 50244, 295, 264, 2808, 5359, 293, 321, 366, 5404], + [50258, 50259, 50358, 50363, 6966, 307, 2221, 13, 2326, 388, 391, 311, 9060, 1570, 1880, 813, 702, 1871, 13, 50257], + [50258, 50259, 50358, 50363, 634, 5112, 505, 300, 412, 341, 42729, 3196, 295, 264, 1064, 11, 365, 5272, 293, 12904], + [50258, 50259, 50358, 50363, 634, 575, 12525, 22618, 1968, 6144, 35617, 20084, 1756, 311, 589, 307, 534, 10281, 934, 439] + ] + ) + # fmt: on + + self.assertTrue(torch.allclose(generated_ids, EXPECTED_LOGITS)) + + # fmt: off + EXPECTED_TRANSCRIPT = [ + " Mr. Quilter is the apostle of the middle classes and we are glad", + " Nor is Mr. Quilter's manner less interesting than his matter.", + " He tells us that at this festive season of the year, with Christmas and roast", + " He has grave doubts whether Sir Frederick Layton's work is really Greek after all", + ] + # fmt: on + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + self.assertListEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_tiny_en_batched_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + model.to(torch_device) + + input_speech = self._load_datasamples(4) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="pt").input_features.to( + torch_device + ) + generated_ids = model.generate(input_features, max_length=20).to("cpu") + + # fmt: off + EXPECTED_LOGITS = torch.tensor( + [ + [50257, 50362, 1770, 13, 2264, 346, 353, 318, 262, 46329, 286, 262, 3504, 6097, 11, 290, 356, 389, 9675, 284], + [50257, 50362, 5414, 318, 1770, 13, 2264, 346, 353, 338, 5642, 1342, 3499, 621, 465, 2300, 13, 50256, 50256, 50256], + [50257, 50362, 679, 4952, 514, 326, 379, 428, 43856, 1622, 286, 262, 614, 11, 351, 6786, 290, 32595, 12023, 28236], + [50257, 50362, 679, 468, 12296, 17188, 1771, 7361, 26113, 18881, 1122, 338, 670, 318, 1107, 8312, 706, 477, 290, 460] + ] + + ) + # fmt: on + + self.assertTrue(torch.allclose(generated_ids, EXPECTED_LOGITS)) + + # fmt: off + EXPECTED_TRANSCRIPT = [ + " Mr. Quilter is the apostle of the middle classes, and we are glad to", + " Nor is Mr. Quilter's manner less interesting than his matter.", + " He tells us that at this festive season of the year, with Christmas and roast beef looming", + " He has grave doubts whether Sir Frederick Layton's work is really Greek after all and can", + ] + # fmt: on + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True) + self.assertListEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_tiny_timestamp_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + model.to(torch_device) + + input_speech = np.concatenate(self._load_datasamples(4)) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="pt").input_features.to( + torch_device + ) + + generated_ids = model.generate(input_features, max_length=448, return_timestamps=True).to("cpu") + + EXPECTED_OUTPUT = torch.tensor([50258, 50259, 50359, 50364, 2221, 13, 2326, 388, 391, 307, 264, 50244, 295, 264, 2808, 5359, 11, 293, 321, 366, 5404, 281, 2928, 702, 14943, 13, 50692, 50692, 6966, 307, 2221, 13, 2326, 388, 391, 311, 9060, 1570, 1880, 813, 702, 1871, 13, 50926, 50926, 634, 5112, 505, 300, 412, 341, 42729, 3196, 295, 264, 1064, 11, 365, 5272, 293, 12904, 9256, 450, 10539, 51208, 51208, 949, 505, 11, 14138, 10117, 490, 3936, 293, 1080, 3542, 5160, 881, 26336, 281, 264, 1575, 13, 51552, 51552, 634, 575, 12525, 22618, 1968, 6144, 35617, 7354, 1292, 6, 589, 307, 534, 10281, 934, 439, 11, 293, 51836, 51836, 50257]) # fmt: skip + + self.assertTrue(torch.allclose(generated_ids, EXPECTED_OUTPUT)) + + EXPECTED_TRANSCRIPT = [ + { + "text": ( + " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel. Nor is" + " Mr. Quilter's manner less interesting than his matter. He tells us that at this festive season" + " of the year, with Christmas and roast beef looming before us, similarly drawn from eating and" + " its results occur most readily to the mind. He has grave doubts whether Sir Frederick Latins'" + " work is really Greek after all, and" + ), + "offsets": [ + { + "text": ( + " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel." + ), + "timestamp": (0.0, 6.5600000000000005), + }, + { + "text": " Nor is Mr. Quilter's manner less interesting than his matter.", + "timestamp": (6.5600000000000005, 11.24), + }, + { + "text": ( + " He tells us that at this festive season of the year, with Christmas and roast beef" + " looming" + ), + "timestamp": (11.24, 16.88), + }, + { + "text": ( + " before us, similarly drawn from eating and its results occur most readily to the mind." + ), + "timestamp": (16.88, 23.76), + }, + { + "text": ( + " He has grave doubts whether Sir Frederick Latins' work is really Greek after all, and" + ), + "timestamp": (23.76, 29.44), + }, + ], + } + ] + + transcript = processor.batch_decode(generated_ids, skip_special_tokens=True, output_offsets=True) + self.assertEqual(transcript, EXPECTED_TRANSCRIPT) + + @slow + def test_tiny_token_timestamp_generation(self): + set_seed(0) + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + model.to(torch_device) + model.generation_config.alignment_heads = [[2, 2], [3, 0], [3, 2], [3, 3], [3, 4], [3, 5]] + + input_speech = self._load_datasamples(4) + input_features = processor.feature_extractor(raw_speech=input_speech, return_tensors="pt").input_features.to( + torch_device + ) + + generate_outputs = model.generate( + input_features, max_length=448, return_timestamps=True, return_token_timestamps=True + ) + + self.assertEqual(generate_outputs.sequences.shape, generate_outputs.token_timestamps.shape) + + # fmt: off + EXPECTED_OUTPUT = torch.tensor([ + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4800, 0.8200, 0.9600, 1.1200, 1.1200, 1.2200, 1.5000, 1.7200, 2.0000, 2.3400, 2.5000, 2.6600, 3.1800, 3.5600, 3.6800, 3.8000, 4.1000, 4.3000, 4.5800, 4.9400, 5.3800, 12.4200, 12.8400, 26.9200, 26.9200, 26.9200, 26.9200, 26.9200, 26.9200, 26.9200, 26.9200, 26.9200, 26.9200, 26.9200, 26.9400, 26.9400, 26.9400, 26.9400, 29.8400 ], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.5200, 0.9000, 1.1400, 1.4200, 1.5200, 1.6800, 1.6800, 1.8800, 2.1000, 2.2200, 2.6200, 3.1400, 3.5800, 3.9600, 4.4000, 17.3000, 17.3000, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7200, 26.7400, 26.7400, 26.7400, 26.7400, 26.7400, 26.7400, 28.0000 ], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.7600, 1.0000, 1.4200, 1.8000, 1.9400, 2.1800, 2.5200, 3.0200, 3.3200, 3.5400, 3.9400, 4.5600, 4.9200, 5.2800, 5.5600, 5.9000, 6.1600, 6.3000, 6.4800, 6.4800, 6.6400, 7.8200, 7.9600, 8.2200, 8.6000, 8.9200, 9.2200, 9.5200, 9.7200, 10.0600, 10.5400, 10.8800, 11.2600, 11.5400, 11.7400, 12.0800, 15.6800, 15.6800], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.7400, 1.0400, 1.3200, 1.6800, 2.1400, 2.4800, 2.7800, 3.0800, 3.1600, 3.4000, 3.6000, 4.0200, 4.2200, 4.8600, 5.2400, 5.7400, 6.3400, 6.6200, 6.7600, 6.7600, 6.8600, 7.2400, 7.4200, 7.6800, 7.9200, 8.4800, 8.7600, 9.2000, 9.2000, 9.4200, 15.8200, 15.8200, 29.6400, 29.6600, 29.6600, 29.6600, 29.6600, 29.7600] + ]) + # fmt: on + + self.assertTrue(torch.allclose(generate_outputs.token_timestamps.to("cpu"), EXPECTED_OUTPUT)) + + @slow + def test_tiny_specaugment_librispeech(self): + torch_device = "cpu" + set_seed(0) + # Apply SpecAugment + model = WhisperModel.from_pretrained("openai/whisper-tiny", apply_spec_augment=True) + # Set model to training mode to enable SpecAugment + model.train() + model.to(torch_device) + input_speech = self._load_datasamples(1) + feature_extractor = WhisperFeatureExtractor() + input_features = feature_extractor(input_speech, return_tensors="pt").input_features + + with torch.no_grad(): + logits = model( + input_features, + decoder_input_ids=torch.tensor([[50258, 50259, 50359]]), + output_hidden_states=False, + output_attentions=False, + return_dict=False, + use_cache=False, + ) + + # fmt: off + EXPECTED_LOGITS = torch.tensor( + [ + 0.9362, -4.7105, 5.0879, 3.9642, 1.0013, -6.0096, 4.7285, -3.1847, + -0.8648, 1.9631, 6.2653, 3.6936, 0.3575, -4.5818, 3.0564, 7.8712, + 2.9951, 0.6848, 9.9497, -2.6638, 1.1571, -6.8546, -1.4333, -7.7584, + 1.1200, 3.9030, 4.4655, -4.4919, -1.1703, 9.6241 + ] + ) + # fmt: on + self.assertTrue(torch.allclose(logits[0][0, 0, :30].cpu(), EXPECTED_LOGITS, atol=1e-4)) + + @slow + def test_generate_with_prompt_ids(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + model.to(torch_device) + input_speech = self._load_datasamples(4)[-1:] + input_features = processor(input_speech, return_tensors="pt").input_features.to(torch_device) + + output_without_prompt = model.generate(input_features) + prompt_ids = processor.get_prompt_ids("Leighton") + output_with_prompt = model.generate(input_features, prompt_ids=prompt_ids) + + expected_without_prompt = "<|startoftranscript|><|en|><|transcribe|><|notimestamps|> He has grave doubts whether Sir Frederick Layton's work is really Greek after all and can discover in it but little of Rocky Ithaca.<|endoftext|>" + expected_with_prompt = "<|startofprev|> Leighton<|startoftranscript|><|en|><|transcribe|><|notimestamps|> He has grave doubts whether Sir Frederick Leighton's work is really Greek after all and can discover in it but little of Rocky Ithaca.<|endoftext|>" + self.assertEqual(processor.decode(output_without_prompt[0]), expected_without_prompt) + self.assertEqual(processor.decode(output_with_prompt[0]), expected_with_prompt) + + @slow + def test_generate_with_prompt_ids_and_forced_decoder_ids(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + model.to(torch_device) + input_speech = self._load_datasamples(1) + input_features = processor(input_speech, return_tensors="pt").input_features.to(torch_device) + task = "translate" + language = "de" + expected_tokens = [f"<|{task}|>", f"<|{language}|>"] + prompt = "test prompt" + prompt_ids = processor.get_prompt_ids(prompt) + + output = model.generate(input_features, task=task, language=language, prompt_ids=prompt_ids) + text = processor.decode(output[0]) + + self.assertTrue(prompt in text) + self.assertTrue(all(token in text for token in expected_tokens)) + + @slow + def test_generate_with_prompt_ids_and_no_non_prompt_forced_decoder_ids(self): + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + model.to(torch_device) + input_speech = self._load_datasamples(1) + input_features = processor(input_speech, return_tensors="pt").input_features.to(torch_device) + prompt = "test prompt" + prompt_ids = processor.get_prompt_ids(prompt) + + model.generation_config.forced_decoder_ids = None + model.config.forced_decoder_ids = None + + output = model.generate(input_features, prompt_ids=prompt_ids, return_timestamps=True) + text = processor.decode(output[0]) + + self.assertTrue(prompt in text) + + @slow + @require_torch_gpu + def test_speculative_decoding_distil(self): + torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32 + model_id = "openai/whisper-large-v2" + model = WhisperForConditionalGeneration.from_pretrained( + model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True + ) + model.to(torch_device) + + processor = WhisperProcessor.from_pretrained(model_id) + + assistant_model_id = "distil-whisper/distil-large-v2" + assistant_model = WhisperForCausalLM.from_pretrained( + assistant_model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True + ) + assistant_model.to(torch_device) + + dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + sample = dataset[0]["audio"] + + input_features = processor(sample["array"], return_tensors="pt").input_features.to("cuda").to(torch.float16) + + # warm up assisted decoding + _ = model.generate(input_features, assistant_model=assistant_model) + # warm up non-assisted decoding + _ = model.generate(input_features) + + # assisted decoding + start_time = time.time() + tokens = model.generate(input_features, assistant_model=assistant_model) + total_time_assist = time.time() - start_time + + transcription_ass = processor.batch_decode(tokens, skip_special_tokens=True) + + # non-assisted decoding + start_time = time.time() + tokens = model.generate(input_features) + total_time_non_assist = time.time() - start_time + + transcription_non_ass = processor.batch_decode(tokens, skip_special_tokens=True) + + assert transcription_ass == transcription_non_ass + assert transcription_ass == [ + " Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel." + ] + assert total_time_non_assist > total_time_assist, "Make sure that assistant decoding is faster" + + @slow + @require_torch_gpu + def test_speculative_decoding_non_distil(self): + torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32 + model_id = "openai/whisper-large-v2" + model = WhisperForConditionalGeneration.from_pretrained( + model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True + ) + model.to(torch_device) + + processor = WhisperProcessor.from_pretrained(model_id) + + assistant_model_id = "openai/whisper-tiny" + assistant_model = WhisperForConditionalGeneration.from_pretrained( + assistant_model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True + ) + assistant_model.to(torch_device) + + dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + sample = dataset[0]["audio"] + + input_features = processor(sample["array"], return_tensors="pt").input_features.to("cuda").to(torch.float16) + + # warm up assisted decoding + _ = model.generate(input_features, assistant_model=assistant_model) + # warm up non-assisted decoding + _ = model.generate(input_features) + + # assisted decoding + start_time = time.time() + tokens = model.generate(input_features, assistant_model=assistant_model) + total_time_assist = time.time() - start_time + + transcription_ass = processor.batch_decode(tokens, skip_special_tokens=True) + + # non-assisted decoding + start_time = time.time() + tokens = model.generate(input_features) + total_time_non_assist = time.time() - start_time + + transcription_non_ass = processor.batch_decode(tokens, skip_special_tokens=True) + + assert transcription_ass == transcription_non_ass + assert transcription_ass == [ + " Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel." + ] + assert total_time_non_assist > total_time_assist, "Make sure that assistant decoding is faster" + + @slow + def test_whisper_longform_single_batch(self): + # fmt: off + EXPECTED_TEXT = [' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel. Nor is Mr. Quilter\'s manner less interesting than his matter. He tells us that at this festive season of the year, with Christmas and roast beef looming before us, similes drawn from eating and its results occur most readily to the mind. He has grave doubts whether Sir Frederick Layton\'s work is really Greek after all, and can discover in it but little of rocky Ithaca. Linnell\'s pictures are a sort of up-gards and atom paintings, and Mason\'s exquisite idles are as national as a jingo poem. Mr. Birk at Foster\'s landscapes smile at one much in the same way that Mr. Carker used to flash his teeth. Mr. John Collier gives his sitter a cheerful slap in the back, before he says, like a shampoo or a Turkish bath. Next man, it is obviously unnecessary for us to point out how luminous these criticisms are, how delicate an expression. On the general principles of art, Mr. Quilter writes with equal lucidity. he tells us is of a different quality to mathematics, and finish in art is adding more effect. As for etchings, there are two kinds, British and foreign. He laments most bitterly the divorce that has been made between decorative art and what we usually call pictures. Makes the customary appeal to the last judgment and reminds us that in the great days of art Michelangelo was the furnishing upholsterer. Near the fire, any ornaments Fred brought home from India on the mantelboard. In fact, he is quite severe on Mr. Ruskin for not recognizing that a picture should denote the frailty of man. And remarks was pleasing courtesy in Felicitis Grace that many faces are feeling. Only, unfortunately, his own work never does get good. Mr. Quilter has missed his chance, for he has failed even to make himself the Tupper of painting. By Harry Quilter M.A. A man said to the universe, Sir, I exist. Sweat-covered Breon\'s body trickling into the tight-lowing cloth that was the only german he wore. The cut on his chest still dripping blood. The ache of his overstrained eyes, even the soaring arena around him with thousands of spectators, retrovealities not worth thinking about. His instant panic was followed by a small sharp blow high on his chest. One minute, a voice said, and a time buzzer sounded. A minute is not a very large measure of time, and his body needed every fraction of it. The buzzers were triggered his muscles into complete relaxation. Oli\'s heart and lungs worked on at a strong, measured rate. He was in reverie, sliding along the borders of consciousness. The contestants in the twenties needed undisturbed rest. Therefore, nights in the dormitories were as quiet as death. Particularly so, on this last night, when only two of the little cubicles were occupied, The thousands of others standing with dark empty doors. The other voice snapped with a harsh urgency, clearly used to command. I\'m here because the matter is of utmost importance, and brand is the one I must see. Now stand aside. The twenties, he must have drawn his gun because the intruder said quickly, but that away you\'re being a fool. out, through his silence then, and still wondering, Breon was once more asleep. Ten seconds, he asked the handler who was needing his aching muscles. A red-haired mountain of a man, with an apparently inexhaustible store of energy. There could be little art in this last and final round of fencing. Just thrust and parry, and victory to the stronger. man who entered the twenties had his own training tricks. They were appeared to be an immediate association with the death trauma, as if the two were inextricably linked into one. The strength that enables someone in a trance to hold his body stiff and unsupported except at two points, the head and heels. This is physically impossible when conscious. had died before during the 20s and death during the last round was in some ways easier than defeat. Breathing deeply, Breon\'s softly spoke the auto-hypnotic phrases that triggered the process. When the buzzer sounded, he pulled his foil from his second startled grasp and ran forward. Our role looked amazed at the sudden fury of the attack, then smiled. He thought it was the last burst of energy. He knew how close they both were to exhaustion. Breon saw something close to panic on his opponent\'s face when the man finally recognized his error. A wave of despair rolled out from our rogue. Breon sensed it and knew the fifth point was his. Then the powerful twist that\'s rested aside, in and under the guard, because he was sleeping instead of conquering, the lovely rose princess has become a fiddle without a bow, while poor Shaggy sits there, accooing dove. He has gone, and gone for good," answered Polychrom, who had managed to squeeze into the room beside the dragon, and had witnessed the occurrences with much interest. I have remained a prisoner only because I wished to be one. And with says he stepped forward and burst the stout chains as easily as if they had been threads. The little girl had been asleep, but she heard the wraps and opened the door. The king has flooded disgrace, and your friends are asking for you. I begged Ruggadot long ago to send him away, but he would not do so. I also offered to help your brother to escape, but he would not go. He eats and sleeps very steadily, replied the new king. I hope he doesn\'t work too hard, said Shaggy. He doesn\'t work at all. In fact, there\'s nothing he can do in these dominions as well as our gnomes, whose numbers are so great that it worries us to keep them all busy. Not exactly, we\'ve turned Calico. Where is my brother now, inquired Shaggy. In the metal forest. Where is that? The middle forest is in the great domed cavern, the largest and all-ard dominions, replied Calico. Calico hesitated. However, if we look sharp, we may be able to discover one of these secret ways. Oh no, I\'m quite sure he didn\'t. That\'s funny, remarked Betsy thoughtfully. I don\'t believe Anne knew any magic, or she\'d have worked it before. I do not know, confess Shaggy. True, agreed Calico. Calico went to the big gong and pounded on it just as Virgato used to do, but no one answered the summons. Having returned to the Royal Cavern, Calico first pounded the gong and then sat in the throne, wearing Virgato\'s discarded ruby crown and holding in his hand to scepter which reggative head so often thrown at his head.'] + # fmt: on + + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + model = model.to("cuda") + + ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean") + one_audio = np.concatenate([x["array"] for x in ds["validation"]["audio"]], dtype=np.float32) + + input_features = processor(one_audio, return_tensors="pt", truncation=False, padding="longest")[ + "input_features" + ] + input_features = input_features.to(device="cuda") + + result = model.generate(input_features, return_timestamps=True) + decoded = processor.batch_decode(result, skip_special_tokens=True) + + assert decoded == EXPECTED_TEXT + + @slow + def test_whisper_longform_multi_batch(self): + # fmt: off + EXPECTED_TEXT_1 = [" Mr. Quilter's manner less interesting than his matter. He tells us that at this festive season of the year, with Christmas and roast beef looming before us, similes drawn from eating and its results occur most readily to the mind. He has grave doubts whether Sir Frederick Layton's work is really Greek after all, and can discover in it but little of rocky Ithaca. Linnell's pictures are a sort of up-gards and atom paintings, and Mason's exquisite idles are as national as a jingo poem. Mr. Birkett Foster's landscapes smile at one much in the same way that Mr. Carker used to flash his teeth. And Mr. John Collier gives his sitter a cheerful slap in the back, before he says, like a shampooer and a Turkish bath. Next man, it is obviously unnecessary for us to point out how luminous these criticisms are, how delicate an expression. On the general principles of art, Mr. Quilter writes with equal lucidity. Painting he tells us is of a different quality to mathematics, and finish in art is adding more effect. As for etchings, there are two kinds, British and foreign. He laments most bitterly the divorce that has been made between decorative art and what we usually call pictures. Mix a customary appeal to the last judgment and reminds us that in the great days of art Michelangelo was the furnishing a poster or near the fire, and the ornaments Fred brought home from India on the mental board. In fact, he is quite severe on Mr. Ruskin for not recognizing that a picture should denote the frailty of man. And remarks was pleasing courtesy in Felicitis Grace that many faces are feeling. Only unfortunately his own work never does get good. Mr. Quilter has missed his chance, for he has failed even to make himself the Tupper of painting. a Harry Quilter M.A. A man said to the universe, Sir, I exist. Sweat-covered Breon's body trickling into the tight-wing cloth that was the only germany war. The cut on his chest still dripping blood. The ache of his overstrained eyes, even the soaring arena around him with thousands of spectators, retrovealities not worth thinking about. His instant panic was followed by a small sharp blow high on his chest. One minute, a voice said, and a time buzzer sounded. A minute is not a very large measure of time, and his body needed every fraction of it. The buzzers were, triggered his muscles into complete relaxation. Oily his heart and lungs worked on at a strong, measured rate. He was in reverie, sliding along the borders of consciousness. The contestants in the 20s needed undisturbed rest. Therefore, knights in the dormitories were as quiet as death. Particularly so, on this last night, when only two of the little cubicles were occupied, the thousands of others standing with dark empty doors. The other voice snapped with a harsh urgency, clearly used to command. I'm here because the matter is of utmost importance, and brand is the one I must see. Now stand aside. The twenty's he must have drawn his gun, because the intruder said quickly, but that away you're being a fool. Out there was silence then, and still wondering, Breon was once more asleep. Ten seconds he asked the handler who was needing his aching muscles. a red-haired mountain of a man with an apparently inexhaustible store of energy. There could be little art in this last and final round of fencing, just thrust and parry and victory to the stronger. Every man who entered the twenties had his own training tricks. There appeared to be an immediate association with the death trauma as if the two were andextricably linked into one. The strength that enables someone in a trance to hold his body stiff and unsupported except at two points, the head and heels. This is physically impossible when conscious. Others had died before during the twenties and death during the last round was, in some ways, easier than defeat. Breeding deeply, Breon's softly spoke the auto-hypnotic phrases that triggered the process. When the buzzer sounded, he pulled his foil from his second startled grasp and ran forward. I rolled the mazed at the sudden fury of the attack, then smiled. He thought it was the last burst of energy. He knew how close they both were to exhaustion. Breon saw something close to panic on his opponent's face when the man finally recognized his error. A wave of despair rolled out from our rogue, pre-inscented and new to fifth point was his. Then the powerful twist that's rest of the side, in and under the guard, because you were sleeping instead of conquering, the lovely rose princess has become a fiddle without a bow, while poor Shaggy sits there, a cooing dove. He has gone and gone for good, answered Polychrome, who had managed to squeeze into the room beside the dragon, and had witnessed the occurrences with much interest. I have remained a prisoner only because I wished to be one. And with this, he stepped forward and burst the stout chains as easily as if they had been threads. The little girl had been asleep, but she heard the wraps and opened the door. The king has flooded disgrace, and your friends are asking for you. I begged Ruggadot long ago to send him away, but he would not do so. I also offered to help your brother to escape, but he would not go. He eats and sleeps very steadily, replied the new king. I hope he doesn't work too hard, since Shaggy. He doesn't work at all. In fact, there's nothing he can do in these dominions, as well as our gnomes, whose numbers are so great that it worries us to keep them all busy. Not exactly, return Calico. Where is my brother now? choir-dshaggy, in the metal forest. Where is that? The metal forest is in the great domed cavern, the largest and all-ard dominions, replied Calico. Calico hesitated. However, if we look sharp, we may be able to discover one of these secret ways. Oh, no, I'm quite sure he didn't. That's funny, remarked Betsy thoughtfully. I don't believe and knew any magic, or she'd have worked it before. I do not know, confess shaggy. True, a great calico. Calico went to the big gong and pounded on it, just as Virgado used to do, but no one answered the summons. Having returned to the Royal Cavern, Calico first pounded the gong and then sat in the throne, wearing Virgados discarded Ruby Crown, and holding in his hand to scepter, which Virgado had so often thrown at his head. head."] + EXPECTED_TEXT_2 = [" Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel. Nor is Mr. Quilter's manner less interesting than his matter. He tells us that at this festive season of the year, with Christmas and roast beef looming before us, similes drawn from eating and its results occur most readily to the mind. He has grave doubts whether Sir Frederick Layton's work is really Greek after all, and can discover in it but little of rocky Ithaca. Linnell's pictures are a sort of up-gards and atom paintings, and Mason's exquisite idles are as national as a jingo poem. Mr. Burkett Foster's landscapes smile at one much in the same way that Mr. Carker."] + EXPECTED_TEXT_3 = [" possible. Nor is Mr. Quilter's manner less interesting than his matter. He tells us that at this festive season of the year, with Christmas and roast beef looming before us, similes drawn from eating and its results occur most readily to the mind. He has grieved doubts whether Sir Frederick Layton's work is really greek after all, and can discover in it but little of rocky Ithaca. Linnell's pictures are a sort of up-guards and atom paintings, and Mason's exquisite idles are as national as a jingo poem. Mr. Birk at Foster's landscapes smile at one much in the same way that Mr. Carker used to flash his teeth. And Mr. John Collier gives his sitter a cheerful slap in the back, before he says, like a shampooer and a Turkish bath, next man, it is obviously unnecessary for us to point out how luminous these criticisms are, how delicate an expression. Under general principles of art, Mr. Quilter writes with equal lucidity. Painting, he tells us, is of a different quality to mathematics and finish in art is adding more effect. As for etchings, there are two kinds, British and foreign. He laments most bitterly the divorce that has been made between decorative art and what we usually call pictures. Mix a customary appeal to the last judgment and reminds us that in the great days of art Michelangelo was the furnishing upholsterer. Near the fire. any ornaments Fred brought home from India on the mental board. In fact, he is quite severe on Mr. Ruskin for not recognizing that a picture should denote the frailty of man, and remarks was pleasing courtesy in Felicitis Grace that many faces are feeling. Only, unfortunately, his own work never does get good. Mr. Quilter has missed his chance, for he has failed even to make himself the tupper of painting. By Harry Quilter M.A. A man said to the universe, Sir, I exist. Sweat-covered Breon's body trickling into the titling cloth that was the only german he wore. The cut on his chest still dripping blood. The ache of his overstrained eyes. Even to soaring arena around him with thousands of spectators, retrovealities not worth thinking about. His instant panic was followed by a small sharp blow high on his chest. One minute, a voice said, and a time buzzer sounded. A minute is not a very large measure of time, and his body needed every fraction of it. The buzzers were triggered as muscles into complete relaxation. Oily his heart and lungs worked on at a strong measured rate. He was in In reverie, sliding along the borders of consciousness. The contestants in the 20s needed undisturbed rest. Therefore, nights in the dormitories were as quiet as death. Particularly so, on this last night, when only two of the little cubicles were occupied, the thousands of others standing with dark empty doors. The other voice snapped with a harsh urgency clearly used to command. I'm here because the matter is of utmost importance, and brand is the one I must see. Now stand aside. The twenty's he must have drawn his gun, because the intruder said quickly, but that away you're being a fool. Out there was silence then, and still wondering, Breon was once more asleep. Ten seconds he asked the handler who was needing his aching muscles. a red-haired mountain of a man with an apparently inexhaustible store of energy. There could be little art in this last and final round of fencing, just thrust and parry and victory to the stronger. Every man who entered the twenties had his own training tricks. There appeared to be an immediate association with the death trauma as if the two were andextricably linked into one. The strength that enables someone in a trance to hold his body stiff and unsupported except at two points, the head and heels. This is physically impossible when conscious. Others had died before during the twenties and death during the last round was, in some ways, easier than defeat. Breeding deeply, Breon's softly spoke the auto-hypnotic phrases that triggered the process. When the buzzer sounded, he pulled his foil from his second startled grasp and ran forward. Our role looked amazed at the sudden fury of the attack, then smiled. He thought it was the last burst of energy. He knew how close they both were to exhaustion. Breon saw something close to panic on his opponent's face when the man finally recognized his error. A wave of despair rolled out from our rogue, re-insunced it and knew the fifth point was his. Then the powerful twist that's rest of the side, in and under the guard, because you were sleeping instead of conquering, the lovely rose princess has become a fiddle without a bow, while poor Shaggy sits there, a cooing dove. He has gone and gone for good, answered Polychrome, who had managed to squeeze into the room beside the dragon, and had witnessed the occurrences with much interest. I have remained a prisoner only because I wished to be one. And with this, he stepped forward and burst the stout chains as easily as if they had been threads. The little girl had been asleep, but she heard the wraps and opened the door. The king has fled and disgraced, and your friends are asking for you. I begged Ruggadot long ago to send him away, but he would not do so. I also offered to help your brother to escape, but he would not go. He eats and sleeps very steadily, replied the new king. I hope he doesn't work too hard, since Shaggy. He doesn't work at all. In fact, there's nothing he can do in these dominions as well as our gnomes, whose numbers are so great that it worries us to keep them all busy. Not exactly, we've turned Calico. Where is my brother now? quared shaggy. In the metal forest. Where is that? The metal forest is in the great domed cavern, the largest and all-ard dominions, replied Calico. Calico hesitated. However, if we look sharp, we may be able to discover one of these secret ways. Oh no, I'm quite sure he didn't. And that's funny, remarked Betsy thoughtfully. I don't believe Anne knew any magic, or she'd have worked it before. I do not know, confess Shaggy. True, a great calico. Calico went to the big gong and pounded on it, just as we're good to have used to do, but no one answered the summons. Having returned to the Royal Cavern, Calico first pounded the gong and then sat in the thrown wearing ruggedos discarded ruby crown and holding in his hand to septor which Ruggato had so often thrown at his head."] + EXPECTED_TEXT_4 = [' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel. Nor is Mr. Quilter\'s manner less interesting than his matter. He tells us that at this festive season of the year, with Christmas and roast beef looming before us, similes drawn from eating and its results occur most readily to the mind. He has grave doubts whether Sir Frederick Layton\'s work is really Greek after all, and can discover in it but little of rocky Ithaca. Linnell\'s pictures are a sort of up-gards and atom paintings, and Mason\'s exquisite idles are as national as a jingo poem. Mr. Birk at Foster\'s landscapes smile at one much in the same way that Mr. Carker used to flash his teeth. Mr. John Collier gives his sitter a cheerful slap in the back, before he says, like a shampoo or a Turkish bath. Next man, it is obviously unnecessary for us to point out how luminous these criticisms are, how delicate an expression. On the general principles of art, Mr. Quilter writes with equal lucidity. he tells us is of a different quality to mathematics, and finish in art is adding more effect. As for etchings, there are two kinds, British and foreign. He laments most bitterly the divorce that has been made between decorative art and what we usually call pictures. Makes the customary appeal to the last judgment and reminds us that in the great days of art Michelangelo was the furnishing upholsterer. Near the fire, any ornaments Fred brought home from India on the mantelboard. In fact, he is quite severe on Mr. Ruskin for not recognizing that a picture should denote the frailty of man. And remarks was pleasing courtesy in Felicitis Grace that many faces are feeling. Only, unfortunately, his own work never does get good. Mr. Quilter has missed his chance, for he has failed even to make himself the Tupper of painting. By Harry Quilter M.A. A man said to the universe, Sir, I exist. Sweat-covered Breon\'s body trickling into the tight-lowing cloth that was the only german he wore. The cut on his chest still dripping blood. The ache of his overstrained eyes, even the soaring arena around him with thousands of spectators, retrovealities not worth thinking about. His instant panic was followed by a small sharp blow high on his chest. One minute, a voice said, and a time buzzer sounded. A minute is not a very large measure of time, and his body needed every fraction of it. The buzzers were triggered his muscles into complete relaxation. Oli\'s heart and lungs worked on at a strong, measured rate. He was in reverie, sliding along the borders of consciousness. The contestants in the twenties needed undisturbed rest. Therefore, nights in the dormitories were as quiet as death. Particularly so, on this last night, when only two of the little cubicles were occupied, The thousands of others standing with dark empty doors. The other voice snapped with a harsh urgency, clearly used to command. I\'m here because the matter is of utmost importance, and brand is the one I must see. Now stand aside. The twenties, he must have drawn his gun because the intruder said quickly, but that away you\'re being a fool. out, through his silence then, and still wondering, Breon was once more asleep. Ten seconds, he asked the handler who was needing his aching muscles. A red-haired mountain of a man, with an apparently inexhaustible store of energy. There could be little art in this last and final round of fencing. Just thrust and parry, and victory to the stronger. man who entered the twenties had his own training tricks. They were appeared to be an immediate association with the death trauma, as if the two were inextricably linked into one. The strength that enables someone in a trance to hold his body stiff and unsupported except at two points, the head and heels. This is physically impossible when conscious. had died before during the 20s and death during the last round was in some ways easier than defeat. Breathing deeply, Breon\'s softly spoke the auto-hypnotic phrases that triggered the process. When the buzzer sounded, he pulled his foil from his second startled grasp and ran forward. Our role looked amazed at the sudden fury of the attack, then smiled. He thought it was the last burst of energy. He knew how close they both were to exhaustion. Breon saw something close to panic on his opponent\'s face when the man finally recognized his error. A wave of despair rolled out from our rogue. Breon sensed it and knew the fifth point was his. Then the powerful twist that\'s rested aside, in and under the guard, because he was sleeping instead of conquering, the lovely rose princess has become a fiddle without a bow, while poor Shaggy sits there, accooing dove. He has gone, and gone for good," answered Polychrom, who had managed to squeeze into the room beside the dragon, and had witnessed the occurrences with much interest. I have remained a prisoner only because I wished to be one. And with says he stepped forward and burst the stout chains as easily as if they had been threads. The little girl had been asleep, but she heard the wraps and opened the door. The king has flooded disgrace, and your friends are asking for you. I begged Ruggadot long ago to send him away, but he would not do so. I also offered to help your brother to escape, but he would not go. He eats and sleeps very steadily, replied the new king. I hope he doesn\'t work too hard, said Shaggy. He doesn\'t work at all. In fact, there\'s nothing he can do in these dominions as well as our gnomes, whose numbers are so great that it worries us to keep them all busy. Not exactly, we\'ve turned Calico. Where is my brother now, inquired Shaggy. In the metal forest. Where is that? The middle forest is in the great domed cavern, the largest and all-ard dominions, replied Calico. Calico hesitated. However, if we look sharp, we may be able to discover one of these secret ways. Oh no, I\'m quite sure he didn\'t. That\'s funny, remarked Betsy thoughtfully. I don\'t believe Anne knew any magic, or she\'d have worked it before. I do not know, confess Shaggy. True, agreed Calico. Calico went to the big gong and pounded on it just as Virgato used to do, but no one answered the summons. Having returned to the Royal Cavern, Calico first pounded the gong and then sat in the throne, wearing Virgato\'s discarded ruby crown and holding in his hand to scepter which reggative head so often thrown at his head.'] + # fmt: on + + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + model = model.to("cuda") + + ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean") + one_audio = np.concatenate([x["array"] for x in ds["validation"]["audio"]], dtype=np.float32) + audios = [] + audios.append(one_audio[110000:]) + audios.append(one_audio[:800000]) + audios.append(one_audio[80000:]) + audios.append(one_audio[:]) + + decoded_single = [] + for audio in audios: + inputs = processor(audio, return_tensors="pt", truncation=False) + inputs = inputs.to(device="cuda") + + result = model.generate(**inputs, return_timestamps=True) + decoded_single.append(processor.batch_decode(result, skip_special_tokens=True)) + + inputs = processor( + audios, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True + ) + inputs = inputs.to(device="cuda") + + result = model.generate(**inputs, return_timestamps=True) + decoded_all = processor.batch_decode(result, skip_special_tokens=True) + + # make sure single & batch is exactly the same + assert decoded_all[0:1] == decoded_single[0] + assert decoded_all[1:2] == decoded_single[1] + assert decoded_all[2:3] == decoded_single[2] + assert decoded_all[3:4] == decoded_single[3] + + # exact match + assert decoded_all[0:1] == EXPECTED_TEXT_1 + assert decoded_all[1:2] == EXPECTED_TEXT_2 + assert decoded_all[2:3] == EXPECTED_TEXT_3 + assert decoded_all[3:4] == EXPECTED_TEXT_4 + + @slow + def test_whisper_longform_multi_batch_hard(self): + # fmt: off + EXPECTED_TEXT = [ + " Folks, if you watch the show, you know, I spent a lot of time right over there. Patiently and astutely scrutinizing the boxwood and mahogany chest set of the day's biggest stories developing the central headline pawns, definitely maneuvering an oso topical night to F6, fainting a classic Sicilian, nade door variation on the news, all the while seeing eight moves deep and patiently marshalling the latest press releases into a fisher's shows in Lip Nitsky attack that culminates in the elegant lethal slow-played, all-passant checkmate that is my nightly monologue. But sometimes, sometimes, folks, I. CHEERING AND APPLAUSE Sometimes I startle away, cubside down in the monkey bars of a condemned playground on a super fun site. Get all hept up on goofballs. Rummage that were discarded tag bag of defective toys. Yank out a fist bowl of disembodied doll limbs, toss them on a stained kid's place mat from a defunct dennies. set up a table inside a rusty cargo container down by the Wharf and challenged toothless drifters to the godless bughouse blitz of tournament that is my segment. Meanwhile!", + " Folks, I spend a lot of time right over there, night after night after night, actually. Carefully selecting for you the day's noosiest, most aerodynamic headlines, stress testing, and those topical anti-lock breaks and power steering, painstakingly stitching, leather seating so soft, it would make JD power and her associates blush to create the luxury sedan that is my nightly monologue. But sometimes, you sometimes, folks. I lurched a consciousness in the back of an abandoned school and slap myself awake with a crusty floor mat. Before using a mouse-bitten timing belt to strap some old plywood to a couple of discarded oil drums, then by the light of a heathen moon, render a gas tank out of an empty big gulp, fill with white claw and denatured alcohol, then light a match and let her rip and the demented one man soapbox derby of news that is my segment. Me, Guadalupe! No!", + " Ladies and gentlemen, you know, I spent a lot of time right over there Raising the finest Holstein news cattle firmly yet tenderly milking the latest headlines from their jokes swollen teats Churning the daily stories into the decadent proven-style style triple cream breed that is my nightly monologue But sometimes sometimes folks I stagger home hungry after being released by the police and Root around in the neighbor's trash can for an old milk carton scrape out the blooming dairy residue into the remains of a wet cheese rod I won from a rat in a pre-donned street fight. Put it in a discarded paint can to leave it to ferment next to a trash fire then hunker down and hallucinate while eating the listeria laden demon custard of news that is my segment. You mean one of them.", + " Folks, if you watch this show, you know I spend most of my time right over there carefully sorting through the day's biggest stories and selecting only the most subtle and unblemished ostrich and crocodile news leather, which I then entrust to artisan graduates of the Ichol Gregoire Ferrandi, who carefully dye them in a palette of bright zesty shades and adorn them in the finest and most topical inlay work using hand tools and double magnifying glasses, then assemble them according to now classic and elegant geometry using our signature saddles stitching. In line it with bees, wax, coated linen, finely attached a mallet, hammered strap, pearled hardware, and close-shit to create for you the one-of-a-kind hoke couture, Erme's Birkin bag that is my monologue. But sometimes, sometimes folks, sometimes. Sometimes I wake up in the last car of an abandoned roller coaster at Coney Island where I'm I'm hiding from the triads. I have some engine lubricants out of a safe way bag and stagger down the shore to tear the sail off a beach schooner. Then I rip the coaxial cable out of an RV and elderly couple from Utah, Hank, and Mabel lovely folks. And use it to stitch the sail into a loose pouch like a rock sack. And I stow away in the back of a garbage truck to the junkyard where I pick through to the debris for only the broken toys that make me the saddest until I have loaded for you. The Hobo Fugitives bug out, bindle of news that is my segment. Me one!", + " You know, folks, I spent a lot of time crafting for you a bespoke playlist of the day's biggest stories right over there. Meticulously selecting the most topical chakra affirming scented candles, and using Feng Shui to perfectly align the joke energy in the exclusive boutique yoga retreat that is my monologue. But sometimes just sometimes I go to the dumpster behind the waffle house at three in the morning, take off my shirt, cover myself, and used fry oil, wrap my hands with some double-duct tape by stole from the broken car window. Pound a six-pack of blueberry hard-seltzer and a sack of pills I stole from a parked ambulance. Then arm wrestle a raccoon in the back alley vision quest of news that is my segment. Meanwhile!", + " You know, folks, I spend most of my time right over there. Mining the day's biggest, most important stories, collecting the finest, most topical iron or hand hammering it into joke panels. Then I craft sheets of bronze and blazing with patterns that tell an epic tale of conquest and glory. Then, using the Germanic tradition press-black process, I place thin sheets of foil against the scenes and by hammering or otherwise applying pressure from the back, I project these scenes into a pair of cheat cards in a faceplate and, finally, using fluted strips of white alloyed molding, I divide the designs into framed panels and hold it all together using bronze rivets to create the beautiful and intimidating, Anglo-Saxon battle helm that is my nightly monologue. Sometimes, sometimes folks. Sometimes, just sometimes, I come into my sense as fully naked on the deck of a pirate besieged melee container ship that picked me up floating on the detached door of a portapotty in the Indian Ocean. Then after a sunstroke-induced realization of the crew of this ship plans to sell me an exchange for a bag of oranges to fight off scurvy, I lead a mutiny using only a PVC pipe at a pool chain that accepting my new role as Captain and declaring myself king of the windarc seas. I grab a dirty mop bucket covered in barnacles and adorn it with the teeth of the vanquished to create the sopping wet pirate crown of news that is my segment. Meanwhile!", + " Folks, if you watch this show, you know I spend most of my time right over there carefully blending for you the day's Newsiest most topical flower eggs milk and butter and Stranding into a fine batter to make delicate and informative comedy pancakes Then I glaze them in the juice and zest of the most relevant midnight Valencia oranges and douse it all and a fine Dela main de voyage cognac Before prom baying and basting them tables. I deserve for you the James Beard award worthy crepe suzzette That is my nightly monologue, but sometimes just sometimes folks. I wake up in the baggage hold of Greyhound bus. It's being hoisted by the scrap yard claw toward the burn pit. Escape to a nearby abandoned price chopper where I scrounge for old bread scraps and busted open bags of starfruit candies and expired eggs. Chuck it all on a dirty hubcap and slap it over a tire fire before using the legs of a strain, pair of sweatpants and as oven mitts to extract and serve the demented transience poundcake of news that is my segment. Me, Guadalupe!", + " Folks, if you watched the show and I hope you do, I spent a lot of time right over there. Tiredlessly studying the lineage of the days most important thoroughbred stories and whole-stiner headlines, working with the best trainers, money can buy to rear their comedy offspring with a hand that is stern yet gentle into the triple crown winning equine specimen. That is my nightly monologue, but sometimes, sometimes, folks, I break into an unincorporated veterinary genetics lab and grab whatever test tubes I can find and then under a grow light I got from a discarded chia pet. I mixed the pilfered DNA of a horse and whatever was in a tube labeled Keith Colan extra. Slurrying the concoction with caffeine pills and a microwave red bull, I screamed, sang a prayer to Janice, initiator of human life and God of transformation as a half horse, half man, freak. Seizes to life before me and the hideous collection of loose animal parts and corrupted man tissue that is my segment. Meanwhile!", + ] + # fmt: on + + processor = WhisperProcessor.from_pretrained("openai/whisper-tiny.en") + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + model = model.to("cuda") + + ds = load_dataset("distil-whisper/meanwhile", "default")["test"] + ds = ds.cast_column("audio", Audio(sampling_rate=16000)) + + num_samples = 8 + + audio = ds[:num_samples]["audio"] + audios = [x["array"] for x in audio] + + decoded_single = [] + for audio in audios: + inputs = processor(audio, return_tensors="pt", truncation=False, sampling_rate=16_000) + inputs = inputs.to(device="cuda") + + result = model.generate(**inputs, return_timestamps=True) + decoded_single += processor.batch_decode(result, skip_special_tokens=True) + + inputs = processor( + audios, return_tensors="pt", truncation=False, padding="longest", return_attention_mask=True + ) + inputs = inputs.to(device="cuda") + + result = model.generate(**inputs, return_timestamps=True) + decoded_all = processor.batch_decode(result, skip_special_tokens=True) + + for i in range(num_samples): + assert decoded_all[i] == decoded_single[i] + assert decoded_all[i] == EXPECTED_TEXT[i] + + +def prepare_whisper_encoder_inputs_dict(config, input_features, head_mask=None): + if head_mask is None: + head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device) + return {"input_features": input_features, "head_mask": head_mask} + + +@require_torch +class WhisperEncoderModelTester: + def __init__( + self, + parent, + batch_size=2, + seq_length=60, + is_training=True, + use_labels=True, + hidden_size=16, + num_hidden_layers=2, + num_attention_heads=4, + input_channels=1, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=20, + max_source_positions=30, + num_mel_bins=80, + num_conv_layers=1, + suppress_tokens=None, + begin_suppress_tokens=None, + classifier_proj_size=4, + num_labels=2, + is_encoder_decoder=False, + is_decoder=False, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_labels = use_labels + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.input_channels = input_channels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.num_mel_bins = num_mel_bins + self.max_position_embeddings = max_position_embeddings + self.max_source_positions = max_source_positions + self.num_conv_layers = num_conv_layers + self.suppress_tokens = suppress_tokens + self.begin_suppress_tokens = begin_suppress_tokens + self.classifier_proj_size = classifier_proj_size + self.num_labels = num_labels + self.is_encoder_decoder = is_encoder_decoder + self.is_decoder = is_decoder + + def get_config(self): + return WhisperConfig( + 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, + input_channels=self.input_channels, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + max_source_positions=self.max_source_positions, + decoder_ffn_dim=self.hidden_size, + encoder_ffn_dim=self.hidden_size, + suppress_tokens=self.suppress_tokens, + begin_suppress_tokens=self.begin_suppress_tokens, + classifier_proj_size=self.classifier_proj_size, + num_labels=self.num_labels, + is_encoder_decoder=self.is_encoder_decoder, + is_decoder=self.is_decoder, + ) + + def prepare_config_and_inputs(self): + input_features = floats_tensor([self.batch_size, self.num_mel_bins, self.seq_length]) + + config = self.get_config() + inputs_dict = prepare_whisper_encoder_inputs_dict( + config, + input_features=input_features, + ) + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_subsampled_output_lengths(self, input_lengths): + """ + Computes the output length of the convolutional layers + """ + + for i in range(self.num_conv_layers): + input_lengths = (input_lengths - 1) // 2 + 1 + + return input_lengths + + @property + def encoder_seq_length(self): + return self.get_subsampled_output_lengths(self.seq_length) + + def create_and_check_model_forward(self, config, inputs_dict, freeze_encoder=False): + model = WhisperForAudioClassification(config=config).to(torch_device).eval() + + if freeze_encoder: + model.freeze_encoder() + + input_features = inputs_dict["input_features"] + + # first forward pass + last_hidden_state = model(input_features).logits + + self.parent.assertTrue(last_hidden_state.shape, (13, 2)) + + +@require_torch +class WhisperEncoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): + all_model_classes = (WhisperForAudioClassification,) if is_torch_available() else () + is_encoder_decoder = False + fx_compatible = False + test_pruning = False + test_missing_keys = False + + input_name = "input_features" + + def setUp(self): + self.model_tester = WhisperEncoderModelTester(self) + self.config_tester = ConfigTester(self, config_class=WhisperConfig) + self.maxDiff = 3000 + + def test_config(self): + self.config_tester.run_common_tests() + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["input_features", "head_mask", "encoder_outputs"] + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + @unittest.skip(reason="Some undefined behavior encountered with tiny versions of this model. Skip for now.") + def test_cpu_offload(self): + pass + + @unittest.skip(reason="Some undefined behavior encountered with tiny versions of this model. Skip for now.") + def test_disk_offload_bin(self): + pass + + @unittest.skip(reason="Some undefined behavior encountered with tiny versions of this model. Skip for now.") + def test_disk_offload_safetensors(self): + pass + + @unittest.skip(reason="Some undefined behavior encountered with tiny versions of this model. Skip for now.") + def test_model_parallelism(self): + pass + + # input embeds is meaningless for an encoder-only acoustic model + def test_inputs_embeds(self): + pass + + # the equivalent test is passing the encoder outputs directly to the model + def test_encoder_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + + with torch.no_grad(): + outputs = model(**inputs)[0] + + encoder = model.encoder + + encoder_inputs = {"input_features": inputs["input_features"]} + del inputs["input_features"] + + if "head_mask" in inputs: + encoder_inputs["head_mask"] = inputs["head_mask"] + if "attention_mask" in inputs: + encoder_inputs["attention_mask"] = inputs["attention_mask"] + if "output_attentions" in inputs: + encoder_inputs["output_attentions"] = inputs["output_attentions"] + + with torch.no_grad(): + inputs["encoder_outputs"] = encoder(**encoder_inputs) + outputs_embeds = model(**inputs)[0] + + self.assertTrue((outputs_embeds == outputs).all()) + + # Needs to override as the encoder input embedding is a Conv1d + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (torch.nn.Conv1d)) + model.set_input_embeddings(torch.nn.Conv1d(10, 10, 3)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, torch.nn.Conv1d)) + + # WhisperEncoder cannot resize token embeddings since it has no tokens embeddings + def test_resize_tokens_embeddings(self): + pass + + @is_pt_flax_cross_test + def test_equivalence_pt_to_flax(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + init_shape = (1,) + inputs_dict["input_features"].shape[1:] + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + fx_model_class_name = "Flax" + model_class.__name__ + + if not hasattr(transformers, fx_model_class_name): + # no flax model exists for this class + return + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + fx_model_class = getattr(transformers, fx_model_class_name) + + # load PyTorch class + pt_model = model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + + # load Flax class + fx_model = fx_model_class(config, input_shape=init_shape, dtype=jnp.float32) + + # make sure only flax inputs are forward that actually exist in function args + fx_input_keys = inspect.signature(fx_model.__call__).parameters.keys() + + # prepare inputs + pt_inputs = self._prepare_for_class(inputs_dict, model_class) + + # remove function args that don't exist in Flax + pt_inputs = {k: v for k, v in pt_inputs.items() if k in fx_input_keys} + + # send pytorch inputs to the correct device + pt_inputs = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs.items() + } + + # convert inputs to Flax + fx_inputs = {k: np.array(v.to("cpu")) for k, v in pt_inputs.items() if torch.is_tensor(v)} + + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + # send pytorch model to the correct device + pt_model.to(torch_device) + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + fx_outputs = fx_model(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs, model_class) + + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = fx_model_class.from_pretrained(tmpdirname, input_shape=init_shape, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs_loaded.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs_loaded, pt_outputs, model_class) + + @is_pt_flax_cross_test + def test_equivalence_flax_to_pt(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + init_shape = (1,) + inputs_dict["input_features"].shape[1:] + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + fx_model_class_name = "Flax" + model_class.__name__ + + if not hasattr(transformers, fx_model_class_name): + # no flax model exists for this class + return + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + fx_model_class = getattr(transformers, fx_model_class_name) + + # load PyTorch class + pt_model = model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + + # load Flax class + fx_model = fx_model_class(config, input_shape=init_shape, dtype=jnp.float32) + + # make sure only flax inputs are forward that actually exist in function args + fx_input_keys = inspect.signature(fx_model.__call__).parameters.keys() + + # prepare inputs + pt_inputs = self._prepare_for_class(inputs_dict, model_class) + + # remove function args that don't exist in Flax + pt_inputs = {k: v for k, v in pt_inputs.items() if k in fx_input_keys} + + # send pytorch inputs to the correct device + pt_inputs = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs.items() + } + + # convert inputs to Flax + fx_inputs = {k: np.array(v.to("cpu")) for k, v in pt_inputs.items() if torch.is_tensor(v)} + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + + # make sure weights are tied in PyTorch + pt_model.tie_weights() + + # send pytorch model to the correct device + pt_model.to(torch_device) + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + fx_outputs = fx_model(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs, model_class) + + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = model_class.from_pretrained(tmpdirname, from_flax=True) + + # send pytorch model to the correct device + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs_loaded.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs_loaded, model_class) + + +class WhisperStandaloneDecoderModelTester: + def __init__( + self, + parent, + batch_size=2, + is_training=True, + use_labels=False, + vocab_size=200, + hidden_size=16, + num_hidden_layers=2, + num_attention_heads=4, + input_channels=1, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=20, + max_source_positions=30, + max_target_positions=40, + bos_token_id=98, + eos_token_id=98, + pad_token_id=0, + num_mel_bins=80, + decoder_start_token_id=85, + num_conv_layers=1, + suppress_tokens=None, + begin_suppress_tokens=None, + ): + self.parent = parent + self.batch_size = batch_size + 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.input_channels = input_channels + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.num_mel_bins = num_mel_bins + self.max_position_embeddings = max_position_embeddings + self.max_source_positions = max_source_positions + self.max_target_positions = max_target_positions + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.bos_token_id = bos_token_id + self.decoder_start_token_id = decoder_start_token_id + self.num_conv_layers = num_conv_layers + self.suppress_tokens = suppress_tokens + self.begin_suppress_tokens = begin_suppress_tokens + + def prepare_config_and_inputs(self): + input_features = floats_tensor([self.batch_size, self.num_mel_bins, self.seq_length], self.vocab_size) + + decoder_input_ids = torch.tensor( + self.batch_size * [[self.decoder_start_token_id, 3, 3, 7, 2]], device=torch_device + ) + + config = self.get_config() + config.is_encoder_decoder = False + inputs_dict = prepare_whisper_inputs_dict( + config, + attention_mask=None, + input_features=input_features, + decoder_input_ids=decoder_input_ids, + ) + + inputs_dict.pop("input_features") + inputs_dict.pop("head_mask") + inputs_dict.pop("decoder_head_mask") + inputs_dict.pop("cross_attn_head_mask") + + inputs_dict["attention_mask"] = inputs_dict.pop("decoder_attention_mask") + inputs_dict["input_ids"] = inputs_dict.pop("decoder_input_ids") + return config, inputs_dict + + @property + def encoder_seq_length(self): + return 5 + + @property + def seq_length(self): + return 5 + + def get_config(self): + return WhisperConfig( + 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, + input_channels=self.input_channels, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + max_source_positions=self.max_source_positions, + max_target_positions=self.max_target_positions, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + decoder_ffn_dim=self.hidden_size, + encoder_ffn_dim=self.hidden_size, + decoder_start_token_id=self.decoder_start_token_id, + suppress_tokens=self.suppress_tokens, + begin_suppress_tokens=self.begin_suppress_tokens, + ) + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + + inputs_dict["input_ids"][:, -1] = self.pad_token_id + + return config, inputs_dict + + def prepare_config_and_inputs_for_decoder(self): + config, input_features = self.prepare_config_and_inputs() + input_ids = input_features["input_ids"] + encoder_hidden_states = floats_tensor([self.batch_size, self.decoder_seq_length, self.hidden_size]) + + return (config, input_ids, encoder_hidden_states) + + def create_and_check_decoder_model_past(self, config, input_ids): + config.use_cache = True + model = WhisperDecoder(config=config).to(torch_device).eval() + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_use_cache_conf = model(input_ids) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + past_key_values = outputs["past_key_values"] + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3) + + def create_and_check_decoder_model_attention_mask_past(self, config, input_ids): + model = WhisperDecoder(config=config).to(torch_device).eval() + + # create attention mask + attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) + + half_seq_length = input_ids.shape[-1] // 2 + attn_mask[:, half_seq_length:] = 0 + + # first forward pass + past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"] + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # change a random masked slice from input_ids + random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1 + random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1) + input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens + + # append to next input_ids and attn_mask + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + attn_mask = torch.cat( + [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)], + dim=1, + ) + + # get two different outputs + output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=attn_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3) + + +@require_torch +class WhisperStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): + all_model_classes = (WhisperDecoder, WhisperForCausalLM) if is_torch_available() else () + all_generative_model_classes = (WhisperForCausalLM,) if is_torch_available() else () + fx_comptatible = False + test_pruning = False + is_encoder_decoder = False + test_missing_keys = False + + def setUp(self): + self.model_tester = WhisperStandaloneDecoderModelTester(self, is_training=False) + self.config_tester = ConfigTester(self, config_class=WhisperConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_decoder_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config, inputs_dict = config_and_inputs + + self.model_tester.create_and_check_decoder_model_past(config=config, input_ids=inputs_dict["input_ids"]) + + def test_decoder_model_attn_mask_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + config, inputs_dict = config_and_inputs + + self.model_tester.create_and_check_decoder_model_attention_mask_past( + config=config, input_ids=inputs_dict["input_ids"] + ) + + @unittest.skip("Generate needs input ids") + def test_generate_without_input_ids(self): + # generate only works with input ids for whisper + pass + + @unittest.skip("Decoder can't keep attention grads") + def test_retain_grad_hidden_states_attentions(self): + # decoder cannot keep gradients + return + + @unittest.skip("The model doesn't support fast init from base") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip("The model doesn't support left padding") # and it's not used enough to be worth fixing :) + def test_left_padding_compatibility(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_processor_whisper.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_processor_whisper.py new file mode 100644 index 0000000000000000000000000000000000000000..e96f4260e94c1ddd461f5d6c460d7748314059b4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_processor_whisper.py @@ -0,0 +1,179 @@ +# Copyright 2022 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 shutil +import tempfile +import unittest + +import pytest + +from transformers import WhisperTokenizer, is_speech_available +from transformers.testing_utils import require_sentencepiece, require_torch, require_torchaudio + +from .test_feature_extraction_whisper import floats_list + + +if is_speech_available(): + from transformers import WhisperFeatureExtractor, WhisperProcessor + + +TRANSCRIBE = 50358 +NOTIMESTAMPS = 50362 + + +@require_torch +@require_torchaudio +@require_sentencepiece +class WhisperProcessorTest(unittest.TestCase): + def setUp(self): + self.checkpoint = "openai/whisper-small.en" + self.tmpdirname = tempfile.mkdtemp() + + def get_tokenizer(self, **kwargs): + return WhisperTokenizer.from_pretrained(self.checkpoint, **kwargs) + + def get_feature_extractor(self, **kwargs): + return WhisperFeatureExtractor.from_pretrained(self.checkpoint, **kwargs) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_save_load_pretrained_default(self): + tokenizer = self.get_tokenizer() + feature_extractor = self.get_feature_extractor() + + processor = WhisperProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + processor.save_pretrained(self.tmpdirname) + processor = WhisperProcessor.from_pretrained(self.tmpdirname) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) + self.assertIsInstance(processor.tokenizer, WhisperTokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string()) + self.assertIsInstance(processor.feature_extractor, WhisperFeatureExtractor) + + def test_save_load_pretrained_additional_features(self): + processor = WhisperProcessor(tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor()) + processor.save_pretrained(self.tmpdirname) + + tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)") + feature_extractor_add_kwargs = self.get_feature_extractor(do_normalize=False, padding_value=1.0) + + processor = WhisperProcessor.from_pretrained( + self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0 + ) + + self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) + self.assertIsInstance(processor.tokenizer, WhisperTokenizer) + + self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string()) + self.assertIsInstance(processor.feature_extractor, WhisperFeatureExtractor) + + def test_feature_extractor(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = WhisperProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + raw_speech = floats_list((3, 1000)) + + input_feat_extract = feature_extractor(raw_speech, return_tensors="np") + input_processor = processor(raw_speech, return_tensors="np") + + for key in input_feat_extract.keys(): + self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) + + def test_tokenizer(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = WhisperProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + input_str = "This is a test string" + + encoded_processor = processor(text=input_str) + + encoded_tok = tokenizer(input_str) + + for key in encoded_tok.keys(): + self.assertListEqual(encoded_tok[key], encoded_processor[key]) + + def test_tokenizer_decode(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = WhisperProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] + + decoded_processor = processor.batch_decode(predicted_ids) + decoded_tok = tokenizer.batch_decode(predicted_ids) + + self.assertListEqual(decoded_tok, decoded_processor) + + def test_model_input_names(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = WhisperProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + + self.assertListEqual( + processor.model_input_names, + feature_extractor.model_input_names, + msg="`processor` and `feature_extractor` model input names do not match", + ) + + def test_get_decoder_prompt_ids(self): + feature_extractor = self.get_feature_extractor() + tokenizer = self.get_tokenizer() + + processor = WhisperProcessor(tokenizer=tokenizer, feature_extractor=feature_extractor) + forced_decoder_ids = processor.get_decoder_prompt_ids(task="transcribe", no_timestamps=True) + + self.assertIsInstance(forced_decoder_ids, list) + for ids in forced_decoder_ids: + self.assertIsInstance(ids, (list, tuple)) + + expected_ids = [TRANSCRIBE, NOTIMESTAMPS] + self.assertListEqual([ids[-1] for ids in forced_decoder_ids], expected_ids) + + def test_get_prompt_ids(self): + processor = WhisperProcessor(tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor()) + prompt_ids = processor.get_prompt_ids("Mr. Quilter") + decoded_prompt = processor.tokenizer.decode(prompt_ids) + + self.assertListEqual(prompt_ids.tolist(), [50360, 1770, 13, 2264, 346, 353]) + self.assertEqual(decoded_prompt, "<|startofprev|> Mr. Quilter") + + def test_empty_get_prompt_ids(self): + processor = WhisperProcessor(tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor()) + prompt_ids = processor.get_prompt_ids("") + decoded_prompt = processor.tokenizer.decode(prompt_ids) + + self.assertListEqual(prompt_ids.tolist(), [50360, 220]) + self.assertEqual(decoded_prompt, "<|startofprev|> ") + + def test_get_prompt_ids_with_special_tokens(self): + processor = WhisperProcessor(tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor()) + + def _test_prompt_error_raised_helper(prompt, special_token): + with pytest.raises(ValueError) as excinfo: + processor.get_prompt_ids(prompt) + expected = f"Encountered text in the prompt corresponding to disallowed special token: {special_token}." + self.assertEqual(expected, str(excinfo.value)) + + _test_prompt_error_raised_helper("<|startofprev|> test", "<|startofprev|>") + _test_prompt_error_raised_helper("test <|notimestamps|>", "<|notimestamps|>") + _test_prompt_error_raised_helper("test <|zh|> test <|transcribe|>", "<|zh|>") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_tokenization_whisper.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_tokenization_whisper.py new file mode 100644 index 0000000000000000000000000000000000000000..731abd3a283e4b3c3b80fac2a9209886690e862d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/whisper/test_tokenization_whisper.py @@ -0,0 +1,523 @@ +# Copyright 2022 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 unittest + +from transformers.models.whisper import WhisperTokenizer, WhisperTokenizerFast +from transformers.models.whisper.tokenization_whisper import _combine_tokens_into_words, _find_longest_common_sequence +from transformers.testing_utils import require_jinja, slow + +from ...test_tokenization_common import TokenizerTesterMixin + + +ES_CODE = 50262 +EN_CODE = 50259 +END_OF_TRANSCRIPT = 50257 +START_OF_TRANSCRIPT = 50258 +TRANSLATE = 50358 +TRANSCRIBE = 50359 +NOTIMESTAMPS = 50363 + + +class WhisperTokenizerTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = WhisperTokenizer + rust_tokenizer_class = WhisperTokenizerFast + test_rust_tokenizer = True + test_sentencepiece = False + test_seq2seq = False + + def setUp(self): + super().setUp() + tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny") + tokenizer.pad_token_id = 50256 + tokenizer.pad_token = "<|endoftext|>" + tokenizer.save_pretrained(self.tmpdirname) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "Where" + token_id = 14436 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "!") + self.assertEqual(vocab_keys[1], '"') + self.assertEqual(vocab_keys[-1], "<|30.00|>") + self.assertEqual(len(vocab_keys), 51865) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 50258) + + def test_full_tokenizer(self): + tokenizer = WhisperTokenizer.from_pretrained(self.tmpdirname) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["This", "Ġis", "Ġa", "Ġ", "test"]) + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [5723, 307, 257, 220, 31636], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + ["I", "Ġwas", "Ġborn", "Ġin", "Ġ9", "2000", ",", "Ġand", "Ġ", "this", "Ġis", "Ġfals", "é", "."], # fmt: skip + ) # fmt: skip + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual(ids, [40, 390, 4232, 294, 1722, 25743, 11, 293, 220, 11176, 307, 16720, 526, 13]) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual( + back_tokens, + ["I", "Ġwas", "Ġborn", "Ġin", "Ġ9", "2000", ",", "Ġand", "Ġ", "this", "Ġis", "Ġfals", "é", "."], # fmt: skip + ) # fmt: skip + + def test_tokenizer_slow_store_full_signature(self): + pass + + def test_tokenizer_fast_store_full_signature(self): + pass + + def test_special_tokens_initialization(self): + # Whisper relies on specific additional special tokens, so we skip this + # general test. In particular, this test loads fast tokenizer from slow + # tokenizer, and the conversion uses prefix_tokens, where we reference + # additional special tokens by specific indices, hence overriding the + # list with less tokens leads to out of index error + pass + + @slow + def test_tokenizer_integration(self): + expected_encoding = {'input_ids': [[50257, 50362, 41762, 364, 357, 36234, 1900, 355, 12972, 13165, 354, 12, 35636, 364, 290, 12972, 13165, 354, 12, 5310, 13363, 12, 4835, 8, 3769, 2276, 12, 29983, 45619, 357, 13246, 51, 11, 402, 11571, 12, 17, 11, 5564, 13246, 38586, 11, 16276, 44, 11, 4307, 346, 33, 861, 11, 16276, 7934, 23029, 329, 12068, 15417, 28491, 357, 32572, 52, 8, 290, 12068, 15417, 16588, 357, 32572, 38, 8, 351, 625, 3933, 10, 2181, 13363, 4981, 287, 1802, 10, 8950, 290, 2769, 48817, 1799, 1022, 449, 897, 11, 9485, 15884, 354, 290, 309, 22854, 37535, 13, 50256], [50257, 50362, 13246, 51, 318, 3562, 284, 662, 12, 27432, 2769, 8406, 4154, 282, 24612, 422, 9642, 9608, 276, 2420, 416, 26913, 21143, 319, 1111, 1364, 290, 826, 4732, 287, 477, 11685, 13, 50256], [50257, 50362, 464, 2068, 7586, 21831, 18045, 625, 262, 16931, 3290, 13, 50256]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # fmt: skip + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, model_name="openai/whisper-tiny.en", padding=False + ) + + def test_output_offsets(self): + tokenizer = self.get_tokenizer() + previous_sequence = [51492, 406, 3163, 1953, 466, 13, 51612, 51612] + self.assertEqual( + tokenizer.decode(previous_sequence, output_offsets=True), + { + "text": " not worth thinking about.", + "offsets": [{"text": " not worth thinking about.", "timestamp": (22.56, 24.96)}], + }, + ) + + # Merge when the previous sequence is a suffix of the next sequence + next_sequences_1 = [50364, 295, 6177, 3391, 11, 19817, 3337, 507, 307, 406, 3163, 1953, 466, 13, 50614, 50614, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 50834, 50257] # fmt: skip + self.assertEqual( + tokenizer.decode(next_sequences_1, output_offsets=True), + { + "text": ( + " of spectators, retrievality is not worth thinking about. His instant panic was followed by a" + " small, sharp blow high on his chest.<|endoftext|>" + ), + "offsets": [ + {"text": " of spectators, retrievality is not worth thinking about.", "timestamp": (0.0, 5.0)}, + { + "text": " His instant panic was followed by a small, sharp blow high on his chest.", + "timestamp": (5.0, 9.4), + }, + ], + }, + ) + + def test_find_longest_common_subsequence(self): + previous_sequence = [1, 2, 3] + next_sequence = [2, 3, 4, 5] + merge = _find_longest_common_sequence([previous_sequence, next_sequence]) + self.assertEqual(merge, [1, 2, 3, 4, 5]) + + # Now previous is larger than next. + # We merge what we can and remove the extra right side of the left sequence + previous_sequence = [1, 2, 3, 4, 5, 6, 7] + next_sequence = [2, 3, 4, 5] + merge = _find_longest_common_sequence([previous_sequence, next_sequence]) + self.assertEqual(merge, [1, 2, 3, 4, 5]) + + # Nothing in common + previous_sequence = [1, 2, 3] + next_sequence = [4, 5, 6] + merge = _find_longest_common_sequence([previous_sequence, next_sequence]) + self.assertEqual(merge, [1, 2, 3, 4, 5, 6]) + + # Some errors in the overlap. + # We take from previous on the left, from the next on the right of the overlap + previous_sequence = [1, 2, 3, 4, 99] + next_sequence = [2, 98, 4, 5, 6] + merge = _find_longest_common_sequence([previous_sequence, next_sequence]) + self.assertEqual(merge, [1, 2, 3, 4, 5, 6]) + + # We take from previous on the left, from the next on the right of the overlap + previous_sequence = [1, 2, 99, 4, 5] + next_sequence = [2, 3, 4, 98, 6] + merge = _find_longest_common_sequence([previous_sequence, next_sequence]) + self.assertEqual(merge, [1, 2, 99, 4, 98, 6]) + + # This works on 3 sequences + seq1 = [1, 2, 3] + seq2 = [2, 3, 4] + seq3 = [3, 4, 5] + merge = _find_longest_common_sequence([seq1, seq2, seq3]) + self.assertEqual(merge, [1, 2, 3, 4, 5]) + + # This works on 3 sequences with errors + seq1 = [1, 2, 3, 98, 5] + seq2 = [2, 99, 4, 5, 6, 7] + seq3 = [4, 97, 6, 7, 8] + merge = _find_longest_common_sequence([seq1, seq2, seq3]) + self.assertEqual(merge, [1, 2, 3, 4, 5, 6, 7, 8]) + + def test_skip_special_tokens_skips_prompt_ids(self): + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + # fmt: off + encoded_input = [ + 50361, 2221, 13, 2326, 388, 391, 50258, 50259, 50359, + 50363, 1282, 264, 2674, 9156, 295, 1523, 11, 2221, 13, + 2326, 388, 391, 13657, 365, 2681, 21296, 17711, 13, 50257, + ] + # fmt: on + expected_with_special_tokens = "<|startofprev|> Mr. Quilter<|startoftranscript|><|en|><|transcribe|><|notimestamps|> On the general principles of art, Mr. Quilter writes with equal lucidity.<|endoftext|>" + expected_without_special_tokens = " On the general principles of art, Mr. Quilter writes with equal lucidity." + self.assertEqual(tokenizer.decode(encoded_input, skip_special_tokens=False), expected_with_special_tokens) + self.assertEqual(tokenizer.decode(encoded_input, skip_special_tokens=True), expected_without_special_tokens) + self.assertEqual(rust_tokenizer.decode(encoded_input, skip_special_tokens=False), expected_with_special_tokens) + self.assertEqual( + rust_tokenizer.decode(encoded_input, skip_special_tokens=True), expected_without_special_tokens + ) + + def test_skip_special_tokens_with_timestamps(self): + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + # fmt: off + encoded_input = [ + 50258, 50363, 50364, 634, 575, 12525, 22618, 1968, 6144, + 35617, 20084, 1756, 311, 589, 307, 534, 10281, 934, + 439, 293, 50676, 50676, 393, 4411, 294, 309, 457, + 707, 295, 33301, 286, 392, 6628, 13, 50836, 50257, + ] + # fmt: on + + expected_with_special_tokens = "<|startoftranscript|><|notimestamps|><|0.00|> He has grave doubts whether Sir Frederick Layton's work is really Greek after all and<|6.24|><|6.24|> can discover in it but little of rocky Ithaca.<|9.44|><|endoftext|>" + expected_without_special_tokens = "<|0.00|> He has grave doubts whether Sir Frederick Layton's work is really Greek after all and<|6.24|><|6.24|> can discover in it but little of rocky Ithaca.<|9.44|>" + self.assertEqual( + tokenizer.decode(encoded_input, decode_with_timestamps=True, skip_special_tokens=False), + expected_with_special_tokens, + ) + self.assertEqual( + tokenizer.decode(encoded_input, decode_with_timestamps=True, skip_special_tokens=True), + expected_without_special_tokens, + ) + self.assertEqual( + rust_tokenizer.decode(encoded_input, decode_with_timestamps=True, skip_special_tokens=False), + expected_with_special_tokens, + ) + self.assertEqual( + rust_tokenizer.decode(encoded_input, decode_with_timestamps=True, skip_special_tokens=True), + expected_without_special_tokens, + ) + + def test_fast_tokenizer_get_prompt_ids(self): + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + prompt = "This is test prompt text." + tokenizer_prompt_ids = tokenizer.get_prompt_ids(prompt) + fast_tokenizer_prompt_ids = rust_tokenizer.get_prompt_ids(prompt) + + self.assertListEqual(tokenizer_prompt_ids.tolist(), fast_tokenizer_prompt_ids.tolist()) + + def test_combine_tokens_into_words(self): + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + # 'whatever "whatever" said someone, clever!?' + encoded_input = [1363, 7969, 503, 1363, 7969, 1, 848, 1580, 11, 13494, 7323] + expected_words = ["whatever", ' "whatever"', " said", " someone,", " clever!?"] + expected_tokens = [[1363, 7969], [503, 1363, 7969, 1], [848], [1580, 11], [13494, 7323]] + expected_indices = [[0, 1], [2, 3, 4, 5], [6], [7, 8], [9, 10]] + output = _combine_tokens_into_words(tokenizer, encoded_input) + self.assertEqual(expected_words, output[0]) + self.assertEqual(expected_tokens, output[1]) + self.assertEqual(expected_indices, output[2]) + output_rust = _combine_tokens_into_words(rust_tokenizer, encoded_input) + self.assertEqual(expected_words, output_rust[0]) + self.assertEqual(expected_tokens, output_rust[1]) + self.assertEqual(expected_indices, output_rust[2]) + + def test_basic_normalizer(self): + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + input_str = "Hola güey!" + expected_output_normalize = "hola güey " + expected_output_diacritics = "hola guey " + + # tokenizer tests + encoded_input = tokenizer(input_str).input_ids + decoded_output = tokenizer.decode(encoded_input, skip_special_tokens=True, basic_normalize=False) + self.assertEqual(decoded_output, input_str) + + decoded_output_normalize = tokenizer.decode(encoded_input, skip_special_tokens=True, basic_normalize=True) + self.assertEqual(decoded_output_normalize, expected_output_normalize) + + decoded_output_diacritics = tokenizer.decode( + encoded_input, skip_special_tokens=True, basic_normalize=True, remove_diacritics=True + ) + self.assertEqual(decoded_output_diacritics, expected_output_diacritics) + + # fast tokenizer tests + encoded_input = rust_tokenizer(input_str).input_ids + decoded_output = rust_tokenizer.decode(encoded_input, skip_special_tokens=True, basic_normalize=False) + self.assertEqual(decoded_output, input_str) + + decoded_output_normalize = rust_tokenizer.decode(encoded_input, skip_special_tokens=True, basic_normalize=True) + self.assertEqual(decoded_output_normalize, expected_output_normalize) + + decoded_output_diacritics = rust_tokenizer.decode( + encoded_input, skip_special_tokens=True, basic_normalize=True, remove_diacritics=True + ) + self.assertEqual(decoded_output_diacritics, expected_output_diacritics) + + +class SpeechToTextTokenizerMultilinguialTest(unittest.TestCase): + checkpoint_name = "openai/whisper-small.en" + + @classmethod + def setUpClass(cls): + cls.tokenizer: WhisperTokenizer = WhisperTokenizer.from_pretrained(cls.checkpoint_name) + return cls + + def test_tokenizer_equivalence(self): + text = "다람쥐 헌 쳇바퀴에 타고파" + multilingual_tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny", language="korean") + monolingual_tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny.en") + + monolingual_tokens = monolingual_tokenizer.encode(text, add_special_tokens=False) + multilingual_tokens = multilingual_tokenizer.encode(text, add_special_tokens=False) + + assert monolingual_tokenizer.decode(monolingual_tokens) == text + assert multilingual_tokenizer.decode(multilingual_tokens) == text + assert len(monolingual_tokens) > len(multilingual_tokens) + + # fmt: off + EXPECTED_ENG = [ + 46695, 97, 167, 252, 234, 168, 98, 238, 220, 169, + 245, 234, 23821, 111, 229, 167, 108, 242, 169, 222, + 112, 168, 245, 238, 220, 169, 225, 222, 166, 111, + 254, 169, 234, 234 + ] + EXPECTED_MULTI = [ + 9835, 22855, 168, 98, 238, 13431, 234, 43517, 229, 47053, + 169, 222, 19086, 19840, 1313, 17974 + ] + # fmt: on + + self.assertListEqual(monolingual_tokens, EXPECTED_ENG) + self.assertListEqual(multilingual_tokens, EXPECTED_MULTI) + + def test_tokenizer_special(self): + multilingual_tokenizer = WhisperTokenizer.from_pretrained( + "openai/whisper-tiny", language="english", task="transcribe" + ) + text = "Hey! How are you feeling? J'ai l'impression que 郷さん est prêt" + + multilingual_tokens = multilingual_tokenizer.encode(text) + + # fmt: off + # format: <|startoftranscript|> <|lang-id|> <|task|> <|notimestamps|> ... transcription ids ... <|endoftext|> + EXPECTED_MULTI = [ + START_OF_TRANSCRIPT, EN_CODE, TRANSCRIBE, NOTIMESTAMPS, 7057, 0, 1012, 366, 291, + 2633, 30, 508, 6, 1301, 287, 6, 36107, 631, 220, 11178, + 115, 15567, 871, 44393, END_OF_TRANSCRIPT + ] + EXPECTED_SPECIAL_TEXT = ( + "<|startoftranscript|><|en|><|transcribe|><|notimestamps|>Hey! How are you feeling? " + "J'ai l'impression que 郷さん est prêt<|endoftext|>" + ) + # fmt: on + + self.assertListEqual(multilingual_tokens, EXPECTED_MULTI) + + special_transcript = multilingual_tokenizer.decode(multilingual_tokens, skip_special_tokens=False) + self.assertEqual(special_transcript, EXPECTED_SPECIAL_TEXT) + + transcript = multilingual_tokenizer.decode(multilingual_tokens, skip_special_tokens=True) + self.assertEqual(transcript, text) + + def test_vocab_size(self): + self.assertEqual(self.tokenizer.vocab_size, 50257) + + # Copied from tests.models.speech_to_text.test_tokenization_speech_to_text.SpeechToTextTokenizerMultilinguialTest.test_tokenizer_decode_ignores_language_codes + def test_tokenizer_decode_ignores_language_codes(self): + self.assertIn(ES_CODE, self.tokenizer.all_special_ids) + generated_ids = [ES_CODE, 4, 1601, 47, 7647, 2] + result = self.tokenizer.decode(generated_ids, skip_special_tokens=True) + expected_spanish = self.tokenizer.decode(generated_ids[1:], skip_special_tokens=True) + self.assertEqual(result, expected_spanish) + self.assertNotIn(self.tokenizer.eos_token, result) + + def test_batch_encoding(self): + multilingual_tokenizer = WhisperTokenizer.from_pretrained( + "openai/whisper-tiny", language="spanish", task="translate" + ) + batch = ["El gato ", "El gato se sentó"] + batch_output = multilingual_tokenizer.batch_encode_plus(batch, padding=True).input_ids + + # fmt: off + EXPECTED_MULTI = [ + [START_OF_TRANSCRIPT, ES_CODE, TRANSLATE, NOTIMESTAMPS, 17356, 290, 2513, 220, + END_OF_TRANSCRIPT, END_OF_TRANSCRIPT, END_OF_TRANSCRIPT], + [START_OF_TRANSCRIPT, ES_CODE, TRANSLATE, NOTIMESTAMPS, 17356, 290, 2513, 369, + 2279, 812, END_OF_TRANSCRIPT] + ] + # fmt: on + + self.assertListEqual(batch_output, EXPECTED_MULTI) + + def test_set_prefix_tokens(self): + multilingual_tokenizer = WhisperTokenizer.from_pretrained( + "openai/whisper-tiny", language="spanish", task="translate" + ) + + # change the language prefix token from Spanish to English + multilingual_tokenizer.set_prefix_tokens(language="english") + + batch = ["the cat", "the cat sat"] + batch_output = multilingual_tokenizer.batch_encode_plus(batch, padding=True).input_ids + + # fmt: off + EXPECTED_MULTI = [ + [START_OF_TRANSCRIPT, EN_CODE, TRANSLATE, NOTIMESTAMPS, 3322, 3857, + END_OF_TRANSCRIPT, END_OF_TRANSCRIPT], + [START_OF_TRANSCRIPT, EN_CODE, TRANSLATE, NOTIMESTAMPS, 3322, 3857, + 3227, END_OF_TRANSCRIPT] + ] + # fmt: on + + self.assertListEqual(batch_output, EXPECTED_MULTI) + + def test_batch_encoding_decoding(self): + multilingual_tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny", language="spanish") + batch = ["hola güey", "que onda"] + batch_encoding = multilingual_tokenizer.batch_encode_plus(batch, padding=True).input_ids + transcription = multilingual_tokenizer.batch_decode(batch_encoding, skip_special_tokens=True) + self.assertListEqual(batch, transcription) + + def test_offset_decoding(self): + multilingual_tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny") + # fmt: off + INPUT_TOKENS = [ + 50258, 50259, 50359, 50364, 441, 1857, 4174, 11, 5242, 366, + 257, 1333, 295, 493, 2794, 2287, 293, 12018, 14880, 11, + 293, 25730, 311, 454, 34152, 4496, 904, 50724, 50724, 366, + 382, 4048, 382, 257, 361, 18459, 13065, 13, 2221, 13, + 7145, 74, 325, 38756, 311, 29822, 7563, 412, 472, 709, + 294, 264, 51122, 51122, 912, 636, 300, 2221, 13, 2741, + 5767, 1143, 281, 7319, 702, 7798, 13, 400, 2221, 13, + 2619, 4004, 811, 2709, 702, 51449, 51449, 50257 + ] + # fmt: on + output = multilingual_tokenizer.decode(INPUT_TOKENS, output_offsets=True)["offsets"] + + self.assertEqual( + output, + [ + { + "text": ( + " Lennils, pictures are a sort of upguards and atom paintings, and Mason's exquisite idles" + ), + "timestamp": (0.0, 7.2), + }, + { + "text": ( + " are as national as a jingo poem. Mr. Birkut Foster's landscapes smile at one much in the" + ), + "timestamp": (7.2, 15.16), + }, + { + "text": " same way that Mr. Carker used to flash his teeth. And Mr. John Colier gives his", + "timestamp": (15.16, 21.7), + }, + ], + ) + # test `decode_with_offsets` + output = multilingual_tokenizer.decode(INPUT_TOKENS, decode_with_timestamps=True) + self.assertEqual( + output, + "<|startoftranscript|><|en|><|transcribe|><|0.00|> Lennils, pictures are a sort of upguards and atom" + " paintings, and Mason's exquisite idles<|7.20|><|7.20|> are as national as a jingo poem. Mr. Birkut" + " Foster's landscapes smile at one much in the<|15.16|><|15.16|> same way that Mr. Carker used to flash" + " his teeth. And Mr. John Colier gives his<|21.70|><|21.70|><|endoftext|>", + ) + # test a single sequence with timestamps + # fmt: off + INPUT_TOKENS = [ + 50364, 441, 1857, 4174, 11, 5242, 366, + 257, 1333, 295, 493, 2794, 2287, 293, 12018, 14880, 11, + 293, 25730, 311, 454, 34152, 4496, 904, 50724 + ] + # fmt: on + + output = multilingual_tokenizer.decode(INPUT_TOKENS, output_offsets=True)["offsets"] + self.assertEqual( + output[0], + { + "text": " Lennils, pictures are a sort of upguards and atom paintings, and Mason's exquisite idles", + "timestamp": (0.0, 7.2), + }, + ) + + # test a sequence without a single timestamps + # fmt: off + INPUT_TOKENS = [ + 441, 1857, 4174, 11, 5242, 366, + 257, 1333, 295, 493, 2794, 2287, 293, 12018, 14880, 11, + 293, 25730, 311, 454, 34152, 4496, 904, 50724 + ] + # fmt: on + + output = multilingual_tokenizer.decode(INPUT_TOKENS, output_offsets=True)["offsets"] + self.assertEqual(output, []) + + @require_jinja + def test_tokenization_for_chat(self): + multilingual_tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny") + # This is in English, but it's just here to make sure the chat control tokens are being added properly + test_chats = [ + [{"role": "system", "content": "You are a helpful chatbot."}, {"role": "user", "content": "Hello!"}], + [ + {"role": "system", "content": "You are a helpful chatbot."}, + {"role": "user", "content": "Hello!"}, + {"role": "assistant", "content": "Nice to meet you."}, + ], + [{"role": "assistant", "content": "Nice to meet you."}, {"role": "user", "content": "Hello!"}], + ] + tokenized_chats = [multilingual_tokenizer.apply_chat_template(test_chat) for test_chat in test_chats] + expected_tokens = [ + [3223, 366, 257, 4961, 5081, 18870, 13, 50257, 15947, 0, 50257], + [3223, 366, 257, 4961, 5081, 18870, 13, 50257, 15947, 0, 50257, 37717, 220, 1353, 1677, 291, 13, 50257], + [37717, 220, 1353, 1677, 291, 13, 50257, 15947, 0, 50257], + ] + for tokenized_chat, expected_tokens in zip(tokenized_chats, expected_tokens): + self.assertListEqual(tokenized_chat, expected_tokens) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/x_clip/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/x_clip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/x_clip/test_modeling_x_clip.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/x_clip/test_modeling_x_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..db28b41c0b39a3d0dc712765b30f5a388cb125e5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/x_clip/test_modeling_x_clip.py @@ -0,0 +1,730 @@ +# coding=utf-8 +# Copyright 2022 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 XCLIP model. """ + + +import inspect +import os +import tempfile +import unittest + +import numpy as np +from huggingface_hub import hf_hub_download + +from transformers import XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig +from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device +from transformers.utils import is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ( + ModelTesterMixin, + _config_zero_init, + floats_tensor, + ids_tensor, + random_attention_mask, +) +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import XCLIPModel, XCLIPTextModel, XCLIPVisionModel + from transformers.models.x_clip.modeling_x_clip import XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from transformers import XCLIPProcessor + + +class XCLIPVisionModelTester: + def __init__( + self, + parent, + batch_size=8, + image_size=30, + patch_size=2, + num_channels=3, + num_frames=8, # important; the batch size * time must be divisible by the number of frames + is_training=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + mit_hidden_size=64, + dropout=0.1, + attention_dropout=0.1, + initializer_range=0.02, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.num_frames = num_frames + self.is_training = is_training + 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.mit_hidden_size = mit_hidden_size + self.dropout = dropout + self.attention_dropout = attention_dropout + self.initializer_range = initializer_range + self.scope = scope + + # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) + num_patches = (image_size // patch_size) ** 2 + self.seq_length = num_patches + 1 + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor( + [self.batch_size * self.num_frames, self.num_channels, self.image_size, self.image_size] + ) + config = self.get_config() + + return config, pixel_values + + def get_config(self): + return XCLIPVisionConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + num_frames=self.num_frames, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + mit_hidden_size=self.mit_hidden_size, + dropout=self.dropout, + attention_dropout=self.attention_dropout, + initializer_range=self.initializer_range, + ) + + def create_and_check_model(self, config, pixel_values): + model = XCLIPVisionModel(config=config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + result = model(pixel_values) + # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + image_size = (self.image_size, self.image_size) + patch_size = (self.patch_size, self.patch_size) + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size * self.num_frames, num_patches + 1, self.hidden_size) + ) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size * self.num_frames, self.hidden_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class XCLIPVisionModelTest(ModelTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as X-CLIP does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (XCLIPVisionModel,) if is_torch_available() else () + fx_compatible = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = XCLIPVisionModelTester(self) + self.config_tester = ConfigTester( + self, config_class=XCLIPVisionConfig, has_text_modality=False, hidden_size=37 + ) + + def test_config(self): + self.config_tester.run_common_tests() + + @unittest.skip(reason="X-CLIP does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_training(self): + pass + + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + @unittest.skip(reason="XCLIPVisionModel has no base class and is not available in MODEL_MAPPING") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip(reason="XCLIPVisionModel has no base class and is not available in MODEL_MAPPING") + def test_save_load_fast_init_to_base(self): + pass + + @slow + def test_model_from_pretrained(self): + for model_name in XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = XCLIPVisionModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_gradient_checkpointing_backward_compatibility(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if not model_class.supports_gradient_checkpointing: + continue + + print("Model class:", model_class) + + config.gradient_checkpointing = True + model = model_class(config) + self.assertTrue(model.is_gradient_checkpointing) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + # we add 1 here due to the special message token in X-CLIP's vision encoder + seq_len = getattr(self.model_tester, "seq_length", None) + 1 + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + self.assertEqual(len(outputs.attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + self.assertEqual(len(outputs.attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(outputs.attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_seq_length], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + 1, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_seq_length], + ) + + @require_torch_multi_gpu + def test_multi_gpu_data_parallel_forward(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # some params shouldn't be scattered by nn.DataParallel + # so just remove them if they are present. + blacklist_non_batched_params = ["head_mask", "decoder_head_mask", "cross_attn_head_mask"] + for k in blacklist_non_batched_params: + inputs_dict.pop(k, None) + + # move input tensors to cuda:O + for k, v in inputs_dict.items(): + if torch.is_tensor(v): + inputs_dict[k] = v.to(0) + + for model_class in self.all_model_classes: + model = model_class(config=config) + model.to(0) + model.eval() + + # Wrap model in nn.DataParallel + model = nn.DataParallel(model) + with torch.no_grad(): + test = self._prepare_for_class(inputs_dict, model_class) + for k, v in test.items(): + if isinstance(v, torch.Tensor): + print(k, v.shape) + else: + print(k, v) + _ = model(**self._prepare_for_class(inputs_dict, model_class)) + + +class XCLIPTextModelTester: + def __init__( + self, + parent, + batch_size=8, + seq_length=7, + is_training=True, + use_input_mask=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + dropout=0.1, + attention_dropout=0.1, + max_position_embeddings=512, + initializer_range=0.02, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + 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.dropout = dropout + self.attention_dropout = attention_dropout + self.max_position_embeddings = max_position_embeddings + self.initializer_range = initializer_range + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + if input_mask is not None: + batch_size, seq_length = input_mask.shape + rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,)) + for batch_idx, start_index in enumerate(rnd_start_indices): + input_mask[batch_idx, :start_index] = 1 + input_mask[batch_idx, start_index:] = 0 + + config = self.get_config() + + return config, input_ids, input_mask + + def get_config(self): + return XCLIPTextConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + dropout=self.dropout, + attention_dropout=self.attention_dropout, + max_position_embeddings=self.max_position_embeddings, + initializer_range=self.initializer_range, + ) + + def create_and_check_model(self, config, input_ids, input_mask): + model = XCLIPTextModel(config=config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + result = model(input_ids, attention_mask=input_mask) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, input_mask = config_and_inputs + inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class XCLIPTextModelTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (XCLIPTextModel,) if is_torch_available() else () + fx_compatible = False + test_pruning = False + test_head_masking = False + + def setUp(self): + self.model_tester = XCLIPTextModelTester(self) + self.config_tester = ConfigTester(self, config_class=XCLIPTextConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_training(self): + pass + + def test_training_gradient_checkpointing(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant(self): + pass + + @unittest.skip( + reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" + ) + def test_training_gradient_checkpointing_use_reentrant_false(self): + pass + + @unittest.skip(reason="X-CLIP does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="XCLIPTextModel has no base class and is not available in MODEL_MAPPING") + def test_save_load_fast_init_from_base(self): + pass + + @unittest.skip(reason="XCLIPTextModel has no base class and is not available in MODEL_MAPPING") + def test_save_load_fast_init_to_base(self): + pass + + @slow + def test_model_from_pretrained(self): + for model_name in XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = XCLIPTextModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +class XCLIPModelTester: + def __init__( + self, + parent, + text_kwargs=None, + vision_kwargs=None, + projection_dim=64, + mit_hidden_size=64, + is_training=True, + ): + if text_kwargs is None: + text_kwargs = {} + if vision_kwargs is None: + vision_kwargs = {} + + self.parent = parent + self.projection_dim = projection_dim + self.mit_hidden_size = mit_hidden_size + self.text_model_tester = XCLIPTextModelTester(parent, **text_kwargs) + self.vision_model_tester = XCLIPVisionModelTester(parent, **vision_kwargs) + self.is_training = is_training + + def prepare_config_and_inputs(self): + text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs() + vision_config, _ = self.vision_model_tester.prepare_config_and_inputs() + pixel_values = floats_tensor( + [ + self.vision_model_tester.batch_size, + self.vision_model_tester.num_frames, + self.vision_model_tester.num_channels, + self.vision_model_tester.image_size, + self.vision_model_tester.image_size, + ] + ) + + config = self.get_config() + + return config, input_ids, attention_mask, pixel_values + + def get_config(self): + return XCLIPConfig.from_text_vision_configs( + self.text_model_tester.get_config(), + self.vision_model_tester.get_config(), + projection_dim=self.projection_dim, + ) + + def create_and_check_model(self, config, input_ids, attention_mask, pixel_values): + model = XCLIPModel(config).to(torch_device).eval() + with torch.no_grad(): + result = model(input_ids, pixel_values, attention_mask) + self.parent.assertEqual( + result.logits_per_video.shape, + (self.vision_model_tester.batch_size, self.text_model_tester.batch_size), + ) + self.parent.assertEqual( + result.logits_per_text.shape, + (self.text_model_tester.batch_size, self.vision_model_tester.batch_size), + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, attention_mask, pixel_values = config_and_inputs + inputs_dict = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "pixel_values": pixel_values, + "return_loss": True, + } + return config, inputs_dict + + +@require_torch +class XCLIPModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (XCLIPModel,) if is_torch_available() else () + pipeline_model_mapping = {"feature-extraction": XCLIPModel} if is_torch_available() else {} + fx_compatible = False + test_head_masking = False + test_pruning = False + test_resize_embeddings = False + test_attention_outputs = False + test_torchscript = False + maxdiff = None + + def setUp(self): + self.model_tester = XCLIPModelTester(self) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + @unittest.skip(reason="Hidden_states is tested in individual model tests") + def test_hidden_states_output(self): + pass + + @unittest.skip(reason="Inputs_embeds is tested in individual model tests") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="Retain_grad is tested in individual model tests") + def test_retain_grad_hidden_states_attentions(self): + pass + + @unittest.skip(reason="XCLIPModel does not have input/output embeddings") + def test_model_common_attributes(self): + pass + + @unittest.skip(reason="XCLIPModel does not support feedforward chunking") + def test_feed_forward_chunking(self): + pass + + # override as the `logit_scale`, `prompts_generator.alpha` parameters require special treatment + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if param.requires_grad: + # check if `logit_scale` is initilized as per the original implementation + if name == "logit_scale": + self.assertAlmostEqual( + param.data.item(), + np.log(1 / 0.07), + delta=1e-3, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + elif name == "prompts_generator.alpha": + self.assertAlmostEqual(param.data.mean().item(), model.config.prompt_alpha) + else: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def _create_and_check_torchscript(self, config, inputs_dict): + if not self.test_torchscript: + return + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.torchscript = True + configs_no_init.return_dict = False + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + + try: + input_ids = inputs_dict["input_ids"] + pixel_values = inputs_dict["pixel_values"] # X-CLIP needs pixel_values + traced_model = torch.jit.trace(model, (input_ids, pixel_values)) + except RuntimeError: + self.fail("Couldn't trace module.") + + with tempfile.TemporaryDirectory() as tmp_dir_name: + pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt") + + try: + torch.jit.save(traced_model, pt_file_name) + except Exception: + self.fail("Couldn't save module.") + + try: + loaded_model = torch.jit.load(pt_file_name) + except Exception: + self.fail("Couldn't load module.") + + model.to(torch_device) + model.eval() + + loaded_model.to(torch_device) + loaded_model.eval() + + model_state_dict = model.state_dict() + loaded_model_state_dict = loaded_model.state_dict() + + non_persistent_buffers = {} + for key in loaded_model_state_dict.keys(): + if key not in model_state_dict.keys(): + non_persistent_buffers[key] = loaded_model_state_dict[key] + + loaded_model_state_dict = { + key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers + } + + self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys())) + + model_buffers = list(model.buffers()) + for non_persistent_buffer in non_persistent_buffers.values(): + found_buffer = False + for i, model_buffer in enumerate(model_buffers): + if torch.equal(non_persistent_buffer, model_buffer): + found_buffer = True + break + + self.assertTrue(found_buffer) + model_buffers.pop(i) + + models_equal = True + for layer_name, p1 in model_state_dict.items(): + p2 = loaded_model_state_dict[layer_name] + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + def test_load_vision_text_config(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # Save XCLIPConfig and check if we can load XCLIPVisionConfig from it + with tempfile.TemporaryDirectory() as tmp_dir_name: + config.save_pretrained(tmp_dir_name) + vision_config = XCLIPVisionConfig.from_pretrained(tmp_dir_name) + self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict()) + + # Save XCLIPConfig and check if we can load XCLIPTextConfig from it + with tempfile.TemporaryDirectory() as tmp_dir_name: + config.save_pretrained(tmp_dir_name) + text_config = XCLIPTextConfig.from_pretrained(tmp_dir_name) + self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict()) + + @slow + def test_model_from_pretrained(self): + for model_name in XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = XCLIPModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on a spaghetti video +def prepare_video(): + file = hf_hub_download( + repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti_8_frames.npy", repo_type="dataset" + ) + video = np.load(file) + return list(video) + + +@require_vision +@require_torch +class XCLIPModelIntegrationTest(unittest.TestCase): + @slow + def test_inference(self): + model_name = "microsoft/xclip-base-patch32" + model = XCLIPModel.from_pretrained(model_name).to(torch_device) + processor = XCLIPProcessor.from_pretrained(model_name) + + video = prepare_video() + inputs = processor( + text=["playing sports", "eating spaghetti", "go shopping"], videos=video, return_tensors="pt", padding=True + ).to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the logits + self.assertEqual( + outputs.logits_per_video.shape, + torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])), + ) + self.assertEqual( + outputs.logits_per_text.shape, + torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])), + ) + + expected_logits = torch.tensor([[14.0181, 20.2771, 14.4776]], device=torch_device) + + self.assertTrue(torch.allclose(outputs.logits_per_video, expected_logits, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_flax_xglm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_flax_xglm.py new file mode 100644 index 0000000000000000000000000000000000000000..8f1c9a5e2a74e79004d7179ca80ca3ecaa3b9ada --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_flax_xglm.py @@ -0,0 +1,346 @@ +# coding=utf-8 +# 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 tempfile +import unittest + +import transformers +from transformers import XGLMConfig, XGLMTokenizer, is_flax_available, is_torch_available +from transformers.testing_utils import is_pt_flax_cross_test, require_flax, require_sentencepiece, slow + +from ...generation.test_flax_utils import FlaxGenerationTesterMixin +from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask + + +if is_flax_available(): + import jax + import jax.numpy as jnp + import numpy as np + + from transformers.modeling_flax_pytorch_utils import ( + convert_pytorch_state_dict_to_flax, + load_flax_weights_in_pytorch_model, + ) + from transformers.models.xglm.modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel + + +if is_torch_available(): + import torch + + +@require_flax +class FlaxXGLMModelTester: + def __init__( + self, + parent, + batch_size=14, + seq_length=7, + is_training=True, + use_input_mask=True, + use_labels=True, + vocab_size=99, + d_model=32, + num_hidden_layers=2, + num_attention_heads=4, + ffn_dim=37, + activation_function="gelu", + activation_dropout=0.1, + attention_dropout=0.1, + max_position_embeddings=512, + initializer_range=0.02, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_labels = use_labels + self.vocab_size = vocab_size + self.hidden_size = d_model + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.ffn_dim = ffn_dim + self.activation_function = activation_function + self.activation_dropout = activation_dropout + self.attention_dropout = attention_dropout + self.max_position_embeddings = max_position_embeddings + self.initializer_range = initializer_range + self.scope = None + self.bos_token_id = 0 + self.eos_token_id = 2 + self.pad_token_id = 1 + + def prepare_config_and_inputs(self): + input_ids = np.clip(ids_tensor([self.batch_size, self.seq_length], self.vocab_size), 3, self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = XGLMConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + num_layers=self.num_hidden_layers, + attention_heads=self.num_attention_heads, + ffn_dim=self.ffn_dim, + activation_function=self.activation_function, + activation_dropout=self.activation_dropout, + attention_dropout=self.attention_dropout, + max_position_embeddings=self.max_position_embeddings, + initializer_range=self.initializer_range, + use_cache=True, + bos_token_id=self.bos_token_id, + eos_token_id=self.eos_token_id, + pad_token_id=self.pad_token_id, + ) + + return (config, input_ids, input_mask) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, input_ids, attention_mask = config_and_inputs + inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask} + return config, inputs_dict + + def prepare_config_and_inputs_for_decoder(self): + config, input_ids, attention_mask = self.prepare_config_and_inputs() + + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + attention_mask, + encoder_hidden_states, + encoder_attention_mask, + ) + + def check_use_cache_forward(self, model_class_name, config, input_ids, attention_mask): + max_decoder_length = 20 + model = model_class_name(config) + + past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length) + attention_mask = jnp.ones((input_ids.shape[0], max_decoder_length), dtype="i4") + + position_ids = jnp.broadcast_to( + jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1) + ) + outputs_cache = model( + input_ids[:, :-1], + attention_mask=attention_mask, + past_key_values=past_key_values, + position_ids=position_ids, + ) + + position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4") + outputs_cache_next = model( + input_ids[:, -1:], + attention_mask=attention_mask, + past_key_values=outputs_cache.past_key_values, + position_ids=position_ids, + ) + + outputs = model(input_ids) + + diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) + self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}") + + def check_use_cache_forward_with_attn_mask(self, model_class_name, config, input_ids, attention_mask): + max_decoder_length = 20 + model = model_class_name(config) + + attention_mask_cache = jnp.concatenate( + [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))], + axis=-1, + ) + + past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length) + position_ids = jnp.broadcast_to( + jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1) + ) + + outputs_cache = model( + input_ids[:, :-1], + attention_mask=attention_mask_cache, + past_key_values=past_key_values, + position_ids=position_ids, + ) + position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4") + outputs_cache_next = model( + input_ids[:, -1:], + past_key_values=outputs_cache.past_key_values, + attention_mask=attention_mask_cache, + position_ids=position_ids, + ) + + outputs = model(input_ids, attention_mask=attention_mask) + diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]))) + self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}") + + +@require_sentencepiece +@require_flax +class FlaxXGLMModelTest(FlaxModelTesterMixin, FlaxGenerationTesterMixin, unittest.TestCase): + all_model_classes = (FlaxXGLMModel, FlaxXGLMForCausalLM) if is_flax_available() else () + all_generative_model_classes = (FlaxXGLMForCausalLM,) if is_flax_available() else () + + def setUp(self): + self.model_tester = FlaxXGLMModelTester(self) + + def test_use_cache_forward(self): + for model_class_name in self.all_model_classes: + config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_use_cache_forward(model_class_name, config, input_ids, attention_mask) + + def test_use_cache_forward_with_attn_mask(self): + for model_class_name in self.all_model_classes: + config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs() + self.model_tester.check_use_cache_forward_with_attn_mask( + model_class_name, config, input_ids, attention_mask + ) + + @slow + def test_batch_generation(self): + tokenizer = XGLMTokenizer.from_pretrained("XGLM", padding_side="left") + inputs = tokenizer(["Hello this is a long string", "Hey"], return_tensors="np", padding=True, truncation=True) + + model = FlaxXGLMForCausalLM.from_pretrained("facebook/xglm-564M") + model.config.num_beams = 1 + model.config.do_sample = False + + jit_generate = jax.jit(model.generate) + + output_sequences = jit_generate(inputs["input_ids"], attention_mask=inputs["attention_mask"]).sequences + + output_string = tokenizer.batch_decode(output_sequences, skip_special_tokens=True) + + expected_string = [ + "Hello this is a long string of questions, but I'm not sure if I'm", + "Hey, I'm a newbie to the forum and I'", + ] + + self.assertListEqual(output_string, expected_string) + + # overwrite from common since `attention_mask` in combination + # with `causal_mask` behaves slighly differently + @is_pt_flax_cross_test + def test_equivalence_pt_to_flax(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + # prepare inputs + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + pt_inputs = {k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()} + + # load corresponding PyTorch class + pt_model_class_name = model_class.__name__[4:] # Skip the "Flax" at the beginning + pt_model_class = getattr(transformers, pt_model_class_name) + + batch_size, seq_length = pt_inputs["input_ids"].shape + rnd_start_indices = np.random.randint(0, seq_length - 1, size=(batch_size,)) + for batch_idx, start_index in enumerate(rnd_start_indices): + pt_inputs["attention_mask"][batch_idx, :start_index] = 0 + pt_inputs["attention_mask"][batch_idx, start_index:] = 1 + prepared_inputs_dict["attention_mask"][batch_idx, :start_index] = 0 + prepared_inputs_dict["attention_mask"][batch_idx, start_index:] = 1 + pt_model = pt_model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + fx_model = model_class(config, dtype=jnp.float32) + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs).to_tuple() + + fx_outputs = fx_model(**prepared_inputs_dict).to_tuple() + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output in zip(fx_outputs, pt_outputs): + self.assert_almost_equals(fx_output[:, -1], pt_output[:, -1].numpy(), 4e-2) + + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = model_class.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**prepared_inputs_dict).to_tuple() + self.assertEqual( + len(fx_outputs_loaded), len(pt_outputs), "Output lengths differ between Flax and PyTorch" + ) + for fx_output_loaded, pt_output in zip(fx_outputs_loaded, pt_outputs): + self.assert_almost_equals(fx_output_loaded[:, -1], pt_output[:, -1].numpy(), 4e-2) + + # overwrite from common since `attention_mask` in combination + # with `causal_mask` behaves slighly differently + @is_pt_flax_cross_test + def test_equivalence_flax_to_pt(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + # prepare inputs + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + pt_inputs = {k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()} + + # load corresponding PyTorch class + pt_model_class_name = model_class.__name__[4:] # Skip the "Flax" at the beginning + pt_model_class = getattr(transformers, pt_model_class_name) + + pt_model = pt_model_class(config).eval() + pt_model.config.use_cache = False + fx_model = model_class(config, dtype=jnp.float32) + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + batch_size, seq_length = pt_inputs["input_ids"].shape + rnd_start_indices = np.random.randint(0, seq_length - 1, size=(batch_size,)) + for batch_idx, start_index in enumerate(rnd_start_indices): + pt_inputs["attention_mask"][batch_idx, :start_index] = 0 + pt_inputs["attention_mask"][batch_idx, start_index:] = 1 + prepared_inputs_dict["attention_mask"][batch_idx, :start_index] = 0 + prepared_inputs_dict["attention_mask"][batch_idx, start_index:] = 1 + + # make sure weights are tied in PyTorch + pt_model.tie_weights() + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs).to_tuple() + + fx_outputs = fx_model(**prepared_inputs_dict).to_tuple() + self.assertEqual(len(fx_outputs), len(pt_outputs), "Output lengths differ between Flax and PyTorch") + for fx_output, pt_output in zip(fx_outputs, pt_outputs): + self.assert_almost_equals(fx_output[:, -1], pt_output[:, -1].numpy(), 4e-2) + + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = pt_model_class.from_pretrained(tmpdirname, from_flax=True) + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs).to_tuple() + + self.assertEqual( + len(fx_outputs), len(pt_outputs_loaded), "Output lengths differ between Flax and PyTorch" + ) + for fx_output, pt_output in zip(fx_outputs, pt_outputs_loaded): + self.assert_almost_equals(fx_output[:, -1], pt_output[:, -1].numpy(), 4e-2) + + @slow + def test_model_from_pretrained(self): + for model_class_name in self.all_model_classes: + model = model_class_name.from_pretrained("facebook/xglm-564M") + outputs = model(np.ones((1, 1))) + self.assertIsNotNone(outputs) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_tf_xglm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_tf_xglm.py new file mode 100644 index 0000000000000000000000000000000000000000..3950ccf6524f1f66c83eedfe6ca7ce97ae2ab94a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_tf_xglm.py @@ -0,0 +1,241 @@ +# coding=utf-8 +# Copyright 2022 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. + +from __future__ import annotations + +import unittest + +from transformers import XGLMConfig, XGLMTokenizer, is_tf_available +from transformers.testing_utils import require_tf, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers.models.xglm.modeling_tf_xglm import ( + TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, + TFXGLMForCausalLM, + TFXGLMModel, + ) + + +@require_tf +class TFXGLMModelTester: + config_cls = XGLMConfig + config_updates = {} + hidden_act = "gelu" + + def __init__( + self, + parent, + batch_size=14, + seq_length=7, + is_training=True, + use_input_mask=True, + use_labels=True, + vocab_size=99, + d_model=32, + num_hidden_layers=2, + num_attention_heads=4, + ffn_dim=37, + activation_function="gelu", + activation_dropout=0.1, + attention_dropout=0.1, + max_position_embeddings=512, + initializer_range=0.02, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_labels = use_labels + self.vocab_size = vocab_size + self.hidden_size = d_model + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.ffn_dim = ffn_dim + self.activation_function = activation_function + self.activation_dropout = activation_dropout + self.attention_dropout = attention_dropout + self.max_position_embeddings = max_position_embeddings + self.initializer_range = initializer_range + self.scope = None + self.bos_token_id = 0 + self.eos_token_id = 2 + self.pad_token_id = 1 + + def get_large_model_config(self): + return XGLMConfig.from_pretrained("facebook/xglm-564M") + + def prepare_config_and_inputs(self): + input_ids = tf.clip_by_value( + ids_tensor([self.batch_size, self.seq_length], self.vocab_size), clip_value_min=0, clip_value_max=3 + ) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config() + + head_mask = floats_tensor([self.num_hidden_layers, self.num_attention_heads], 2) + + return ( + config, + input_ids, + input_mask, + head_mask, + ) + + def get_config(self): + return XGLMConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + num_layers=self.num_hidden_layers, + attention_heads=self.num_attention_heads, + ffn_dim=self.ffn_dim, + activation_function=self.activation_function, + activation_dropout=self.activation_dropout, + attention_dropout=self.attention_dropout, + max_position_embeddings=self.max_position_embeddings, + initializer_range=self.initializer_range, + use_cache=True, + bos_token_id=self.bos_token_id, + eos_token_id=self.eos_token_id, + pad_token_id=self.pad_token_id, + return_dict=True, + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + + ( + config, + input_ids, + input_mask, + head_mask, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "head_mask": head_mask, + } + + return config, inputs_dict + + +@require_tf +class TFXGLMModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () + all_generative_model_classes = (TFXGLMForCausalLM,) if is_tf_available() else () + pipeline_model_mapping = ( + {"feature-extraction": TFXGLMModel, "text-generation": TFXGLMForCausalLM} if is_tf_available() else {} + ) + test_onnx = False + test_missing_keys = False + test_pruning = False + + def setUp(self): + self.model_tester = TFXGLMModelTester(self) + self.config_tester = ConfigTester(self, config_class=XGLMConfig, n_embd=37) + + def test_config(self): + self.config_tester.run_common_tests() + + @slow + def test_model_from_pretrained(self): + for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFXGLMModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor.") + def test_resize_token_embeddings(self): + super().test_resize_token_embeddings() + + +@require_tf +class TFXGLMModelLanguageGenerationTest(unittest.TestCase): + @slow + def test_lm_generate_xglm(self, verify_outputs=True): + model = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M") + input_ids = tf.convert_to_tensor([[2, 268, 9865]], dtype=tf.int32) # The dog + # The dog is a very friendly dog. He is very affectionate and loves to play with other + expected_output_ids = [2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581] # fmt: skip + output_ids = model.generate(input_ids, do_sample=False, num_beams=1) + if verify_outputs: + self.assertListEqual(output_ids[0].numpy().tolist(), expected_output_ids) + + @slow + def test_xglm_sample(self): + tokenizer = XGLMTokenizer.from_pretrained("facebook/xglm-564M") + model = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M") + + tf.random.set_seed(0) + tokenized = tokenizer("Today is a nice day and", return_tensors="tf") + input_ids = tokenized.input_ids + # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) + with tf.device(":/CPU:0"): + output_ids = model.generate(input_ids, do_sample=True, seed=[7, 0]) + output_str = tokenizer.decode(output_ids[0], skip_special_tokens=True) + + EXPECTED_OUTPUT_STR = ( + "Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due" + ) + self.assertEqual(output_str, EXPECTED_OUTPUT_STR) + + @slow + def test_batch_generation(self): + model = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M") + tokenizer = XGLMTokenizer.from_pretrained("facebook/xglm-564M") + + tokenizer.padding_side = "left" + + # use different length sentences to test batching + sentences = [ + "This is an extremelly long sentence that only exists to test the ability of the model to cope with " + "left-padding, such as in batched generation. The output for the sequence below should be the same " + "regardless of whether left padding is applied or not. When", + "Hello, my dog is a little", + ] + + inputs = tokenizer(sentences, return_tensors="tf", padding=True) + input_ids = inputs["input_ids"] + + outputs = model.generate(input_ids=input_ids, attention_mask=inputs["attention_mask"], max_new_tokens=12) + + inputs_non_padded = tokenizer(sentences[0], return_tensors="tf").input_ids + output_non_padded = model.generate(input_ids=inputs_non_padded, max_new_tokens=12) + + inputs_padded = tokenizer(sentences[1], return_tensors="tf").input_ids + output_padded = model.generate(input_ids=inputs_padded, max_new_tokens=12) + + batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True) + non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True) + padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True) + + expected_output_sentence = [ + "This is an extremelly long sentence that only exists to test the ability of the model to cope with " + "left-padding, such as in batched generation. The output for the sequence below should be the same " + "regardless of whether left padding is applied or not. When left padding is applied, the sequence will be " + "a single", + "Hello, my dog is a little bit of a shy one, but he is very friendly", + ] + self.assertListEqual(expected_output_sentence, batch_out_sentence) + self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_xglm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_xglm.py new file mode 100644 index 0000000000000000000000000000000000000000..e482b1b384f3eeec4ad2972863c1f9a772400242 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_modeling_xglm.py @@ -0,0 +1,517 @@ +# coding=utf-8 +# Copyright 2021 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 datetime +import gc +import math +import unittest + +from transformers import XGLMConfig, is_torch_available +from transformers.testing_utils import ( + require_torch, + require_torch_accelerator, + require_torch_fp16, + slow, + torch_device, +) + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMTokenizer + + +class XGLMModelTester: + def __init__( + self, + parent, + batch_size=14, + seq_length=7, + is_training=True, + use_input_mask=True, + use_labels=True, + vocab_size=99, + d_model=32, + num_hidden_layers=2, + num_attention_heads=4, + ffn_dim=37, + activation_function="gelu", + activation_dropout=0.1, + attention_dropout=0.1, + max_position_embeddings=512, + initializer_range=0.02, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_labels = use_labels + self.vocab_size = vocab_size + self.hidden_size = d_model + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.ffn_dim = ffn_dim + self.activation_function = activation_function + self.activation_dropout = activation_dropout + self.attention_dropout = attention_dropout + self.max_position_embeddings = max_position_embeddings + self.initializer_range = initializer_range + self.scope = None + self.bos_token_id = 0 + self.eos_token_id = 2 + self.pad_token_id = 1 + + def get_large_model_config(self): + return XGLMConfig.from_pretrained("facebook/xglm-564M") + + def prepare_config_and_inputs( + self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False + ): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(3) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + config = self.get_config(gradient_checkpointing=gradient_checkpointing) + + head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2) + + return ( + config, + input_ids, + input_mask, + head_mask, + ) + + def get_config( + self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False + ): + return XGLMConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + num_layers=self.num_hidden_layers, + attention_heads=self.num_attention_heads, + ffn_dim=self.ffn_dim, + activation_function=self.activation_function, + activation_dropout=self.activation_dropout, + attention_dropout=self.attention_dropout, + max_position_embeddings=self.max_position_embeddings, + initializer_range=self.initializer_range, + use_cache=True, + bos_token_id=self.bos_token_id, + eos_token_id=self.eos_token_id, + pad_token_id=self.pad_token_id, + gradient_checkpointing=gradient_checkpointing, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + input_mask, + head_mask, + ) = self.prepare_config_and_inputs() + + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + input_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_xglm_model(self, config, input_ids, input_mask, head_mask, *args): + model = XGLMModel(config=config) + model.to(torch_device) + model.eval() + + result = model(input_ids, head_mask=head_mask) + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(len(result.past_key_values), config.num_hidden_layers) + + def create_and_check_xglm_model_past(self, config, input_ids, input_mask, head_mask, *args): + model = XGLMModel(config=config) + model.to(torch_device) + model.eval() + + # first forward pass + outputs = model(input_ids, use_cache=True) + outputs_no_past = model(input_ids, use_cache=False) + + self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) + + output, past = outputs.to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and token_type_ids + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + + output_from_no_past = model(next_input_ids)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_xglm_model_attention_mask_past(self, config, input_ids, input_mask, head_mask, *args): + model = XGLMModel(config=config) + model.to(torch_device) + model.eval() + + # create attention mask + attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) + half_seq_length = self.seq_length // 2 + attn_mask[:, half_seq_length:] = 0 + + # first forward pass + output, past = model(input_ids, attention_mask=attn_mask).to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and attn_mask + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + attn_mask = torch.cat( + [attn_mask, torch.zeros((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)], + dim=1, + ) + + # get two different outputs + output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"] + output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_xglm_model_past_large_inputs(self, config, input_ids, input_mask, head_mask, *args): + model = XGLMModel(config=config) + model.to(torch_device) + model.eval() + + # first forward pass + outputs = model(input_ids, attention_mask=input_mask, use_cache=True) + + output, past = outputs.to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_mask = ids_tensor((self.batch_size, 3), vocab_size=1) + + # append to next input_ids + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past)[ + "last_hidden_state" + ] + self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1]) + + # 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() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, *args): + model = XGLMForCausalLM(config) + model.to(torch_device) + model.eval() + + result = model(input_ids, labels=input_ids) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_forward_and_backwards( + self, config, input_ids, input_mask, head_mask, *args, gradient_checkpointing=False + ): + model = XGLMForCausalLM(config) + model.to(torch_device) + if gradient_checkpointing: + model.gradient_checkpointing_enable() + + result = model(input_ids, labels=input_ids) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + result.loss.backward() + + def create_and_check_xglm_weight_initialization(self, config, *args): + model = XGLMModel(config) + model_std = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers) + for key in model.state_dict().keys(): + if "c_proj" in key and "weight" in key: + self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std), 0.001) + self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0), 0.01) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + + ( + config, + input_ids, + input_mask, + head_mask, + ) = config_and_inputs + + inputs_dict = { + "input_ids": input_ids, + "head_mask": head_mask, + } + + return config, inputs_dict + + +@require_torch +class XGLMModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (XGLMModel, XGLMForCausalLM) if is_torch_available() else () + all_generative_model_classes = (XGLMForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": XGLMModel, "text-generation": XGLMForCausalLM} if is_torch_available() else {} + ) + fx_compatible = True + test_missing_keys = False + test_pruning = False + + def setUp(self): + self.model_tester = XGLMModelTester(self) + self.config_tester = ConfigTester(self, config_class=XGLMConfig, n_embd=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_xglm_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xglm_model(*config_and_inputs) + + def test_xglm_model_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xglm_model_past(*config_and_inputs) + + def test_xglm_model_att_mask_past(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xglm_model_attention_mask_past(*config_and_inputs) + + def test_xglm_model_past_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xglm_model_past_large_inputs(*config_and_inputs) + + def test_xglm_lm_head_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_lm_head_model(*config_and_inputs) + + def test_xglm_gradient_checkpointing(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs, gradient_checkpointing=True) + + def test_xglm_weight_initialization(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xglm_weight_initialization(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = XGLMModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.") + def test_model_parallelism(self): + super().test_model_parallelism() + + +@require_torch +class XGLMModelLanguageGenerationTest(unittest.TestCase): + def tearDown(self): + super().tearDown() + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + torch.cuda.empty_cache() + + def _test_lm_generate_xglm_helper( + self, + gradient_checkpointing=False, + verify_outputs=True, + ): + model = XGLMForCausalLM.from_pretrained("facebook/xglm-564M") + if gradient_checkpointing: + model.gradient_checkpointing_enable() + else: + model.gradient_checkpointing_disable() + model.to(torch_device) + input_ids = torch.tensor([[2, 268, 9865]], dtype=torch.long, device=torch_device) # The dog + # The dog is a very friendly dog. He is very affectionate and loves to play with other + expected_output_ids = [2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581] # fmt: skip + output_ids = model.generate(input_ids, do_sample=False, num_beams=1) + if verify_outputs: + self.assertListEqual(output_ids[0].tolist(), expected_output_ids) + + @slow + def test_batch_generation(self): + model = XGLMForCausalLM.from_pretrained("facebook/xglm-564M") + model.to(torch_device) + tokenizer = XGLMTokenizer.from_pretrained("facebook/xglm-564M") + + tokenizer.padding_side = "left" + + # use different length sentences to test batching + sentences = [ + "This is an extremelly long sentence that only exists to test the ability of the model to cope with " + "left-padding, such as in batched generation. The output for the sequence below should be the same " + "regardless of whether left padding is applied or not. When", + "Hello, my dog is a little", + ] + + inputs = tokenizer(sentences, return_tensors="pt", padding=True) + input_ids = inputs["input_ids"].to(torch_device) + + outputs = model.generate( + input_ids=input_ids, attention_mask=inputs["attention_mask"].to(torch_device), max_new_tokens=12 + ) + + inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device) + output_non_padded = model.generate(input_ids=inputs_non_padded, max_new_tokens=12) + + inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device) + output_padded = model.generate(input_ids=inputs_padded, max_new_tokens=12) + + batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True) + non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True) + padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True) + + expected_output_sentence = [ + "This is an extremelly long sentence that only exists to test the ability of the model to cope with " + "left-padding, such as in batched generation. The output for the sequence below should be the same " + "regardless of whether left padding is applied or not. When left padding is applied, the sequence will be " + "a single", + "Hello, my dog is a little bit of a shy one, but he is very friendly", + ] + self.assertListEqual(expected_output_sentence, batch_out_sentence) + self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence]) + + @slow + def test_lm_generate_xglm(self): + self._test_lm_generate_xglm_helper() + + @slow + def test_lm_generate_xglm_with_gradient_checkpointing(self): + self._test_lm_generate_xglm_helper(gradient_checkpointing=True) + + @slow + def test_xglm_sample(self): + tokenizer = XGLMTokenizer.from_pretrained("facebook/xglm-564M") + model = XGLMForCausalLM.from_pretrained("facebook/xglm-564M") + + torch.manual_seed(0) + tokenized = tokenizer("Today is a nice day and", return_tensors="pt") + input_ids = tokenized.input_ids + output_ids = model.generate(input_ids, do_sample=True, num_beams=1) + output_str = tokenizer.decode(output_ids[0], skip_special_tokens=True) + + EXPECTED_OUTPUT_STRS = [ + # TODO: remove this once we move to torch 2.0 + # torch 1.13.1 + cu116 + "Today is a nice day and the sun is shining. A nice day with warm rainy", + # torch 2.0 + cu117 + "Today is a nice day and the water is still cold. We just stopped off for some fresh", + ] + self.assertIn(output_str, EXPECTED_OUTPUT_STRS) + + @slow + def test_xglm_sample_max_time(self): + tokenizer = XGLMTokenizer.from_pretrained("facebook/xglm-564M") + model = XGLMForCausalLM.from_pretrained("facebook/xglm-564M") + model.to(torch_device) + + torch.manual_seed(0) + tokenized = tokenizer("Today is a nice day and", return_tensors="pt") + input_ids = tokenized.input_ids.to(torch_device) + + MAX_TIME = 0.15 + + start = datetime.datetime.now() + model.generate(input_ids, do_sample=True, max_time=MAX_TIME, max_length=256) + duration = datetime.datetime.now() - start + self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME)) + self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME)) + + start = datetime.datetime.now() + model.generate(input_ids, do_sample=False, max_time=MAX_TIME, max_length=256) + duration = datetime.datetime.now() - start + self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME)) + self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME)) + + start = datetime.datetime.now() + model.generate(input_ids, do_sample=False, num_beams=2, max_time=MAX_TIME, max_length=256) + duration = datetime.datetime.now() - start + self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME)) + self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME)) + + start = datetime.datetime.now() + model.generate(input_ids, do_sample=True, num_beams=2, max_time=MAX_TIME, max_length=256) + duration = datetime.datetime.now() - start + self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME)) + self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME)) + + start = datetime.datetime.now() + model.generate(input_ids, do_sample=False, max_time=None, max_length=256) + duration = datetime.datetime.now() - start + self.assertGreater(duration, datetime.timedelta(seconds=1.25 * MAX_TIME)) + + @require_torch_accelerator + @require_torch_fp16 + def test_batched_nan_fp16(self): + model_name = "facebook/xglm-564M" + tokenizer = XGLMTokenizer.from_pretrained(model_name, use_fast=False, padding_side="left") + + model = XGLMForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, use_cache=True).to(torch_device) + model = model.eval() + + batch = tokenizer(["Who are you?", "Joe Biden is the president of"], padding=True, return_tensors="pt") + + input_ids = batch["input_ids"].to(torch_device) + attention_mask = batch["attention_mask"].to(torch_device) + + with torch.no_grad(): + outputs = model(input_ids, attention_mask=attention_mask) + self.assertFalse( + torch.isnan(outputs.logits[0]).any().item() + ) # the first logits could contain NaNs if it fails diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_tokenization_xglm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_tokenization_xglm.py new file mode 100644 index 0000000000000000000000000000000000000000..61674976a382e2a23e689ecf0b3264b6c2e7d424 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xglm/test_tokenization_xglm.py @@ -0,0 +1,202 @@ +# coding=utf-8 +# Copyright 2021 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 pickle +import shutil +import tempfile +import unittest + +from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow +from transformers.utils import cached_property + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + + +@require_sentencepiece +@require_tokenizers +class XGLMTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = XGLMTokenizer + rust_tokenizer_class = XGLMTokenizerFast + test_rust_tokenizer = True + test_sentencepiece = True + + def setUp(self): + super().setUp() + + # We have a SentencePiece fixture for testing + tokenizer = XGLMTokenizer(SAMPLE_VOCAB, keep_accents=True) + tokenizer.save_pretrained(self.tmpdirname) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "" + token_id = 1 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + self.assertEqual(len(vocab_keys), 1_008) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 1_008) + + def test_full_tokenizer(self): + tokenizer = XGLMTokenizer(SAMPLE_VOCAB, keep_accents=True) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "é", + ".", + ], + ) + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual( + ids, + [ + value + tokenizer.fairseq_offset + for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] + ], + ) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual( + back_tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "", + ".", + ], + ) + + @cached_property + def big_tokenizer(self): + return XGLMTokenizer.from_pretrained("facebook/xglm-564M") + + def test_picklable_without_disk(self): + with tempfile.NamedTemporaryFile() as f: + shutil.copyfile(SAMPLE_VOCAB, f.name) + tokenizer = XGLMTokenizer(f.name, keep_accents=True) + pickled_tokenizer = pickle.dumps(tokenizer) + pickle.loads(pickled_tokenizer) + + def test_rust_and_python_full_tokenizers(self): + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + sequence = "I was born in 92000, and this is falsé." + + tokens = tokenizer.tokenize(sequence) + rust_tokens = rust_tokenizer.tokenize(sequence) + self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + rust_tokenizer = self.get_rust_tokenizer() + ids = tokenizer.encode(sequence) + rust_ids = rust_tokenizer.encode(sequence) + self.assertListEqual(ids, rust_ids) + + @slow + def test_tokenization_base_easy_symbols(self): + symbols = "Hello World!" + original_tokenizer_encodings = [2, 31227, 4447, 35] + + self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) + + @slow + def test_tokenization_base_hard_symbols(self): + symbols = ( + 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' + " add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth" + ) + original_tokenizer_encodings = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: skip + + self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) + + @slow + def test_tokenizer_integration(self): + # fmt: off + expected_encoding = { + 'input_ids': [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], + 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] + } # noqa: E501 + # fmt: on + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, + model_name="facebook/xglm-564M", + padding=False, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_modeling_tf_xlm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_modeling_tf_xlm.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfa33828f70f32f8f515639463e2f871e065713 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_modeling_tf_xlm.py @@ -0,0 +1,398 @@ +# coding=utf-8 +# 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. + + +from __future__ import annotations + +import unittest + +from transformers import is_tf_available +from transformers.testing_utils import require_tf, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers import ( + TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, + TFXLMForMultipleChoice, + TFXLMForQuestionAnsweringSimple, + TFXLMForSequenceClassification, + TFXLMForTokenClassification, + TFXLMModel, + TFXLMWithLMHeadModel, + XLMConfig, + ) + + +class TFXLMModelTester: + def __init__( + self, + parent, + ): + self.parent = parent + self.batch_size = 13 + self.seq_length = 7 + self.is_training = True + self.use_input_lengths = True + self.use_token_type_ids = True + self.use_labels = True + self.gelu_activation = True + self.sinusoidal_embeddings = False + self.causal = False + self.asm = False + self.n_langs = 2 + self.vocab_size = 99 + self.n_special = 0 + self.hidden_size = 32 + self.num_hidden_layers = 2 + self.num_attention_heads = 4 + self.hidden_dropout_prob = 0.1 + self.attention_probs_dropout_prob = 0.1 + self.max_position_embeddings = 512 + self.type_vocab_size = 16 + self.type_sequence_label_size = 2 + self.initializer_range = 0.02 + self.num_labels = 3 + self.num_choices = 4 + self.summary_type = "last" + self.use_proj = True + self.scope = None + self.bos_token_id = 0 + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + input_mask = random_attention_mask([self.batch_size, self.seq_length], dtype=tf.float32) + + input_lengths = None + if self.use_input_lengths: + input_lengths = ( + ids_tensor([self.batch_size], vocab_size=2) + self.seq_length - 2 + ) # small variation of seq_length + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.n_langs) + + sequence_labels = None + token_labels = None + is_impossible_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + is_impossible_labels = ids_tensor([self.batch_size], 2, dtype=tf.float32) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = XLMConfig( + vocab_size=self.vocab_size, + n_special=self.n_special, + emb_dim=self.hidden_size, + n_layers=self.num_hidden_layers, + n_heads=self.num_attention_heads, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + gelu_activation=self.gelu_activation, + sinusoidal_embeddings=self.sinusoidal_embeddings, + asm=self.asm, + causal=self.causal, + n_langs=self.n_langs, + max_position_embeddings=self.max_position_embeddings, + initializer_range=self.initializer_range, + summary_type=self.summary_type, + use_proj=self.use_proj, + bos_token_id=self.bos_token_id, + ) + + return ( + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ) + + def create_and_check_xlm_model( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = TFXLMModel(config=config) + inputs = {"input_ids": input_ids, "lengths": input_lengths, "langs": token_type_ids} + result = model(inputs) + + inputs = [input_ids, input_mask] + result = model(inputs) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_xlm_lm_head( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = TFXLMWithLMHeadModel(config) + + inputs = {"input_ids": input_ids, "lengths": input_lengths, "langs": token_type_ids} + outputs = model(inputs) + + result = outputs + + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_xlm_qa( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = TFXLMForQuestionAnsweringSimple(config) + + inputs = {"input_ids": input_ids, "lengths": input_lengths} + + result = model(inputs) + + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_xlm_sequence_classif( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = TFXLMForSequenceClassification(config) + + inputs = {"input_ids": input_ids, "lengths": input_lengths} + + result = model(inputs) + + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def create_and_check_xlm_for_token_classification( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + config.num_labels = self.num_labels + model = TFXLMForTokenClassification(config=config) + inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_xlm_for_multiple_choice( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + config.num_choices = self.num_choices + model = TFXLMForMultipleChoice(config=config) + multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1)) + multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1)) + multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1)) + inputs = { + "input_ids": multiple_choice_inputs_ids, + "attention_mask": multiple_choice_input_mask, + "token_type_ids": multiple_choice_token_type_ids, + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ) = config_and_inputs + inputs_dict = { + "input_ids": input_ids, + "token_type_ids": token_type_ids, + "langs": token_type_ids, + "lengths": input_lengths, + } + return config, inputs_dict + + +@require_tf +class TFXLMModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TFXLMModel, + TFXLMWithLMHeadModel, + TFXLMForSequenceClassification, + TFXLMForQuestionAnsweringSimple, + TFXLMForTokenClassification, + TFXLMForMultipleChoice, + ) + if is_tf_available() + else () + ) + all_generative_model_classes = ( + (TFXLMWithLMHeadModel,) if is_tf_available() else () + ) # TODO (PVP): Check other models whether language generation is also applicable + pipeline_model_mapping = ( + { + "feature-extraction": TFXLMModel, + "fill-mask": TFXLMWithLMHeadModel, + "question-answering": TFXLMForQuestionAnsweringSimple, + "text-classification": TFXLMForSequenceClassification, + "text-generation": TFXLMWithLMHeadModel, + "token-classification": TFXLMForTokenClassification, + "zero-shot": TFXLMForSequenceClassification, + } + if is_tf_available() + else {} + ) + test_head_masking = False + test_onnx = False + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if ( + pipeline_test_casse_name == "QAPipelineTests" + and tokenizer_name is not None + and not tokenizer_name.endswith("Fast") + ): + # `QAPipelineTests` fails for a few models when the slower tokenizer are used. + # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) + # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer + return True + + return False + + def setUp(self): + self.model_tester = TFXLMModelTester(self) + self.config_tester = ConfigTester(self, config_class=XLMConfig, emb_dim=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_xlm_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_model(*config_and_inputs) + + def test_xlm_lm_head(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_lm_head(*config_and_inputs) + + def test_xlm_qa(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_qa(*config_and_inputs) + + def test_xlm_sequence_classif(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_sequence_classif(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_for_token_classification(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_for_multiple_choice(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFXLMModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_tf +class TFXLMModelLanguageGenerationTest(unittest.TestCase): + @slow + def test_lm_generate_xlm_mlm_en_2048(self): + model = TFXLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048") + input_ids = tf.convert_to_tensor([[14, 447]], dtype=tf.int32) # the president + expected_output_ids = [ + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + ] # the president the president the president the president the president the president the president the president the president the president + # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference + output_ids = model.generate(input_ids, do_sample=False) + self.assertListEqual(output_ids[0].numpy().tolist(), expected_output_ids) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_modeling_xlm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_modeling_xlm.py new file mode 100644 index 0000000000000000000000000000000000000000..b551e7e645d5163090a99877a039cff034082981 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_modeling_xlm.py @@ -0,0 +1,544 @@ +# coding=utf-8 +# 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 unittest + +from transformers import XLMConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + XLMForMultipleChoice, + XLMForQuestionAnswering, + XLMForQuestionAnsweringSimple, + XLMForSequenceClassification, + XLMForTokenClassification, + XLMModel, + XLMWithLMHeadModel, + ) + from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST + + +class XLMModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_lengths=True, + use_token_type_ids=True, + use_labels=True, + gelu_activation=True, + sinusoidal_embeddings=False, + causal=False, + asm=False, + n_langs=2, + vocab_size=99, + n_special=0, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=2, + num_choices=4, + summary_type="last", + use_proj=True, + scope=None, + bos_token_id=0, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_lengths = use_input_lengths + self.use_token_type_ids = use_token_type_ids + self.use_labels = use_labels + self.gelu_activation = gelu_activation + self.sinusoidal_embeddings = sinusoidal_embeddings + self.causal = causal + self.asm = asm + self.n_langs = n_langs + self.vocab_size = vocab_size + self.n_special = n_special + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.max_position_embeddings = max_position_embeddings + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.summary_type = summary_type + self.use_proj = use_proj + self.scope = scope + self.bos_token_id = bos_token_id + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + input_lengths = None + if self.use_input_lengths: + input_lengths = ( + ids_tensor([self.batch_size], vocab_size=2) + self.seq_length - 2 + ) # small variation of seq_length + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.n_langs) + + sequence_labels = None + token_labels = None + is_impossible_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + is_impossible_labels = ids_tensor([self.batch_size], 2).float() + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return ( + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ) + + def get_config(self): + return XLMConfig( + vocab_size=self.vocab_size, + n_special=self.n_special, + emb_dim=self.hidden_size, + n_layers=self.num_hidden_layers, + n_heads=self.num_attention_heads, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + gelu_activation=self.gelu_activation, + sinusoidal_embeddings=self.sinusoidal_embeddings, + asm=self.asm, + causal=self.causal, + n_langs=self.n_langs, + max_position_embeddings=self.max_position_embeddings, + initializer_range=self.initializer_range, + summary_type=self.summary_type, + use_proj=self.use_proj, + num_labels=self.num_labels, + bos_token_id=self.bos_token_id, + ) + + def create_and_check_xlm_model( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = XLMModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, lengths=input_lengths, langs=token_type_ids) + result = model(input_ids, langs=token_type_ids) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_xlm_lm_head( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = XLMWithLMHeadModel(config) + model.to(torch_device) + model.eval() + + result = model(input_ids, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_xlm_simple_qa( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = XLMForQuestionAnsweringSimple(config) + model.to(torch_device) + model.eval() + + outputs = model(input_ids) + + outputs = model(input_ids, start_positions=sequence_labels, end_positions=sequence_labels) + result = outputs + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_xlm_qa( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = XLMForQuestionAnswering(config) + model.to(torch_device) + model.eval() + + result = model(input_ids) + + result_with_labels = model( + input_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + cls_index=sequence_labels, + is_impossible=is_impossible_labels, + p_mask=input_mask, + ) + + result_with_labels = model( + input_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + cls_index=sequence_labels, + is_impossible=is_impossible_labels, + ) + + (total_loss,) = result_with_labels.to_tuple() + + result_with_labels = model(input_ids, start_positions=sequence_labels, end_positions=sequence_labels) + + (total_loss,) = result_with_labels.to_tuple() + + self.parent.assertEqual(result_with_labels.loss.shape, ()) + self.parent.assertEqual(result.start_top_log_probs.shape, (self.batch_size, model.config.start_n_top)) + self.parent.assertEqual(result.start_top_index.shape, (self.batch_size, model.config.start_n_top)) + self.parent.assertEqual( + result.end_top_log_probs.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top) + ) + self.parent.assertEqual( + result.end_top_index.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top) + ) + self.parent.assertEqual(result.cls_logits.shape, (self.batch_size,)) + + def create_and_check_xlm_sequence_classif( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + model = XLMForSequenceClassification(config) + model.to(torch_device) + model.eval() + + result = model(input_ids) + result = model(input_ids, labels=sequence_labels) + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + + def create_and_check_xlm_token_classif( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + config.num_labels = self.num_labels + model = XLMForTokenClassification(config) + model.to(torch_device) + model.eval() + + result = model(input_ids, attention_mask=input_mask, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_xlm_for_multiple_choice( + self, + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ): + config.num_choices = self.num_choices + model = XLMForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_lengths, + sequence_labels, + token_labels, + is_impossible_labels, + choice_labels, + input_mask, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} + return config, inputs_dict + + +@require_torch +class XLMModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + XLMModel, + XLMWithLMHeadModel, + XLMForQuestionAnswering, + XLMForSequenceClassification, + XLMForQuestionAnsweringSimple, + XLMForTokenClassification, + XLMForMultipleChoice, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = ( + (XLMWithLMHeadModel,) if is_torch_available() else () + ) # TODO (PVP): Check other models whether language generation is also applicable + pipeline_model_mapping = ( + { + "feature-extraction": XLMModel, + "fill-mask": XLMWithLMHeadModel, + "question-answering": XLMForQuestionAnsweringSimple, + "text-classification": XLMForSequenceClassification, + "text-generation": XLMWithLMHeadModel, + "token-classification": XLMForTokenClassification, + "zero-shot": XLMForSequenceClassification, + } + if is_torch_available() + else {} + ) + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if ( + pipeline_test_casse_name == "QAPipelineTests" + and tokenizer_name is not None + and not tokenizer_name.endswith("Fast") + ): + # `QAPipelineTests` fails for a few models when the slower tokenizer are used. + # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) + # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer + return True + + return False + + # XLM has 2 QA models -> need to manually set the correct labels for one of them here + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) + + if return_labels: + if model_class.__name__ == "XLMForQuestionAnswering": + inputs_dict["start_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + inputs_dict["end_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + + return inputs_dict + + def setUp(self): + self.model_tester = XLMModelTester(self) + self.config_tester = ConfigTester(self, config_class=XLMConfig, emb_dim=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_xlm_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_model(*config_and_inputs) + + def test_xlm_lm_head(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_lm_head(*config_and_inputs) + + def test_xlm_simple_qa(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_simple_qa(*config_and_inputs) + + def test_xlm_qa(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_qa(*config_and_inputs) + + def test_xlm_sequence_classif(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_sequence_classif(*config_and_inputs) + + def test_xlm_token_classif(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_token_classif(*config_and_inputs) + + def test_xlm_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlm_for_multiple_choice(*config_and_inputs) + + def _check_attentions_for_generate( + self, batch_size, attentions, min_length, max_length, config, use_cache=False, num_beam_groups=1 + ): + self.assertIsInstance(attentions, tuple) + self.assertListEqual( + [isinstance(iter_attentions, tuple) for iter_attentions in attentions], [True] * len(attentions) + ) + self.assertEqual(len(attentions), (max_length - min_length) * num_beam_groups) + + for idx, iter_attentions in enumerate(attentions): + # adds PAD dummy token + tgt_len = min_length + idx + 1 + src_len = min_length + idx + 1 + + expected_shape = ( + batch_size * num_beam_groups, + config.num_attention_heads, + tgt_len, + src_len, + ) + # check attn size + self.assertListEqual( + [layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(iter_attentions) + ) + + def _check_hidden_states_for_generate( + self, batch_size, hidden_states, min_length, max_length, config, use_cache=False, num_beam_groups=1 + ): + self.assertIsInstance(hidden_states, tuple) + self.assertListEqual( + [isinstance(iter_hidden_states, tuple) for iter_hidden_states in hidden_states], + [True] * len(hidden_states), + ) + self.assertEqual(len(hidden_states), (max_length - min_length) * num_beam_groups) + + for idx, iter_hidden_states in enumerate(hidden_states): + # adds PAD dummy token + seq_len = min_length + idx + 1 + expected_shape = (batch_size * num_beam_groups, seq_len, config.hidden_size) + # check hidden size + self.assertListEqual( + [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states], + [expected_shape] * len(iter_hidden_states), + ) + pass + + @slow + def test_model_from_pretrained(self): + for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = XLMModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_torch +class XLMModelLanguageGenerationTest(unittest.TestCase): + @slow + def test_lm_generate_xlm_mlm_en_2048(self): + model = XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048") + model.to(torch_device) + input_ids = torch.tensor([[14, 447]], dtype=torch.long, device=torch_device) # the president + expected_output_ids = [ + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + 14, + 447, + ] # the president the president the president the president the president the president the president the president the president the president + # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference + output_ids = model.generate(input_ids, do_sample=False) + self.assertListEqual(output_ids[0].cpu().numpy().tolist(), expected_output_ids) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_tokenization_xlm.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_tokenization_xlm.py new file mode 100644 index 0000000000000000000000000000000000000000..6e3103521585c83ffe8f424cd6a97ba5d91001d8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm/test_tokenization_xlm.py @@ -0,0 +1,97 @@ +# coding=utf-8 +# 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 transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer +from transformers.testing_utils import slow + +from ...test_tokenization_common import TokenizerTesterMixin + + +class XLMTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = XLMTokenizer + test_rust_tokenizer = False + + def setUp(self): + super().setUp() + + # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt + vocab = [ + "l", + "o", + "w", + "e", + "r", + "s", + "t", + "i", + "d", + "n", + "w", + "r", + "t", + "lo", + "low", + "er", + "low", + "lowest", + "newer", + "wider", + "", + ] + vocab_tokens = dict(zip(vocab, range(len(vocab)))) + merges = ["l o 123", "lo w 1456", "e r 1789", ""] + + 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") as fp: + fp.write(json.dumps(vocab_tokens)) + with open(self.merges_file, "w") as fp: + fp.write("\n".join(merges)) + + def get_input_output_texts(self, tokenizer): + input_text = "lower newer" + output_text = "lower newer" + return input_text, output_text + + def test_full_tokenizer(self): + """Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt""" + tokenizer = XLMTokenizer(self.vocab_file, self.merges_file) + + text = "lower" + bpe_tokens = ["low", "er"] + tokens = tokenizer.tokenize(text) + self.assertListEqual(tokens, bpe_tokens) + + input_tokens = tokens + [""] + input_bpe_tokens = [14, 15, 20] + self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens) + + @slow + def test_sequence_builders(self): + tokenizer = XLMTokenizer.from_pretrained("xlm-mlm-en-2048") + + text = tokenizer.encode("sequence builders", add_special_tokens=False) + text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False) + + encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_sentence == [0] + text + [1] + assert encoded_pair == [0] + text + [1] + text_2 + [1] diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_prophetnet/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_prophetnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_prophetnet/test_modeling_xlm_prophetnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_prophetnet/test_modeling_xlm_prophetnet.py new file mode 100644 index 0000000000000000000000000000000000000000..614ccd6ebc2b36026963464cfb65439bcedeceef --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_prophetnet/test_modeling_xlm_prophetnet.py @@ -0,0 +1,150 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team, The Microsoft Research team. +# +# 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 unittest + +from transformers import is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + + +if is_torch_available(): + import torch + + from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer + + +@require_torch +class XLMProphetNetModelIntegrationTest(unittest.TestCase): + @slow + def test_pretrained_checkpoint_hidden_states(self): + model = XLMProphetNetForConditionalGeneration.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") + model.to(torch_device) + + # encoder-decoder outputs + encoder_ids = torch.tensor([[17, 96208, 103471, 2]]).to(torch_device) + decoder_prev_ids = torch.tensor( + [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]] + ).to(torch_device) + output = model( + input_ids=encoder_ids, attention_mask=None, encoder_outputs=None, decoder_input_ids=decoder_prev_ids + ) + output_predited_logis = output[0] + expected_shape = torch.Size((1, 14, 250012)) + self.assertEqual(output_predited_logis.shape, expected_shape) + expected_slice = torch.tensor( + [[[-6.3986, -8.2391, 12.5189], [-6.3289, -8.0864, 12.6211], [-6.2418, -8.0445, 12.7968]]] + ).to(torch_device) + self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3], expected_slice, atol=1e-4)) + + # encoder outputs + encoder_outputs = model.prophetnet.encoder(encoder_ids)[0] + expected_encoder_outputs_slice = torch.tensor( + [[[-1.4260, -0.7628, 0.8453], [-1.4719, -0.1391, 0.7807], [-1.7678, 0.0114, 0.4646]]] + ).to(torch_device) + expected_shape_encoder = torch.Size((1, 4, 1024)) + self.assertEqual(encoder_outputs.shape, expected_shape_encoder) + self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3], expected_encoder_outputs_slice, atol=1e-4)) + + # decoder outputs + decoder_outputs = model.prophetnet.decoder( + decoder_prev_ids, + encoder_hidden_states=encoder_outputs, + ) + predicting_streams = decoder_outputs[1].view(1, model.config.ngram, 14, -1) + predicting_streams_logits = model.lm_head(predicting_streams) + next_first_stream_logits = predicting_streams_logits[:, 0] + self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3], expected_slice, atol=1e-4)) + + @slow + def test_ntg_hidden_states(self): + model = XLMProphetNetForConditionalGeneration.from_pretrained( + "microsoft/xprophetnet-large-wiki100-cased-xglue-ntg" + ) + model.to(torch_device) + + encoder_ids = torch.tensor([[17, 96208, 103471, 2]]).to(torch_device) + decoder_prev_ids = torch.tensor( + [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]] + ).to(torch_device) + output = model( + input_ids=encoder_ids, attention_mask=None, encoder_outputs=None, decoder_input_ids=decoder_prev_ids + ) + output_predited_logis = output[0] + expected_shape = torch.Size((1, 14, 250012)) + self.assertEqual(output_predited_logis.shape, expected_shape) + # compare the actual values for a slice. + expected_slice = torch.tensor( + [[[-9.2253, -9.7173, -6.3529], [-7.6701, -9.0145, -1.9382], [-8.0195, -7.0004, -0.1523]]] + ).to(torch_device) + + self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3], expected_slice, atol=1e-4)) + + @slow + def test_xprophetnet_ntg_inference(self): + model = XLMProphetNetForConditionalGeneration.from_pretrained( + "microsoft/xprophetnet-large-wiki100-cased-xglue-ntg" + ) + model.to(torch_device) + model.config.max_length = 512 + + tokenizer = XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased-xglue-ntg") + + EN_SENTENCE = ( + "Microsoft Corporation intends to officially end free support for the Windows 7 operating system after" + " January 14, 2020, according to the official portal of the organization. From that day, users of this" + " system will not be able to receive security updates, which could make their computers vulnerable to" + " cyber attacks." + ) + RU_SENTENCE = ( + "орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7" + " после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи" + " этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми" + " к кибератакам." + ) + ZH_SENTENCE = "根据该组织的官方门户网站,微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起,该系统的用户将无法接收安全更新,这可能会使他们的计算机容易受到网络攻击。" + + input_ids = tokenizer( + [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE], padding=True, max_length=255, return_tensors="pt" + ).input_ids + input_ids = input_ids.to(torch_device) + + summary_ids = model.generate( + input_ids, num_beams=10, length_penalty=1.0, no_repeat_ngram_size=3, early_stopping=True + ) + generated_titles = [tokenizer.decode(g, skip_special_tokens=True) for g in summary_ids] + EXPECTED_TITLE_EN = "Microsoft to end Windows 7 free support after January 14, 2020" + EXPECTED_TITLE_RU = "Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года" + EXPECTED_TITLE_ZH = "微软打算终止对Windows 7操作系统的免费支持" + self.assertListEqual( + [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH], + generated_titles, + ) + + summary_ids_beam1 = model.generate( + input_ids, num_beams=1, length_penalty=1.0, no_repeat_ngram_size=3, early_stopping=True + ) + generated_titles_beam1_tok = [ + tokenizer.convert_ids_to_tokens(g, skip_special_tokens=True) for g in summary_ids_beam1 + ] + EXPECTED_TITLE_EN_BEAM1_TOK = "▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7".split(" ") + EXPECTED_TITLE_RU_BEAM1_TOK = "▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года".split( + " " + ) + EXPECTED_TITLE_ZH_BEAM1_TOK = "微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持".split(" ") + self.assertListEqual( + [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK], + generated_titles_beam1_tok, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_prophetnet/test_tokenization_xlm_prophetnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_prophetnet/test_tokenization_xlm_prophetnet.py new file mode 100644 index 0000000000000000000000000000000000000000..679e808dc97505da65c4fbeb77b2b609ef965db0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_prophetnet/test_tokenization_xlm_prophetnet.py @@ -0,0 +1,153 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team, The Microsoft Research team. +# +# 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 unittest + +from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer +from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow +from transformers.utils import cached_property + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + + +@require_sentencepiece +class XLMProphetNetTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = XLMProphetNetTokenizer + test_rust_tokenizer = False + test_sentencepiece = True + + def setUp(self): + super().setUp() + + # We have a SentencePiece fixture for testing + tokenizer = XLMProphetNetTokenizer(SAMPLE_VOCAB, keep_accents=True) + tokenizer.save_pretrained(self.tmpdirname) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "[PAD]" + token_id = 0 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "[PAD]") + self.assertEqual(vocab_keys[1], "[CLS]") + self.assertEqual(vocab_keys[-1], "j") + self.assertEqual(len(vocab_keys), 1_012) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 1_012) + + def test_full_tokenizer(self): + tokenizer = XLMProphetNetTokenizer(SAMPLE_VOCAB, keep_accents=True) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "é", + ".", + ], + ) + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual( + ids, + [ + value + tokenizer.fairseq_offset + for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] + ], + ) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual( + back_tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "[UNK]", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "[UNK]", + ".", + ], + ) + + @cached_property + def big_tokenizer(self): + return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") + + @slow + def test_tokenization_base_easy_symbols(self): + symbols = "Hello World!" + original_tokenizer_encodings = [35389, 6672, 49, 2] + self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) + + @slow + def test_tokenizer_integration(self): + expected_encoding = {'input_ids': [[11073, 82783, 18, 26, 82783, 549, 51540, 248, 17209, 1301, 217, 20, 215186, 1325, 147, 17209, 1301, 217, 20, 56370, 53, 122020, 20, 16477, 27, 87355, 4548, 20, 4728, 78392, 17, 159969, 18, 26, 24491, 629, 15, 538, 22704, 5439, 15, 2788, 24491, 9885, 15, 43534, 605, 15, 814, 18403, 33200, 29, 15, 43534, 24458, 12410, 111, 24966, 83669, 9637, 144068, 26, 850, 22346, 27, 147, 24966, 83669, 83490, 26, 39113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 122020, 115785, 34, 816, 1339, 46887, 18, 147, 53905, 1951, 42238, 41170, 17732, 834, 436, 15, 27523, 98733, 217, 147, 5542, 4981, 930, 17347, 16, 2], [20091, 629, 94, 82786, 58, 490, 20, 1528, 84, 53905, 344, 80592, 110128, 18822, 5267, 1306, 62, 152537, 308, 7997, 401, 124427, 549, 35442, 225, 109, 15055, 25748, 147, 7119, 43712, 34, 767, 135366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63784, 119466, 17, 147808, 88214, 18, 656, 81, 32, 3296, 10280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: skip + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, + model_name="microsoft/xprophetnet-large-wiki100-cased", + revision="1acad1643ddd54a44df6a1b797ada8373685d90e", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_flax_xlm_roberta.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_flax_xlm_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..0ceaa739f3fa862062af28a1dcbfe234ac55256c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_flax_xlm_roberta.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# Copyright 2022 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 unittest + +from transformers import AutoTokenizer, is_flax_available +from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow + + +if is_flax_available(): + import jax.numpy as jnp + + from transformers import FlaxXLMRobertaModel + + +@require_sentencepiece +@require_tokenizers +@require_flax +class FlaxXLMRobertaModelIntegrationTest(unittest.TestCase): + @slow + def test_flax_xlm_roberta_base(self): + model = FlaxXLMRobertaModel.from_pretrained("xlm-roberta-base") + tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base") + text = "The dog is cute and lives in the garden house" + input_ids = jnp.array([tokenizer.encode(text)]) + + expected_output_shape = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim + expected_output_values_last_dim = jnp.array( + [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] + ) + + output = model(input_ids)["last_hidden_state"] + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(jnp.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_tf_xlm_roberta.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_tf_xlm_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..1ecac55310fb04e5713bd4d2a8562e9e03f34342 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_tf_xlm_roberta.py @@ -0,0 +1,59 @@ +# coding=utf-8 +# 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. + +from __future__ import annotations + +import unittest + +from transformers import is_tf_available +from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow + + +if is_tf_available(): + import numpy as np + import tensorflow as tf + + from transformers import TFXLMRobertaModel + + +@require_tf +@require_sentencepiece +@require_tokenizers +class TFFlaubertModelIntegrationTest(unittest.TestCase): + @slow + def test_output_embeds_base_model(self): + model = TFXLMRobertaModel.from_pretrained("jplu/tf-xlm-roberta-base") + + features = { + "input_ids": tf.convert_to_tensor([[0, 2646, 10269, 83, 99942, 2]], dtype=tf.int32), # "My dog is cute" + "attention_mask": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]], dtype=tf.int32), + } + + output = model(features)["last_hidden_state"] + expected_shape = tf.TensorShape((1, 6, 768)) + self.assertEqual(output.shape, expected_shape) + # compare the actual values for a slice. + expected_slice = tf.convert_to_tensor( + [ + [ + [0.0681762, 0.10894451, 0.06772504], + [-0.06423668, 0.02366615, 0.04329344], + [-0.06057295, 0.09974135, -0.00070584], + ] + ], + dtype=tf.float32, + ) + + self.assertTrue(np.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_xlm_roberta.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_xlm_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..ca9db17270dcea8b801ca030776520142b77a863 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_modeling_xlm_roberta.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# 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 unittest + +from transformers import is_torch_available +from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow + + +if is_torch_available(): + import torch + + from transformers import XLMRobertaModel + + +@require_sentencepiece +@require_tokenizers +@require_torch +class XLMRobertaModelIntegrationTest(unittest.TestCase): + @slow + def test_xlm_roberta_base(self): + model = XLMRobertaModel.from_pretrained("xlm-roberta-base") + input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) + # The dog is cute and lives in the garden house + + expected_output_shape = torch.Size((1, 12, 768)) # batch_size, sequence_length, embedding_vector_dim + expected_output_values_last_dim = torch.tensor( + [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] + ) + # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') + # xlmr.eval() + # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] + with torch.no_grad(): + output = model(input_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) + + @slow + def test_xlm_roberta_large(self): + model = XLMRobertaModel.from_pretrained("xlm-roberta-large") + input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) + # The dog is cute and lives in the garden house + + expected_output_shape = torch.Size((1, 12, 1024)) # batch_size, sequence_length, embedding_vector_dim + expected_output_values_last_dim = torch.tensor( + [[-0.0699, -0.0318, 0.0705, -0.1241, 0.0999, -0.0520, 0.1004, -0.1838, -0.4704, 0.1437, 0.0821, 0.0126]] + ) + # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') + # xlmr.eval() + # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] + with torch.no_grad(): + output = model(input_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_tokenization_xlm_roberta.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_tokenization_xlm_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..1cba1c01d5808189b2abf4328b3c9729e1d33009 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta/test_tokenization_xlm_roberta.py @@ -0,0 +1,343 @@ +# coding=utf-8 +# 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 pickle +import shutil +import tempfile +import unittest + +from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow +from transformers.utils import cached_property + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + + +@require_sentencepiece +@require_tokenizers +class XLMRobertaTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = XLMRobertaTokenizer + rust_tokenizer_class = XLMRobertaTokenizerFast + test_rust_tokenizer = True + test_sentencepiece = True + + def setUp(self): + super().setUp() + + # We have a SentencePiece fixture for testing + tokenizer = XLMRobertaTokenizer(SAMPLE_VOCAB, keep_accents=True) + tokenizer.save_pretrained(self.tmpdirname) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "" + token_id = 1 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + self.assertEqual(vocab_keys[-1], "") + self.assertEqual(len(vocab_keys), 1_002) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 1_002) + + def test_full_tokenizer(self): + tokenizer = XLMRobertaTokenizer(SAMPLE_VOCAB, keep_accents=True) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual( + tokenizer.convert_tokens_to_ids(tokens), + [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]], + ) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "é", + ".", + ], + ) + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual( + ids, + [ + value + tokenizer.fairseq_offset + for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] + # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ + ], + ) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual( + back_tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "", + ".", + ], + ) + + # overwrite from test_tokenization_common to speed up test + def test_save_pretrained(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + self.tokenizers_list[0] = (self.rust_tokenizer_class, "hf-internal-testing/tiny-xlm-roberta", {}) + 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) + + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # Checks it save with the same files + the tokenizer.json file for the fast one + self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files)) + tokenizer_r_files = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f) + self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) + # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) + + shutil.rmtree(tmpdirname2) + + # Save tokenizer rust, legacy_format=True + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=True) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # Checks it save with the same files + self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + + shutil.rmtree(tmpdirname2) + + # Save tokenizer rust, legacy_format=False + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=False) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # Checks it saved the tokenizer.json file + self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files)) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + + shutil.rmtree(tmpdirname2) + + @cached_property + def big_tokenizer(self): + return XLMRobertaTokenizer.from_pretrained("xlm-roberta-base") + + def test_picklable_without_disk(self): + with tempfile.NamedTemporaryFile() as f: + shutil.copyfile(SAMPLE_VOCAB, f.name) + tokenizer = XLMRobertaTokenizer(f.name, keep_accents=True) + pickled_tokenizer = pickle.dumps(tokenizer) + pickle.loads(pickled_tokenizer) + + def test_rust_and_python_full_tokenizers(self): + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + sequence = "I was born in 92000, and this is falsé." + + tokens = tokenizer.tokenize(sequence) + rust_tokens = rust_tokenizer.tokenize(sequence) + self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + rust_tokenizer = self.get_rust_tokenizer() + ids = tokenizer.encode(sequence) + rust_ids = rust_tokenizer.encode(sequence) + self.assertListEqual(ids, rust_ids) + + @slow + def test_tokenization_base_easy_symbols(self): + symbols = "Hello World!" + original_tokenizer_encodings = [0, 35378, 6661, 38, 2] + # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer + # xlmr.eval() + # xlmr.encode(symbols) + + self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) + + @slow + def test_tokenization_base_hard_symbols(self): + symbols = ( + 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' + " add words that should not exsist and be tokenized to , such as saoneuhaoesuth" + ) + original_tokenizer_encodings = [ + 0, + 3293, + 83, + 10, + 4552, + 4989, + 7986, + 678, + 10, + 5915, + 111, + 179459, + 124850, + 4, + 6044, + 237, + 12, + 6, + 5, + 6, + 4, + 6780, + 705, + 15, + 1388, + 44, + 378, + 10114, + 711, + 152, + 20, + 6, + 5, + 22376, + 642, + 1221, + 15190, + 34153, + 450, + 5608, + 959, + 1119, + 57702, + 136, + 186, + 47, + 1098, + 29367, + 47, + # 4426, # What fairseq tokenizes from "": "_<" + # 3678, # What fairseq tokenizes from "": "unk" + # 2740, # What fairseq tokenizes from "": ">" + 3, # What we tokenize from "": "" + 6, # Residue from the tokenization: an extra sentencepiece underline + 4, + 6044, + 237, + 6284, + 50901, + 528, + 31, + 90, + 34, + 927, + 2, + ] + # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer + # xlmr.eval() + # xlmr.encode(symbols) + + self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) + + @slow + def test_tokenizer_integration(self): + expected_encoding = {'input_ids': [[0, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 5428, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 12399, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 122009, 115774, 23, 805, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [0, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: skip + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, + model_name="xlm-roberta-base", + revision="d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta_xl/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta_xl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py new file mode 100644 index 0000000000000000000000000000000000000000..828d6a02a6a36872e992e6fca664b07f3410d717 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py @@ -0,0 +1,557 @@ +# coding=utf-8 +# Copyright 2022 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 unittest + +from transformers import XLMRobertaXLConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + XLMRobertaXLForCausalLM, + XLMRobertaXLForMaskedLM, + XLMRobertaXLForMultipleChoice, + XLMRobertaXLForQuestionAnswering, + XLMRobertaXLForSequenceClassification, + XLMRobertaXLForTokenClassification, + XLMRobertaXLModel, + ) + from transformers.models.xlm_roberta_xl.modeling_xlm_roberta_xl import ( + XLMRobertaXLEmbeddings, + create_position_ids_from_input_ids, + ) + + +class XLMRobertaXLModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def get_config(self): + return XLMRobertaXLConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = XLMRobertaXLModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = XLMRobertaXLModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = XLMRobertaXLForCausalLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = XLMRobertaXLForCausalLM(config=config).to(torch_device).eval() + + # make sure that ids don't start with pad token + mask = input_ids.ne(config.pad_token_id).long() + input_ids = input_ids * mask + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + + # make sure that ids don't start with pad token + mask = next_tokens.ne(config.pad_token_id).long() + next_tokens = next_tokens * mask + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # 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)) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = XLMRobertaXLForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = XLMRobertaXLForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = XLMRobertaXLForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = XLMRobertaXLForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class XLMRobertaXLModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + XLMRobertaXLForCausalLM, + XLMRobertaXLForMaskedLM, + XLMRobertaXLModel, + XLMRobertaXLForSequenceClassification, + XLMRobertaXLForTokenClassification, + XLMRobertaXLForMultipleChoice, + XLMRobertaXLForQuestionAnswering, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (XLMRobertaXLForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": XLMRobertaXLModel, + "fill-mask": XLMRobertaXLForMaskedLM, + "question-answering": XLMRobertaXLForQuestionAnswering, + "text-classification": XLMRobertaXLForSequenceClassification, + "text-generation": XLMRobertaXLForCausalLM, + "token-classification": XLMRobertaXLForTokenClassification, + "zero-shot": XLMRobertaXLForSequenceClassification, + } + if is_torch_available() + else {} + ) + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): + return True + + return False + + def setUp(self): + self.model_tester = XLMRobertaXLModelTester(self) + self.config_tester = ConfigTester(self, config_class=XLMRobertaXLConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_as_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_model_as_decoder_with_default_input_mask(self): + # This regression test was failing with PyTorch < 1.3 + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = self.model_tester.prepare_config_and_inputs_for_decoder() + + input_mask = None + + self.model_tester.create_and_check_model_as_decoder( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def test_for_causal_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_for_causal_lm(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs_relative_pos_emb(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + config_and_inputs[0].position_embedding_type = "relative_key" + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_create_position_ids_respects_padding_index(self): + """Ensure that the default position ids only assign a sequential . This is a regression + test for https://github.com/huggingface/transformers/issues/1761 + + The position ids should be masked with the embedding object's padding index. Therefore, the + first available non-padding position index is XLMRobertaXLEmbeddings.padding_idx + 1 + """ + config = self.model_tester.prepare_config_and_inputs()[0] + model = XLMRobertaXLEmbeddings(config=config) + + input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]]) + expected_positions = torch.as_tensor( + [[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]] + ) + + position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx) + self.assertEqual(position_ids.shape, expected_positions.shape) + self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) + + def test_create_position_ids_from_inputs_embeds(self): + """Ensure that the default position ids only assign a sequential . This is a regression + test for https://github.com/huggingface/transformers/issues/1761 + + The position ids should be masked with the embedding object's padding index. Therefore, the + first available non-padding position index is XLMRobertaXLEmbeddings.padding_idx + 1 + """ + config = self.model_tester.prepare_config_and_inputs()[0] + embeddings = XLMRobertaXLEmbeddings(config=config) + + inputs_embeds = torch.empty(2, 4, 30) + expected_single_positions = [ + 0 + embeddings.padding_idx + 1, + 1 + embeddings.padding_idx + 1, + 2 + embeddings.padding_idx + 1, + 3 + embeddings.padding_idx + 1, + ] + expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions]) + position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds) + self.assertEqual(position_ids.shape, expected_positions.shape) + self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) + + +@require_torch +class XLMRobertaModelXLIntegrationTest(unittest.TestCase): + @slow + def test_xlm_roberta_xl(self): + model = XLMRobertaXLModel.from_pretrained("facebook/xlm-roberta-xl").to(torch_device) + input_ids = torch.tensor( + [[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]], device=torch_device + ) + # The dog is cute and lives in the garden house + + expected_output_shape = torch.Size((1, 12, 2560)) # batch_size, sequence_length, embedding_vector_dim + expected_output_values_last_dim = torch.tensor( + [[0.0110, 0.0605, 0.0354, 0.0689, 0.0066, 0.0691, 0.0302, 0.0412, 0.0860, 0.0036, 0.0405, 0.0170]], + device=torch_device, + ) + + output = model(input_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) + + @unittest.skip(reason="Model is too large to be tested on the CI") + def test_xlm_roberta_xxl(self): + model = XLMRobertaXLModel.from_pretrained("facebook/xlm-roberta-xxl").to(torch_device) + input_ids = torch.tensor( + [[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]], device=torch_device + ) + # The dog is cute and lives in the garden house + + expected_output_shape = torch.Size((1, 12, 4096)) # batch_size, sequence_length, embedding_vector_dim + expected_output_values_last_dim = torch.tensor( + [[0.0046, 0.0146, 0.0227, 0.0126, 0.0219, 0.0175, -0.0101, 0.0006, 0.0124, 0.0209, -0.0063, 0.0096]], + device=torch_device, + ) + + output = model(input_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_modeling_tf_xlnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_modeling_tf_xlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..03eba74f4065df9021603fcc9cba02e13d4939e1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_modeling_tf_xlnet.py @@ -0,0 +1,535 @@ +# coding=utf-8 +# 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. + + +from __future__ import annotations + +import inspect +import random +import unittest + +from transformers import XLNetConfig, is_tf_available +from transformers.testing_utils import require_tf, slow + +from ...test_configuration_common import ConfigTester +from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_tf_available(): + import tensorflow as tf + + from transformers.models.xlnet.modeling_tf_xlnet import ( + TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, + TFXLNetForMultipleChoice, + TFXLNetForQuestionAnsweringSimple, + TFXLNetForSequenceClassification, + TFXLNetForTokenClassification, + TFXLNetLMHeadModel, + TFXLNetModel, + ) + + +class TFXLNetModelTester: + def __init__( + self, + parent, + ): + self.parent = parent + self.batch_size = 13 + self.seq_length = 7 + self.mem_len = 10 + # self.key_len = seq_length + mem_len + self.clamp_len = -1 + self.reuse_len = 15 + self.is_training = True + self.use_labels = True + self.vocab_size = 99 + self.cutoffs = [10, 50, 80] + self.hidden_size = 32 + self.num_attention_heads = 4 + self.d_inner = 128 + self.num_hidden_layers = 2 + self.type_sequence_label_size = 2 + self.untie_r = True + self.bi_data = False + self.same_length = False + self.initializer_range = 0.05 + self.seed = 1 + self.type_vocab_size = 2 + self.bos_token_id = 1 + self.eos_token_id = 2 + self.pad_token_id = 5 + self.num_choices = 4 + + def prepare_config_and_inputs(self): + input_ids_1 = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + input_ids_2 = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + segment_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + input_mask = random_attention_mask([self.batch_size, self.seq_length], dtype=tf.float32) + + input_ids_q = ids_tensor([self.batch_size, self.seq_length + 1], self.vocab_size) + perm_mask = tf.zeros((self.batch_size, self.seq_length + 1, self.seq_length), dtype=tf.float32) + perm_mask_last = tf.ones((self.batch_size, self.seq_length + 1, 1), dtype=tf.float32) + perm_mask = tf.concat([perm_mask, perm_mask_last], axis=-1) + # perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token + target_mapping = tf.zeros((self.batch_size, 1, self.seq_length), dtype=tf.float32) + target_mapping_last = tf.ones((self.batch_size, 1, 1), dtype=tf.float32) + target_mapping = tf.concat([target_mapping, target_mapping_last], axis=-1) + # target_mapping[:, 0, -1] = 1.0 # predict last token + + sequence_labels = None + lm_labels = None + is_impossible_labels = None + if self.use_labels: + lm_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + is_impossible_labels = ids_tensor([self.batch_size], 2, dtype=tf.float32) + + config = XLNetConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + n_head=self.num_attention_heads, + d_inner=self.d_inner, + n_layer=self.num_hidden_layers, + untie_r=self.untie_r, + mem_len=self.mem_len, + clamp_len=self.clamp_len, + same_length=self.same_length, + reuse_len=self.reuse_len, + bi_data=self.bi_data, + initializer_range=self.initializer_range, + num_labels=self.type_sequence_label_size, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + eos_token_id=self.eos_token_id, + ) + + return ( + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + ) + + def set_seed(self): + random.seed(self.seed) + tf.random.set_seed(self.seed) + + def create_and_check_xlnet_base_model( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + ): + model = TFXLNetModel(config) + + inputs = {"input_ids": input_ids_1, "input_mask": input_mask, "token_type_ids": segment_ids} + result = model(inputs) + + inputs = [input_ids_1, input_mask] + result = model(inputs) + + config.use_mems_eval = False + model = TFXLNetModel(config) + no_mems_outputs = model(inputs) + self.parent.assertEqual(len(no_mems_outputs), 1) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_xlnet_lm_head( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + ): + model = TFXLNetLMHeadModel(config) + + inputs_1 = {"input_ids": input_ids_1, "token_type_ids": segment_ids} + all_logits_1, mems_1 = model(inputs_1).to_tuple() + + inputs_2 = {"input_ids": input_ids_2, "mems": mems_1, "token_type_ids": segment_ids} + all_logits_2, mems_2 = model(inputs_2).to_tuple() + + inputs_3 = {"input_ids": input_ids_q, "perm_mask": perm_mask, "target_mapping": target_mapping} + logits, _ = model(inputs_3).to_tuple() + + self.parent.assertEqual(all_logits_1.shape, (self.batch_size, self.seq_length, self.vocab_size)) + self.parent.assertListEqual( + [mem.shape for mem in mems_1], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + self.parent.assertEqual(all_logits_2.shape, (self.batch_size, self.seq_length, self.vocab_size)) + self.parent.assertListEqual( + [mem.shape for mem in mems_2], + [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_xlnet_qa( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + ): + model = TFXLNetForQuestionAnsweringSimple(config) + + inputs = {"input_ids": input_ids_1, "attention_mask": input_mask, "token_type_ids": segment_ids} + result = model(inputs) + + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_xlnet_sequence_classif( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + ): + model = TFXLNetForSequenceClassification(config) + + result = model(input_ids_1) + + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_xlnet_for_token_classification( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + ): + config.num_labels = input_ids_1.shape[1] + model = TFXLNetForTokenClassification(config) + inputs = { + "input_ids": input_ids_1, + "attention_mask": input_mask, + # 'token_type_ids': token_type_ids + } + result = model(inputs) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, config.num_labels)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_xlnet_for_multiple_choice( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + ): + config.num_choices = self.num_choices + model = TFXLNetForMultipleChoice(config=config) + multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids_1, 1), (1, self.num_choices, 1)) + multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1)) + multiple_choice_token_type_ids = tf.tile(tf.expand_dims(segment_ids, 1), (1, self.num_choices, 1)) + inputs = { + "input_ids": multiple_choice_inputs_ids, + "attention_mask": multiple_choice_input_mask, + "token_type_ids": multiple_choice_token_type_ids, + } + result = model(inputs) + + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size * self.num_choices, self.hidden_size)] * self.num_hidden_layers, + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids_1} + return config, inputs_dict + + +@require_tf +class TFXLNetModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + TFXLNetModel, + TFXLNetLMHeadModel, + TFXLNetForSequenceClassification, + TFXLNetForTokenClassification, + TFXLNetForQuestionAnsweringSimple, + TFXLNetForMultipleChoice, + ) + if is_tf_available() + else () + ) + all_generative_model_classes = ( + (TFXLNetLMHeadModel,) if is_tf_available() else () + ) # TODO (PVP): Check other models whether language generation is also applicable + pipeline_model_mapping = ( + { + "feature-extraction": TFXLNetModel, + "question-answering": TFXLNetForQuestionAnsweringSimple, + "text-classification": TFXLNetForSequenceClassification, + "text-generation": TFXLNetLMHeadModel, + "token-classification": TFXLNetForTokenClassification, + "zero-shot": TFXLNetForSequenceClassification, + } + if is_tf_available() + else {} + ) + test_head_masking = False + test_onnx = False + + # Note that `TFXLNetModelTest` is not a subclass of `GenerationTesterMixin`, so no contrastive generation tests + # from there is run against `TFXLNetModel`. + @unittest.skip("XLNet has special cache mechanism and is currently not working with contrastive generation") + def test_xla_generate_contrastive(self): + super().test_xla_generate_contrastive() + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + # Exception encountered when calling layer '...' + return True + + def setUp(self): + self.model_tester = TFXLNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=XLNetConfig, d_inner=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_xlnet_base_model(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_base_model(*config_and_inputs) + + def test_xlnet_lm_head(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_lm_head(*config_and_inputs) + + def test_xlnet_sequence_classif(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_sequence_classif(*config_and_inputs) + + def test_xlnet_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_for_token_classification(*config_and_inputs) + + def test_xlnet_qa(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_qa(*config_and_inputs) + + def test_xlnet_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_for_multiple_choice(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = TFXLNetModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + @unittest.skip("Some of the XLNet models misbehave with flexible input shapes.") + def test_compile_tf_model(self): + pass + + # overwrite since `TFXLNetLMHeadModel` doesn't cut logits/labels + def test_loss_computation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model = model_class(config) + if getattr(model, "hf_compute_loss", None): + # The number of elements in the loss should be the same as the number of elements in the label + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + added_label = prepared_for_class[ + sorted(prepared_for_class.keys() - inputs_dict.keys(), reverse=True)[0] + ] + expected_loss_size = added_label.shape.as_list()[:1] + + # `TFXLNetLMHeadModel` doesn't cut logits/labels + # if model.__class__ in get_values(TF_MODEL_FOR_CAUSAL_LM_MAPPING): + # # if loss is causal lm loss, labels are shift, so that one label per batch + # # is cut + # loss_size = loss_size - self.model_tester.batch_size + + # Test that model correctly compute the loss with kwargs + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + input_name = "input_ids" if "input_ids" in prepared_for_class else "pixel_values" + input_ids = prepared_for_class.pop(input_name) + + loss = model(input_ids, **prepared_for_class)[0] + self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]) + + # Test that model correctly compute the loss with a dict + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + loss = model(prepared_for_class)[0] + self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]) + + # Test that model correctly compute the loss with a tuple + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + + # Get keys that were added with the _prepare_for_class function + label_keys = prepared_for_class.keys() - inputs_dict.keys() + signature = inspect.signature(model.call).parameters + signature_names = list(signature.keys()) + + # Create a dictionary holding the location of the tensors in the tuple + tuple_index_mapping = {0: input_name} + for label_key in label_keys: + label_key_index = signature_names.index(label_key) + tuple_index_mapping[label_key_index] = label_key + sorted_tuple_index_mapping = sorted(tuple_index_mapping.items()) + # Initialize a list with their default values, update the values and convert to a tuple + list_input = [] + + for name in signature_names: + if name != "kwargs": + list_input.append(signature[name].default) + + for index, value in sorted_tuple_index_mapping: + list_input[index] = prepared_for_class[value] + + tuple_input = tuple(list_input) + + # Send to model + loss = model(tuple_input[:-1])[0] + + self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]) + + +@require_tf +class TFXLNetModelLanguageGenerationTest(unittest.TestCase): + @slow + def test_lm_generate_xlnet_base_cased(self): + model = TFXLNetLMHeadModel.from_pretrained("xlnet-base-cased") + # fmt: off + input_ids = tf.convert_to_tensor( + [ + [ + 67, 2840, 19, 18, 1484, 20, 965, 29077, 8719, 1273, 21, 45, 273, 17, 10, 15048, 28, 27511, 21, 4185, 11, 41, 2444, 9, 32, 1025, 20, 8719, 26, 23, 673, 966, 19, 29077, 20643, 27511, 20822, 20643, 19, 17, 6616, 17511, 18, 8978, 20, 18, 777, 9, 19233, 1527, 17669, 19, 24, 673, 17, 28756, 150, 12943, 4354, 153, 27, 442, 37, 45, 668, 21, 24, 256, 20, 416, 22, 2771, 4901, 9, 12943, 4354, 153, 51, 24, 3004, 21, 28142, 23, 65, 20, 18, 416, 34, 24, 2958, 22947, 9, 1177, 45, 668, 3097, 13768, 23, 103, 28, 441, 148, 48, 20522, 19, 12943, 4354, 153, 12860, 34, 18, 326, 27, 17492, 684, 21, 6709, 9, 8585, 123, 266, 19, 12943, 4354, 153, 6872, 24, 3004, 20, 18, 9225, 2198, 19, 12717, 103, 22, 401, 24, 6348, 9, 12943, 4354, 153, 1068, 2768, 2286, 19, 33, 104, 19, 176, 24, 9313, 19, 20086, 28, 45, 10292, 9, 4, 3, + ] + ], + dtype=tf.int32, + ) + # fmt: on + + # In 1991, the remains of Russian Tsar Nicholas II and his family + # (except for Alexei and Maria) are discovered. + # The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the + # remainder of the story. 1883 Western Siberia, + # a young Grigori Rasputin is asked by his father and a group of men to perform magic. + # Rasputin has a vision and denounces one of the men as a horse thief. Although his + # father initially slaps him for making such an accusation, Rasputin watches as the + # man is chased outside and beaten. Twenty years later, Rasputin sees a vision of + # the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, + # with people, even a bishop, begging for his blessing. """ + + # fmt: off + expected_output_ids = [ + 67, 2840, 19, 18, 1484, 20, 965, 29077, 8719, 1273, 21, 45, 273, 17, 10, 15048, 28, 27511, 21, 4185, 11, 41, 2444, 9, 32, 1025, 20, 8719, 26, 23, 673, 966, 19, 29077, 20643, 27511, 20822, 20643, 19, 17, 6616, 17511, 18, 8978, 20, 18, 777, 9, 19233, 1527, 17669, 19, 24, 673, 17, 28756, 150, 12943, 4354, 153, 27, 442, 37, 45, 668, 21, 24, 256, 20, 416, 22, 2771, 4901, 9, 12943, 4354, 153, 51, 24, 3004, 21, 28142, 23, 65, 20, 18, 416, 34, 24, 2958, 22947, 9, 1177, 45, 668, 3097, 13768, 23, 103, 28, 441, 148, 48, 20522, 19, 12943, 4354, 153, 12860, 34, 18, 326, 27, 17492, 684, 21, 6709, 9, 8585, 123, 266, 19, 12943, 4354, 153, 6872, 24, 3004, 20, 18, 9225, 2198, 19, 12717, 103, 22, 401, 24, 6348, 9, 12943, 4354, 153, 1068, 2768, 2286, 19, 33, 104, 19, 176, 24, 9313, 19, 20086, 28, 45, 10292, 9, 4, 3, 19, 12943, 4354, 153, 27, 442, 22, 2771, 4901, 9, 69, 27, 442, 22, 2771, 24, 11335, 20, 18, 9225, 2198, 9, 69, 27, 442, 22, 2771, 24, 11335, 20, 18, 9225, 2198, 9, 69, 27, 442, 22, 2771, + ] + # fmt: on + # In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) + # are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, + # narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin + # is asked by his father and a group of men to perform magic. Rasputin has a vision and + # denounces one of the men as a horse thief. Although his father initially slaps + # him for making such an accusation, Rasputin watches as the man is chased outside and beaten. + # Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. + # Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. + # , Rasputin is asked to perform magic. He is asked to perform a ritual of the Virgin Mary. + # He is asked to perform a ritual of the Virgin Mary. He is asked to perform + + output_ids = model.generate(input_ids, max_length=200, do_sample=False) + + self.assertListEqual(output_ids[0].numpy().tolist(), expected_output_ids) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_modeling_xlnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_modeling_xlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..2b0c95cd6d13d09f6c741398969f46a4a56cf9a1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_modeling_xlnet.py @@ -0,0 +1,738 @@ +# coding=utf-8 +# 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 random +import unittest + +from transformers import XLNetConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + XLNetForMultipleChoice, + XLNetForQuestionAnswering, + XLNetForQuestionAnsweringSimple, + XLNetForSequenceClassification, + XLNetForTokenClassification, + XLNetLMHeadModel, + XLNetModel, + ) + from transformers.models.xlnet.modeling_xlnet import XLNET_PRETRAINED_MODEL_ARCHIVE_LIST + + +class XLNetModelTester: + def __init__( + self, + parent, + batch_size=14, + seq_length=7, + mem_len=10, + clamp_len=-1, + reuse_len=15, + is_training=True, + use_labels=True, + vocab_size=99, + cutoffs=[10, 50, 80], + hidden_size=32, + num_attention_heads=4, + d_inner=128, + num_hidden_layers=2, + type_sequence_label_size=2, + untie_r=True, + bi_data=False, + same_length=False, + initializer_range=0.05, + seed=1, + type_vocab_size=2, + bos_token_id=1, + eos_token_id=2, + pad_token_id=5, + num_choices=4, + ): + self.parent = parent + self.batch_size = 14 + self.seq_length = 7 + self.mem_len = 10 + # self.key_len = seq_length + mem_len + self.clamp_len = -1 + self.reuse_len = 15 + self.is_training = True + self.use_labels = True + self.vocab_size = 99 + self.cutoffs = [10, 50, 80] + self.hidden_size = 32 + self.num_attention_heads = 4 + self.d_inner = 128 + self.num_hidden_layers = 5 + self.type_sequence_label_size = 2 + self.untie_r = True + self.bi_data = False + self.same_length = False + self.initializer_range = 0.05 + self.seed = 1 + self.type_vocab_size = 2 + self.bos_token_id = 1 + self.eos_token_id = 2 + self.pad_token_id = 5 + self.num_choices = 4 + + def prepare_config_and_inputs(self): + input_ids_1 = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + input_ids_2 = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + segment_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + input_ids_q = ids_tensor([self.batch_size, self.seq_length + 1], self.vocab_size) + perm_mask = torch.zeros( + self.batch_size, + self.seq_length + 1, + self.seq_length + 1, + dtype=torch.float, + device=torch_device, + ) + perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token + target_mapping = torch.zeros( + self.batch_size, + 1, + self.seq_length + 1, + dtype=torch.float, + device=torch_device, + ) + target_mapping[:, 0, -1] = 1.0 # predict last token + + sequence_labels = None + lm_labels = None + is_impossible_labels = None + token_labels = None + if self.use_labels: + lm_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + is_impossible_labels = ids_tensor([self.batch_size], 2).float() + token_labels = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + config = self.get_config() + + return ( + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ) + + def get_config(self): + return XLNetConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + n_head=self.num_attention_heads, + d_inner=self.d_inner, + n_layer=self.num_hidden_layers, + untie_r=self.untie_r, + mem_len=self.mem_len, + clamp_len=self.clamp_len, + same_length=self.same_length, + reuse_len=self.reuse_len, + bi_data=self.bi_data, + initializer_range=self.initializer_range, + num_labels=self.type_sequence_label_size, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + eos_token_id=self.eos_token_id, + ) + + def set_seed(self): + random.seed(self.seed) + torch.manual_seed(self.seed) + + def create_and_check_xlnet_base_model( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ): + model = XLNetModel(config) + model.to(torch_device) + model.eval() + + result = model(input_ids_1, input_mask=input_mask) + result = model(input_ids_1, attention_mask=input_mask) + result = model(input_ids_1, token_type_ids=segment_ids) + result = model(input_ids_1) + + config.mem_len = 0 + model = XLNetModel(config) + model.to(torch_device) + model.eval() + base_model_output = model(input_ids_1) + self.parent.assertEqual(len(base_model_output), 2) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_use_mems_train( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ): + model = XLNetForSequenceClassification(config) + model.to(torch_device) + model.train() + + train_size = input_ids_1.shape[0] + + batch_size = 4 + for i in range(train_size // batch_size + 1): + input_ids = input_ids_1[i : (i + 1) * batch_size] + labels = sequence_labels[i : (i + 1) * batch_size] + outputs = model(input_ids=input_ids, labels=labels, return_dict=True) + self.parent.assertIsNone(outputs.mems) + self.parent.assertIsNotNone(outputs.loss) + + def create_and_check_xlnet_model_use_mems( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ): + model = XLNetModel(config=config) + model.to(torch_device) + model.eval() + + # first forward pass + causal_mask = torch.ones( + input_ids_1.shape[0], + input_ids_1.shape[1], + input_ids_1.shape[1], + dtype=torch.float, + device=torch_device, + ) + causal_mask = torch.triu(causal_mask, diagonal=0) + outputs_cache = model(input_ids_1, use_mems=True, perm_mask=causal_mask) + outputs_no_cache = model(input_ids_1, use_mems=False, perm_mask=causal_mask) + outputs_conf = model(input_ids_1) + + self.parent.assertTrue(len(outputs_cache) == len(outputs_conf)) + self.parent.assertTrue(len(outputs_cache) == len(outputs_no_cache) + 1) + + output, mems = outputs_cache.to_tuple() + + # create hypothetical next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) + + # append to next input_ids and token_type_ids + next_input_ids = torch.cat([input_ids_1, next_tokens], dim=-1) + + # causal mask + causal_mask = torch.ones( + input_ids_1.shape[0], + input_ids_1.shape[1] + 1, + input_ids_1.shape[1] + 1, + dtype=torch.float, + device=torch_device, + ) + causal_mask = torch.triu(causal_mask, diagonal=0) + single_mask = torch.ones(input_ids_1.shape[0], 1, 1, dtype=torch.float, device=torch_device) + + # second forward pass + output_from_no_past = model(next_input_ids, perm_mask=causal_mask)["last_hidden_state"] + output_from_past = model(next_tokens, mems=mems, perm_mask=single_mask)["last_hidden_state"] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def create_and_check_xlnet_base_model_with_att_output( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ): + model = XLNetModel(config) + model.to(torch_device) + model.eval() + + attentions = model(input_ids_1, target_mapping=target_mapping, output_attentions=True)["attentions"] + + self.parent.assertEqual(len(attentions), config.n_layer) + self.parent.assertIsInstance(attentions[0], tuple) + self.parent.assertEqual(len(attentions[0]), 2) + self.parent.assertTrue(attentions[0][0].shape, attentions[0][0].shape) + + def create_and_check_xlnet_lm_head( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ): + model = XLNetLMHeadModel(config) + model.to(torch_device) + model.eval() + + result1 = model(input_ids_1, token_type_ids=segment_ids, labels=lm_labels) + + result2 = model(input_ids_2, token_type_ids=segment_ids, labels=lm_labels, mems=result1.mems) + + _ = model(input_ids_q, perm_mask=perm_mask, target_mapping=target_mapping) + + self.parent.assertEqual(result1.loss.shape, ()) + self.parent.assertEqual(result1.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + self.parent.assertListEqual( + [mem.shape for mem in result1.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + self.parent.assertEqual(result2.loss.shape, ()) + self.parent.assertEqual(result2.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + self.parent.assertListEqual( + [mem.shape for mem in result2.mems], + [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_xlnet_qa( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ): + model = XLNetForQuestionAnswering(config) + model.to(torch_device) + model.eval() + + result = model(input_ids_1) + + result_with_labels = model( + input_ids_1, + start_positions=sequence_labels, + end_positions=sequence_labels, + cls_index=sequence_labels, + is_impossible=is_impossible_labels, + p_mask=input_mask, + ) + + result_with_labels = model( + input_ids_1, + start_positions=sequence_labels, + end_positions=sequence_labels, + cls_index=sequence_labels, + is_impossible=is_impossible_labels, + ) + + total_loss, mems = result_with_labels.to_tuple() + + result_with_labels = model( + input_ids_1, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + + total_loss, mems = result_with_labels.to_tuple() + + self.parent.assertEqual(result_with_labels.loss.shape, ()) + self.parent.assertEqual(result.start_top_log_probs.shape, (self.batch_size, model.config.start_n_top)) + self.parent.assertEqual(result.start_top_index.shape, (self.batch_size, model.config.start_n_top)) + self.parent.assertEqual( + result.end_top_log_probs.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top) + ) + self.parent.assertEqual( + result.end_top_index.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top) + ) + self.parent.assertEqual(result.cls_logits.shape, (self.batch_size,)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_xlnet_token_classif( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ): + model = XLNetForTokenClassification(config) + model.to(torch_device) + model.eval() + + result = model(input_ids_1) + result = model(input_ids_1, labels=token_labels) + + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.type_sequence_label_size)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def create_and_check_xlnet_sequence_classif( + self, + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ): + model = XLNetForSequenceClassification(config) + model.to(torch_device) + model.eval() + + result = model(input_ids_1) + result = model(input_ids_1, labels=sequence_labels) + + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) + self.parent.assertListEqual( + [mem.shape for mem in result.mems], + [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers, + ) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids_1, + input_ids_2, + input_ids_q, + perm_mask, + input_mask, + target_mapping, + segment_ids, + lm_labels, + sequence_labels, + is_impossible_labels, + token_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids_1} + return config, inputs_dict + + +@require_torch +class XLNetModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + XLNetModel, + XLNetLMHeadModel, + XLNetForTokenClassification, + XLNetForSequenceClassification, + XLNetForQuestionAnswering, + XLNetForQuestionAnsweringSimple, + XLNetForMultipleChoice, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = ( + (XLNetLMHeadModel,) if is_torch_available() else () + ) # TODO (PVP): Check other models whether language generation is also applicable + pipeline_model_mapping = ( + { + "feature-extraction": XLNetModel, + "question-answering": XLNetForQuestionAnsweringSimple, + "text-classification": XLNetForSequenceClassification, + "text-generation": XLNetLMHeadModel, + "token-classification": XLNetForTokenClassification, + "zero-shot": XLNetForSequenceClassification, + } + if is_torch_available() + else {} + ) + fx_compatible = False + test_pruning = False + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): + return True + + return False + + # XLNet has 2 QA models -> need to manually set the correct labels for one of them here + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) + + if return_labels: + if model_class.__name__ == "XLNetForQuestionAnswering": + inputs_dict["start_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + inputs_dict["end_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + + return inputs_dict + + def setUp(self): + self.model_tester = XLNetModelTester(self) + self.config_tester = ConfigTester(self, config_class=XLNetConfig, d_inner=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_xlnet_base_model(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_base_model(*config_and_inputs) + + def test_xlnet_base_model_use_mems(self): + # checking that in auto-regressive mode, `use_mems` gives the same results + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_model_use_mems(*config_and_inputs) + + def test_seq_classification_use_mems_train(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_use_mems_train(*config_and_inputs) + + def test_xlnet_base_model_with_att_output(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_base_model_with_att_output(*config_and_inputs) + + def test_xlnet_lm_head(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_lm_head(*config_and_inputs) + + def test_xlnet_sequence_classif(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_sequence_classif(*config_and_inputs) + + def test_xlnet_token_classif(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_token_classif(*config_and_inputs) + + def test_xlnet_qa(self): + self.model_tester.set_seed() + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_xlnet_qa(*config_and_inputs) + + def test_retain_grad_hidden_states_attentions(self): + # xlnet cannot keep gradients in attentions or hidden states + return + + # overwrite from test_modeling_common + def _mock_init_weights(self, module): + if hasattr(module, "weight") and module.weight is not None: + module.weight.data.fill_(3) + if hasattr(module, "bias") and module.bias is not None: + module.bias.data.fill_(3) + + for param in ["q", "k", "v", "o", "r", "r_r_bias", "r_s_bias", "r_w_bias", "seg_embed", "mask_emb"]: + if hasattr(module, param) and getattr(module, param) is not None: + weight = getattr(module, param) + weight.data.fill_(3) + + def _check_hidden_states_for_generate( + self, batch_size, hidden_states, min_length, max_length, config, use_cache=False, num_beam_groups=1 + ): + self.assertIsInstance(hidden_states, tuple) + self.assertListEqual( + [isinstance(iter_hidden_states, tuple) for iter_hidden_states in hidden_states], + [True] * len(hidden_states), + ) + self.assertEqual(len(hidden_states), (max_length - min_length) * num_beam_groups) + + for idx, iter_hidden_states in enumerate(hidden_states): + # check hidden size + for i, layer_hidden_states in enumerate(iter_hidden_states): + # every 2nd tensor is from extra stream + if i % 2 != 0: + seq_len = 1 + else: + # for first item dummy PAD token is appended so need one more + seq_len = (min_length + 1) if idx == 0 else min_length + + expected_shape = (batch_size * num_beam_groups, seq_len, config.hidden_size) + self.assertEqual(layer_hidden_states.shape, expected_shape) + + def _check_attentions_for_generate( + self, batch_size, attentions, min_length, max_length, config, use_cache=False, num_beam_groups=1 + ): + self.assertIsInstance(attentions, tuple) + self.assertListEqual( + [isinstance(iter_attentions, tuple) for iter_attentions in attentions], [True] * len(attentions) + ) + self.assertEqual(len(attentions), (max_length - min_length) * num_beam_groups) + + for idx, attentions_item in enumerate(attentions): + for iter_attentions in attentions_item: + tgt_len = min_length + + # for first item dummy PAD token is appended so need one more + if idx == 0: + tgt_len += 1 + + src_len = min_length + idx + 1 + + expected_shape = ( + batch_size * num_beam_groups, + config.num_attention_heads, + tgt_len, + src_len, + ) + # check attn size + self.assertListEqual( + [layer_attention.shape for layer_attention in iter_attentions], + [expected_shape] * len(iter_attentions), + ) + + @slow + def test_model_from_pretrained(self): + for model_name in XLNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = XLNetModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +@require_torch +class XLNetModelLanguageGenerationTest(unittest.TestCase): + @slow + def test_lm_generate_xlnet_base_cased(self): + model = XLNetLMHeadModel.from_pretrained("xlnet-base-cased") + model.to(torch_device) + # fmt: off + input_ids = torch.tensor( + [ + [ + 67, 2840, 19, 18, 1484, 20, 965, 29077, 8719, 1273, 21, 45, 273, 17, 10, 15048, 28, 27511, 21, 4185, 11, 41, 2444, 9, 32, 1025, 20, 8719, 26, 23, 673, 966, 19, 29077, 20643, 27511, 20822, 20643, 19, 17, 6616, 17511, 18, 8978, 20, 18, 777, 9, 19233, 1527, 17669, 19, 24, 673, 17, 28756, 150, 12943, 4354, 153, 27, 442, 37, 45, 668, 21, 24, 256, 20, 416, 22, 2771, 4901, 9, 12943, 4354, 153, 51, 24, 3004, 21, 28142, 23, 65, 20, 18, 416, 34, 24, 2958, 22947, 9, 1177, 45, 668, 3097, 13768, 23, 103, 28, 441, 148, 48, 20522, 19, 12943, 4354, 153, 12860, 34, 18, 326, 27, 17492, 684, 21, 6709, 9, 8585, 123, 266, 19, 12943, 4354, 153, 6872, 24, 3004, 20, 18, 9225, 2198, 19, 12717, 103, 22, 401, 24, 6348, 9, 12943, 4354, 153, 1068, 2768, 2286, 19, 33, 104, 19, 176, 24, 9313, 19, 20086, 28, 45, 10292, 9, 4, 3, + ] + ], + dtype=torch.long, + device=torch_device, + ) + # fmt: on + # In 1991, the remains of Russian Tsar Nicholas II and his family + # (except for Alexei and Maria) are discovered. + # The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the + # remainder of the story. 1883 Western Siberia, + # a young Grigori Rasputin is asked by his father and a group of men to perform magic. + # Rasputin has a vision and denounces one of the men as a horse thief. Although his + # father initially slaps him for making such an accusation, Rasputin watches as the + # man is chased outside and beaten. Twenty years later, Rasputin sees a vision of + # the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, + # with people, even a bishop, begging for his blessing. """ + + # fmt: off + expected_output_ids = [ + 67, 2840, 19, 18, 1484, 20, 965, 29077, 8719, 1273, 21, 45, 273, 17, 10, 15048, 28, 27511, 21, 4185, 11, 41, 2444, 9, 32, 1025, 20, 8719, 26, 23, 673, 966, 19, 29077, 20643, 27511, 20822, 20643, 19, 17, 6616, 17511, 18, 8978, 20, 18, 777, 9, 19233, 1527, 17669, 19, 24, 673, 17, 28756, 150, 12943, 4354, 153, 27, 442, 37, 45, 668, 21, 24, 256, 20, 416, 22, 2771, 4901, 9, 12943, 4354, 153, 51, 24, 3004, 21, 28142, 23, 65, 20, 18, 416, 34, 24, 2958, 22947, 9, 1177, 45, 668, 3097, 13768, 23, 103, 28, 441, 148, 48, 20522, 19, 12943, 4354, 153, 12860, 34, 18, 326, 27, 17492, 684, 21, 6709, 9, 8585, 123, 266, 19, 12943, 4354, 153, 6872, 24, 3004, 20, 18, 9225, 2198, 19, 12717, 103, 22, 401, 24, 6348, 9, 12943, 4354, 153, 1068, 2768, 2286, 19, 33, 104, 19, 176, 24, 9313, 19, 20086, 28, 45, 10292, 9, 4, 3, 19, 12943, 4354, 153, 27, 442, 22, 2771, 4901, 9, 69, 27, 442, 22, 2771, 24, 11335, 20, 18, 9225, 2198, 9, 69, 27, 442, 22, 2771, 24, 11335, 20, 18, 9225, 2198, 9, 69, 27, 442, 22, 2771, + ] + # fmt: on + # In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) + # are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, + # narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin + # is asked by his father and a group of men to perform magic. Rasputin has a vision and + # denounces one of the men as a horse thief. Although his father initially slaps + # him for making such an accusation, Rasputin watches as the man is chased outside and beaten. + # Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. + # Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. + # , Rasputin is asked to perform magic. He is asked to perform a ritual of the Virgin Mary. + # He is asked to perform a ritual of the Virgin Mary. He is asked to perform + + output_ids = model.generate(input_ids, max_length=200, do_sample=False) + self.assertListEqual(output_ids[0].tolist(), expected_output_ids) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_tokenization_xlnet.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_tokenization_xlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb28658aab4dae0387985a358c273b6aa19cea2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xlnet/test_tokenization_xlnet.py @@ -0,0 +1,208 @@ +# coding=utf-8 +# 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 unittest + +from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast +from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow + +from ...test_tokenization_common import TokenizerTesterMixin + + +SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") + + +@require_sentencepiece +@require_tokenizers +class XLNetTokenizationTest(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = XLNetTokenizer + rust_tokenizer_class = XLNetTokenizerFast + test_rust_tokenizer = True + test_sentencepiece = True + + def setUp(self): + super().setUp() + + # We have a SentencePiece fixture for testing + tokenizer = XLNetTokenizer(SAMPLE_VOCAB, keep_accents=True) + tokenizer.save_pretrained(self.tmpdirname) + + def test_convert_token_and_id(self): + """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" + token = "" + token_id = 1 + + self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) + self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) + + def test_get_vocab(self): + vocab_keys = list(self.get_tokenizer().get_vocab().keys()) + + self.assertEqual(vocab_keys[0], "") + self.assertEqual(vocab_keys[1], "") + self.assertEqual(vocab_keys[-1], "") + self.assertEqual(len(vocab_keys), 1_006) + + def test_vocab_size(self): + self.assertEqual(self.get_tokenizer().vocab_size, 1_000) + + def test_full_tokenizer(self): + tokenizer = XLNetTokenizer(SAMPLE_VOCAB, keep_accents=True) + + tokens = tokenizer.tokenize("This is a test") + self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) + + self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [285, 46, 10, 170, 382]) + + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "é", + ".", + ], + ) + ids = tokenizer.convert_tokens_to_ids(tokens) + self.assertListEqual(ids, [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]) + + back_tokens = tokenizer.convert_ids_to_tokens(ids) + self.assertListEqual( + back_tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "s", + "", + ".", + ], + ) + + def test_tokenizer_lower(self): + tokenizer = XLNetTokenizer(SAMPLE_VOCAB, do_lower_case=True) + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "", + "i", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "se", + ".", + ], + ) + self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["▁he", "ll", "o"]) + + def test_tokenizer_no_lower(self): + tokenizer = XLNetTokenizer(SAMPLE_VOCAB, do_lower_case=False) + tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") + self.assertListEqual( + tokens, + [ + SPIECE_UNDERLINE + "I", + SPIECE_UNDERLINE + "was", + SPIECE_UNDERLINE + "b", + "or", + "n", + SPIECE_UNDERLINE + "in", + SPIECE_UNDERLINE + "", + "9", + "2", + "0", + "0", + "0", + ",", + SPIECE_UNDERLINE + "and", + SPIECE_UNDERLINE + "this", + SPIECE_UNDERLINE + "is", + SPIECE_UNDERLINE + "f", + "al", + "se", + ".", + ], + ) + + @slow + def test_sequence_builders(self): + tokenizer = XLNetTokenizer.from_pretrained("xlnet-base-cased") + + text = tokenizer.encode("sequence builders", add_special_tokens=False) + text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False) + + encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) + encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) + + assert encoded_sentence == text + [4, 3] + assert encoded_pair == text + [4] + text_2 + [4, 3] + + @slow + def test_tokenizer_integration(self): + expected_encoding = {'input_ids': [[17, 21442, 270, 17, 10, 14645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 22018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 14431, 13, 5500, 11, 1176, 580, 13, 16819, 4797, 23, 17, 10, 17135, 658, 19, 457, 7932, 13, 184, 19, 3154, 17135, 6468, 19, 1404, 12269, 19, 4229, 5356, 16264, 46, 19, 17, 20545, 10395, 9, 9, 9, 11, 28, 6421, 9531, 20729, 17, 10, 353, 17022, 11, 21, 6421, 9531, 16949, 17, 10, 11509, 753, 11, 33, 95, 2421, 7385, 956, 14431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 24738, 19, 13203, 658, 218, 787, 21, 430, 18482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22178, 27, 1064, 22, 956, 13, 11101, 1429, 5854, 24313, 18953, 40, 422, 24366, 68, 1758, 37, 10483, 14257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 13894, 3380, 23, 95, 18, 17634, 2288, 9, 4, 3]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # fmt: skip + + self.tokenizer_integration_test_util( + expected_encoding=expected_encoding, + model_name="xlnet-base-cased", + revision="c841166438c31ec7ca9a106dee7bb312b73ae511", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xmod/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xmod/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xmod/test_modeling_xmod.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xmod/test_modeling_xmod.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1ce44e35d83675ad8c05b10a12f0445d3d9e6f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/xmod/test_modeling_xmod.py @@ -0,0 +1,674 @@ +# coding=utf-8 +# Copyright 2023 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 unittest + +from transformers import XLMRobertaTokenizer, is_torch_available +from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + XmodConfig, + XmodForCausalLM, + XmodForMaskedLM, + XmodForMultipleChoice, + XmodForQuestionAnswering, + XmodForSequenceClassification, + XmodForTokenClassification, + XmodModel, + ) + from transformers.models.xmod.modeling_xmod import XmodEmbeddings, create_position_ids_from_input_ids + + +class XmodModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def get_config(self): + return XmodConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + initializer_range=self.initializer_range, + default_language="en_XX", + ) + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = XmodModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = XmodModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) + + def create_and_check_for_causal_lm( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + model = XmodForCausalLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_decoder_model_past_large_inputs( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.is_decoder = True + config.add_cross_attention = True + model = XmodForCausalLM(config=config).to(torch_device).eval() + + # make sure that ids don't start with pad token + mask = input_ids.ne(config.pad_token_id).long() + input_ids = input_ids * mask + + # first forward pass + outputs = model( + input_ids, + attention_mask=input_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=True, + ) + past_key_values = outputs.past_key_values + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + + # make sure that ids don't start with pad token + mask = next_tokens.ne(config.pad_token_id).long() + next_tokens = next_tokens * mask + next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) + + output_from_no_past = model( + next_input_ids, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_hidden_states=True, + )["hidden_states"][0] + output_from_past = model( + next_tokens, + attention_mask=next_attention_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + output_hidden_states=True, + )["hidden_states"][0] + + # 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)) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = XmodForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = XmodForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = XmodForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = XmodForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class XmodModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + XmodForCausalLM, + XmodForMaskedLM, + XmodModel, + XmodForSequenceClassification, + XmodForTokenClassification, + XmodForMultipleChoice, + XmodForQuestionAnswering, + ) + if is_torch_available() + else () + ) + all_generative_model_classes = (XmodForCausalLM,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "feature-extraction": XmodModel, + "fill-mask": XmodForMaskedLM, + "question-answering": XmodForQuestionAnswering, + "text-classification": XmodForSequenceClassification, + "text-generation": XmodForCausalLM, + "token-classification": XmodForTokenClassification, + "zero-shot": XmodForSequenceClassification, + } + if is_torch_available() + else {} + ) + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): + return True + + return False + + def setUp(self): + self.model_tester = XmodModelTester(self) + self.config_tester = ConfigTester(self, config_class=XmodConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_as_decoder(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) + + def test_model_as_decoder_with_default_input_mask(self): + # This regression test was failing with PyTorch < 1.3 + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) = self.model_tester.prepare_config_and_inputs_for_decoder() + + input_mask = None + + self.model_tester.create_and_check_model_as_decoder( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def test_for_causal_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_for_causal_lm(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_decoder_model_past_with_large_inputs_relative_pos_emb(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() + config_and_inputs[0].position_embedding_type = "relative_key" + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_create_position_ids_respects_padding_index(self): + """Ensure that the default position ids only assign a sequential . This is a regression + test for https://github.com/huggingface/transformers/issues/1761 + + The position ids should be masked with the embedding object's padding index. Therefore, the + first available non-padding position index is XmodEmbeddings.padding_idx + 1 + """ + config = self.model_tester.prepare_config_and_inputs()[0] + model = XmodEmbeddings(config=config) + + input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]]) + expected_positions = torch.as_tensor( + [[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]] + ) + + position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx) + self.assertEqual(position_ids.shape, expected_positions.shape) + self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) + + def test_create_position_ids_from_inputs_embeds(self): + """Ensure that the default position ids only assign a sequential . This is a regression + test for https://github.com/huggingface/transformers/issues/1761 + + The position ids should be masked with the embedding object's padding index. Therefore, the + first available non-padding position index is XmodEmbeddings.padding_idx + 1 + """ + config = self.model_tester.prepare_config_and_inputs()[0] + embeddings = XmodEmbeddings(config=config) + + inputs_embeds = torch.empty(2, 4, 30) + expected_single_positions = [ + 0 + embeddings.padding_idx + 1, + 1 + embeddings.padding_idx + 1, + 2 + embeddings.padding_idx + 1, + 3 + embeddings.padding_idx + 1, + ] + expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions]) + position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds) + self.assertEqual(position_ids.shape, expected_positions.shape) + self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) + + def test_set_default_language(self): + config = self.model_tester.prepare_config_and_inputs()[0] + model = XmodForMaskedLM(config=config) + model.set_default_language("en_XX") + self.assertEqual(model.config.default_language, "en_XX") + with self.assertRaises(ValueError): + model.set_default_language("xx_XX") + + def test_freeze_embeddings_and_language_adapters(self): + config = self.model_tester.prepare_config_and_inputs()[0] + model = XmodForMaskedLM(config=config) + num_trainable_params_before = sum(p.numel() for p in model.parameters() if p.requires_grad) + model.freeze_embeddings_and_language_adapters() + num_trainable_params_after = sum(p.numel() for p in model.parameters() if p.requires_grad) + self.assertLess(num_trainable_params_after, num_trainable_params_before) + + +@require_sentencepiece +@require_tokenizers +@require_torch +class XmodModelIntegrationTest(unittest.TestCase): + @slow + def test_xmod_base(self): + model = XmodModel.from_pretrained("facebook/xmod-base") + + # language en_XX + model.set_default_language("en_XX") + input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) + # The dog is cute and lives in the garden house + expected_output_shape = torch.Size((1, 12, 768)) # batch_size, sequence_length, embedding_vector_dim + expected_output_values_last_dim = torch.tensor( + [[-0.2394, -0.0036, 0.1252, -0.0087, 0.1325, 0.0580, -0.2049, -0.1978, -0.1223, 0.0648, -0.2599, -0.3724]] + ) + output = model(input_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) + + # language de_DE + model.set_default_language("de_DE") + input_ids = torch.tensor([[0, 1310, 49083, 443, 269, 71, 5486, 165, 60429, 660, 23, 2315, 58761, 18391, 5, 2]]) + # Der Hund ist niedlich und wohnt in einem Gartenhaus. + expected_output_shape = torch.Size((1, 16, 768)) # batch_size, sequence_length, embedding_vector_dim + # fmt: off + expected_output_values_last_dim = torch.tensor( + [[0.0162, 0.0075, -0.1882, 0.2335, -0.0952, -0.3994, -0.0317, -0.1174, 0.0177, 0.4280, -0.0240, -0.2138, + 0.0785, -0.1045, -0.2811, -0.3220]] + ) + # fmt: on + output = model(input_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) + + @slow + def test_xmod_large_prenorm(self): + model = XmodModel.from_pretrained("facebook/xmod-large-prenorm") + + # language en_XX + model.set_default_language("en_XX") + input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) + # The dog is cute and lives in the garden house + expected_output_shape = torch.Size((1, 12, 1024)) # batch_size, sequence_length, embedding_vector_dim + # fmt: off + expected_output_values_last_dim = torch.tensor( + [[-0.0121, -0.0194, -0.0240, -0.0160, -0.0205, -0.0159, -0.0243, -0.0206, -0.0161, -0.0335, -0.0196, + -0.0141]] + ) + # fmt: on + output = model(input_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) + + # language de_DE + model.set_default_language("de_DE") + input_ids = torch.tensor([[0, 1310, 49083, 443, 269, 71, 5486, 165, 60429, 660, 23, 2315, 58761, 18391, 5, 2]]) + # Der Hund ist niedlich und wohnt in einem Gartenhaus. + expected_output_shape = torch.Size((1, 16, 1024)) # batch_size, sequence_length, embedding_vector_dim + # fmt: off + expected_output_values_last_dim = torch.tensor( + [[-0.0120, -0.0262, -0.0253, -0.0112, -0.0128, -0.0164, -0.0080, -0.0081, -0.0192, -0.0117, -0.0170, + -0.0120, -0.0210, -0.0173, -0.0078, -0.0122]] + ) + # fmt: on + output = model(input_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) + + @slow + def test_multilingual_batch(self): + model = XmodModel.from_pretrained("facebook/xmod-base") + # fmt: off + input_ids = torch.tensor([ + [0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2], + [0, 1310, 49083, 443, 269, 71, 5486, 165, 60429, 660, 23, 2], + [0, 1310, 49083, 443, 269, 71, 5486, 165, 60429, 660, 23, 2], + [0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2], + ]) + # fmt: on + lang_ids = torch.LongTensor([0, 8, 8, 0]) + expected_output_shape = torch.Size((4, 12, 768)) # batch_size, sequence_length, embedding_vector_dim + # fmt: off + expected_output_values_last_dim = torch.tensor([ + [-0.2394, -0.0036, 0.1252, -0.0087, 0.1325, 0.0580, -0.2049, -0.1978, -0.1223, 0.0648, -0.2599, -0.3724], + [-0.2668, -0.0235, -0.1739, 0.2266, -0.0901, -0.3482, 0.0105, -0.1915, 0.0397, 0.3822, 0.1836, -0.3407], + [-0.2668, -0.0235, -0.1739, 0.2266, -0.0901, -0.3482, 0.0105, -0.1915, 0.0397, 0.3822, 0.1836, -0.3407], + [-0.2394, -0.0036, 0.1252, -0.0087, 0.1325, 0.0580, -0.2049, -0.1978, -0.1223, 0.0648, -0.2599, -0.3724], + ]) + # fmt: on + output = model(input_ids, lang_ids=lang_ids)["last_hidden_state"].detach() + self.assertEqual(output.shape, expected_output_shape) + # compare the actual values for a slice of last dim + self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) + + @slow + def test_end_to_end_mask_fill(self): + tokenizer = XLMRobertaTokenizer.from_pretrained("xlm-roberta-base") + model = XmodForMaskedLM.from_pretrained("facebook/xmod-base", default_language="en_XX") + model.to(torch_device) + + sentences = [ + "Hello, my dog is a little .", + "Hi !", + ] + + inputs = tokenizer(sentences, return_tensors="pt", padding=True) + input_ids = inputs["input_ids"].to(torch_device) + + outputs = model( + input_ids=input_ids, + attention_mask=inputs["attention_mask"].to(torch_device), + ) + probs = outputs.logits.softmax(dim=-1) + _, predictions = probs.topk(1) + predictions = predictions.squeeze(-1) + + inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device) + output_non_padded = model(input_ids=inputs_non_padded) + probs_non_padded = output_non_padded.logits.softmax(dim=-1) + _, predictions_non_padded = probs_non_padded.topk(1) + predictions_non_padded = predictions_non_padded.squeeze(-1) + + inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device) + output_padded = model(input_ids=inputs_padded) + probs_padded = output_padded.logits.softmax(dim=-1) + _, predictions_padded = probs_padded.topk(1) + predictions_padded = predictions_padded.squeeze(-1) + + batch_out_sentence = tokenizer.batch_decode(predictions, skip_special_tokens=True) + non_padded_sentence = tokenizer.decode(predictions_non_padded[0], skip_special_tokens=True) + padded_sentence = tokenizer.decode(predictions_padded[0], skip_special_tokens=True) + + expected_output_sentence = [ + "Hello, my dog is a little girl.", + "Hi everyone!", + ] + self.assertListEqual(expected_output_sentence, batch_out_sentence) + self.assertListEqual(batch_out_sentence, [non_padded_sentence, padded_sentence]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yolos/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yolos/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yolos/test_image_processing_yolos.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yolos/test_image_processing_yolos.py new file mode 100644 index 0000000000000000000000000000000000000000..1039e4c91bc6e1cbdd937a7a2ff4a53116a716cc --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yolos/test_image_processing_yolos.py @@ -0,0 +1,267 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 pathlib +import unittest + +from transformers.testing_utils import require_torch, require_vision, slow +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import AnnotationFormatTestMixin, ImageProcessingTestMixin, prepare_image_inputs + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + from transformers import YolosImageProcessor + + +class YolosImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + min_resolution=30, + max_resolution=400, + do_resize=True, + size=None, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + do_rescale=True, + rescale_factor=1 / 255, + do_pad=True, + ): + # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p + size = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + self.do_rescale = do_rescale + self.rescale_factor = rescale_factor + self.do_pad = do_pad + + def prepare_image_processor_dict(self): + return { + "do_resize": self.do_resize, + "size": self.size, + "do_normalize": self.do_normalize, + "image_mean": self.image_mean, + "image_std": self.image_std, + "do_rescale": self.do_rescale, + "rescale_factor": self.rescale_factor, + "do_pad": self.do_pad, + } + + def get_expected_values(self, image_inputs, batched=False): + """ + This function computes the expected height and width when providing images to YolosImageProcessor, + assuming do_resize is set to True with a scalar size. + """ + if not batched: + image = image_inputs[0] + if isinstance(image, Image.Image): + w, h = image.size + else: + h, w = image.shape[1], image.shape[2] + if w < h: + expected_height = int(self.size["shortest_edge"] * h / w) + expected_width = self.size["shortest_edge"] + elif w > h: + expected_height = self.size["shortest_edge"] + expected_width = int(self.size["shortest_edge"] * w / h) + else: + expected_height = self.size["shortest_edge"] + expected_width = self.size["shortest_edge"] + + else: + expected_values = [] + for image in image_inputs: + expected_height, expected_width = self.get_expected_values([image]) + expected_values.append((expected_height, expected_width)) + expected_height = max(expected_values, key=lambda item: item[0])[0] + expected_width = max(expected_values, key=lambda item: item[1])[1] + + return expected_height, expected_width + + def expected_output_image_shape(self, images): + height, width = self.get_expected_values(images, batched=True) + return self.num_channels, height, width + + def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): + return prepare_image_inputs( + batch_size=self.batch_size, + num_channels=self.num_channels, + min_resolution=self.min_resolution, + max_resolution=self.max_resolution, + equal_resolution=equal_resolution, + numpify=numpify, + torchify=torchify, + ) + + +@require_torch +@require_vision +class YolosImageProcessingTest(AnnotationFormatTestMixin, ImageProcessingTestMixin, unittest.TestCase): + image_processing_class = YolosImageProcessor if is_vision_available() else None + + def setUp(self): + self.image_processor_tester = YolosImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "size")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"shortest_edge": 18, "longest_edge": 1333}) + self.assertEqual(image_processor.do_pad, True) + + image_processor = self.image_processing_class.from_dict( + self.image_processor_dict, size=42, max_size=84, pad_and_return_pixel_mask=False + ) + self.assertEqual(image_processor.size, {"shortest_edge": 42, "longest_edge": 84}) + self.assertEqual(image_processor.do_pad, False) + + def test_equivalence_padding(self): + # Initialize image_processings + image_processing_1 = self.image_processing_class(**self.image_processor_dict) + image_processing_2 = self.image_processing_class(do_resize=False, do_normalize=False, do_rescale=False) + # create random PyTorch tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test whether the method "pad" and calling the image processor return the same tensors + encoded_images_with_method = image_processing_1.pad(image_inputs, return_tensors="pt") + encoded_images = image_processing_2(image_inputs, return_tensors="pt") + + self.assertTrue( + torch.allclose(encoded_images_with_method["pixel_values"], encoded_images["pixel_values"], atol=1e-4) + ) + + @slow + def test_call_pytorch_with_coco_detection_annotations(self): + # prepare image and target + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f: + target = json.loads(f.read()) + + target = {"image_id": 39769, "annotations": target} + + # encode them + image_processing = YolosImageProcessor.from_pretrained("hustvl/yolos-small") + encoding = image_processing(images=image, annotations=target, return_tensors="pt") + + # verify pixel values + expected_shape = torch.Size([1, 3, 800, 1066]) + self.assertEqual(encoding["pixel_values"].shape, expected_shape) + + expected_slice = torch.tensor([0.2796, 0.3138, 0.3481]) + self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3], expected_slice, atol=1e-4)) + + # verify area + expected_area = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]) + self.assertTrue(torch.allclose(encoding["labels"][0]["area"], expected_area)) + # verify boxes + expected_boxes_shape = torch.Size([6, 4]) + self.assertEqual(encoding["labels"][0]["boxes"].shape, expected_boxes_shape) + expected_boxes_slice = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]) + self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0], expected_boxes_slice, atol=1e-3)) + # verify image_id + expected_image_id = torch.tensor([39769]) + self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"], expected_image_id)) + # verify is_crowd + expected_is_crowd = torch.tensor([0, 0, 0, 0, 0, 0]) + self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"], expected_is_crowd)) + # verify class_labels + expected_class_labels = torch.tensor([75, 75, 63, 65, 17, 17]) + self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"], expected_class_labels)) + # verify orig_size + expected_orig_size = torch.tensor([480, 640]) + self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"], expected_orig_size)) + # verify size + expected_size = torch.tensor([800, 1066]) + self.assertTrue(torch.allclose(encoding["labels"][0]["size"], expected_size)) + + @slow + def test_call_pytorch_with_coco_panoptic_annotations(self): + # prepare image, target and masks_path + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt", "r") as f: + target = json.loads(f.read()) + + target = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target} + + masks_path = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic") + + # encode them + image_processing = YolosImageProcessor(format="coco_panoptic") + encoding = image_processing(images=image, annotations=target, masks_path=masks_path, return_tensors="pt") + + # verify pixel values + expected_shape = torch.Size([1, 3, 800, 1066]) + self.assertEqual(encoding["pixel_values"].shape, expected_shape) + + expected_slice = torch.tensor([0.2796, 0.3138, 0.3481]) + self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3], expected_slice, atol=1e-4)) + + # verify area + expected_area = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]) + self.assertTrue(torch.allclose(encoding["labels"][0]["area"], expected_area)) + # verify boxes + expected_boxes_shape = torch.Size([6, 4]) + self.assertEqual(encoding["labels"][0]["boxes"].shape, expected_boxes_shape) + expected_boxes_slice = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]) + self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0], expected_boxes_slice, atol=1e-3)) + # verify image_id + expected_image_id = torch.tensor([39769]) + self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"], expected_image_id)) + # verify is_crowd + expected_is_crowd = torch.tensor([0, 0, 0, 0, 0, 0]) + self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"], expected_is_crowd)) + # verify class_labels + expected_class_labels = torch.tensor([17, 17, 63, 75, 75, 93]) + self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"], expected_class_labels)) + # verify masks + expected_masks_sum = 822873 + self.assertEqual(encoding["labels"][0]["masks"].sum().item(), expected_masks_sum) + # verify orig_size + expected_orig_size = torch.tensor([480, 640]) + self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"], expected_orig_size)) + # verify size + expected_size = torch.tensor([800, 1066]) + self.assertTrue(torch.allclose(encoding["labels"][0]["size"], expected_size)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yolos/test_modeling_yolos.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yolos/test_modeling_yolos.py new file mode 100644 index 0000000000000000000000000000000000000000..73281df02560d0deeb313455a6cd90fd8e74ad75 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yolos/test_modeling_yolos.py @@ -0,0 +1,375 @@ +# coding=utf-8 +# Copyright 2022 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 YOLOS model. """ + + +import unittest + +from transformers import YolosConfig +from transformers.testing_utils import require_torch, require_vision, slow, torch_device +from transformers.utils import cached_property, is_torch_available, is_vision_available + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import YolosForObjectDetection, YolosModel + from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST + + +if is_vision_available(): + from PIL import Image + + from transformers import AutoImageProcessor + + +class YolosModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=[30, 30], + patch_size=2, + num_channels=3, + is_training=True, + use_labels=True, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + type_sequence_label_size=10, + initializer_range=0.02, + num_labels=3, + scope=None, + n_targets=8, + num_detection_tokens=10, + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.is_training = is_training + self.use_labels = use_labels + 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.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.scope = scope + self.n_targets = n_targets + self.num_detection_tokens = num_detection_tokens + # we set the expected sequence length (which is used in several tests) + # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens + num_patches = (image_size[1] // patch_size) * (image_size[0] // patch_size) + self.expected_seq_len = num_patches + 1 + self.num_detection_tokens + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]) + + labels = None + if self.use_labels: + # labels is a list of Dict (each Dict being the labels for a given example in the batch) + labels = [] + for i in range(self.batch_size): + target = {} + target["class_labels"] = torch.randint( + high=self.num_labels, size=(self.n_targets,), device=torch_device + ) + target["boxes"] = torch.rand(self.n_targets, 4, device=torch_device) + labels.append(target) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return YolosConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + is_decoder=False, + initializer_range=self.initializer_range, + num_detection_tokens=self.num_detection_tokens, + num_labels=self.num_labels, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = YolosModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + self.parent.assertEqual( + result.last_hidden_state.shape, (self.batch_size, self.expected_seq_len, self.hidden_size) + ) + + def create_and_check_for_object_detection(self, config, pixel_values, labels): + model = YolosForObjectDetection(config) + model.to(torch_device) + model.eval() + + result = model(pixel_values=pixel_values) + result = model(pixel_values) + + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_detection_tokens, self.num_labels + 1)) + self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_detection_tokens, 4)) + + result = model(pixel_values=pixel_values, labels=labels) + + self.parent.assertEqual(result.loss.shape, ()) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_detection_tokens, self.num_labels + 1)) + self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_detection_tokens, 4)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class YolosModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + """ + Here we also overwrite some of the tests of test_modeling_common.py, as YOLOS does not use input_ids, inputs_embeds, + attention_mask and seq_length. + """ + + all_model_classes = (YolosModel, YolosForObjectDetection) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {} + ) + + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + test_torchscript = False + + # special case for head model + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) + + if return_labels: + if model_class.__name__ == "YolosForObjectDetection": + labels = [] + for i in range(self.model_tester.batch_size): + target = {} + target["class_labels"] = torch.ones( + size=(self.model_tester.n_targets,), device=torch_device, dtype=torch.long + ) + target["boxes"] = torch.ones( + self.model_tester.n_targets, 4, device=torch_device, dtype=torch.float + ) + labels.append(target) + inputs_dict["labels"] = labels + + return inputs_dict + + def setUp(self): + self.model_tester = YolosModelTester(self) + self.config_tester = ConfigTester(self, config_class=YolosConfig, has_text_modality=False, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_inputs_embeds(self): + # YOLOS does not use inputs_embeds + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + # in YOLOS, the seq_len is different + seq_len = self.model_tester.expected_seq_len + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + out_len = len(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, seq_len, seq_len], + ) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + # YOLOS has a different seq_length + seq_length = self.model_tester.expected_seq_len + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_for_object_detection(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_object_detection(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = YolosModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_torch +@require_vision +class YolosModelIntegrationTest(unittest.TestCase): + @cached_property + def default_image_processor(self): + return AutoImageProcessor.from_pretrained("hustvl/yolos-small") if is_vision_available() else None + + @slow + def test_inference_object_detection_head(self): + model = YolosForObjectDetection.from_pretrained("hustvl/yolos-small").to(torch_device) + + image_processor = self.default_image_processor + image = prepare_img() + inputs = image_processor(images=image, return_tensors="pt").to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(inputs.pixel_values) + + # verify outputs + expected_shape = torch.Size((1, 100, 92)) + self.assertEqual(outputs.logits.shape, expected_shape) + + expected_slice_logits = torch.tensor( + [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]], + device=torch_device, + ) + expected_slice_boxes = torch.tensor( + [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]], device=torch_device + ) + self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_slice_logits, atol=1e-4)) + self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4)) + + # verify postprocessing + results = image_processor.post_process_object_detection( + outputs, threshold=0.3, target_sizes=[image.size[::-1]] + )[0] + expected_scores = torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]).to(torch_device) + expected_labels = [75, 75, 17, 63, 17] + expected_slice_boxes = torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]).to(torch_device) + + self.assertEqual(len(results["scores"]), 5) + self.assertTrue(torch.allclose(results["scores"], expected_scores, atol=1e-4)) + self.assertSequenceEqual(results["labels"].tolist(), expected_labels) + self.assertTrue(torch.allclose(results["boxes"][0, :], expected_slice_boxes)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yoso/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yoso/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yoso/test_modeling_yoso.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yoso/test_modeling_yoso.py new file mode 100644 index 0000000000000000000000000000000000000000..67d7b9edc4e4c376301a992b9a4ff9ee6304e256 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/models/yoso/test_modeling_yoso.py @@ -0,0 +1,417 @@ +# coding=utf-8 +# Copyright 2022 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 YOSO model. """ + + +import unittest + +from transformers import YosoConfig, is_torch_available +from transformers.testing_utils import require_torch, slow, torch_device + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + YosoForMaskedLM, + YosoForMultipleChoice, + YosoForQuestionAnswering, + YosoForSequenceClassification, + YosoForTokenClassification, + YosoModel, + ) + from transformers.models.yoso.modeling_yoso import YOSO_PRETRAINED_MODEL_ARCHIVE_LIST + + +class YosoModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_input_mask=True, + use_token_type_ids=True, + use_labels=True, + vocab_size=99, + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=37, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=512, + type_vocab_size=16, + type_sequence_label_size=2, + initializer_range=0.02, + num_labels=3, + num_choices=4, + scope=None, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_input_mask = use_input_mask + self.use_token_type_ids = use_token_type_ids + 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.type_vocab_size = type_vocab_size + self.type_sequence_label_size = type_sequence_label_size + self.initializer_range = initializer_range + self.num_labels = num_labels + self.num_choices = num_choices + self.scope = scope + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + input_mask = None + if self.use_input_mask: + input_mask = random_attention_mask([self.batch_size, self.seq_length]) + + token_type_ids = None + if self.use_token_type_ids: + token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) + + sequence_labels = None + token_labels = None + choice_labels = None + if self.use_labels: + sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) + choice_labels = ids_tensor([self.batch_size], self.num_choices) + + config = self.get_config() + + return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + + def get_config(self): + return YosoConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + hidden_act=self.hidden_act, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + type_vocab_size=self.type_vocab_size, + is_decoder=False, + initializer_range=self.initializer_range, + ) + + def get_pipeline_config(self): + config = self.get_config() + config.vocab_size = 300 + return config + + def prepare_config_and_inputs_for_decoder(self): + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = self.prepare_config_and_inputs() + + config.is_decoder = True + encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) + encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) + + return ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ) + + def create_and_check_model( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = YosoModel(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + result = model(input_ids, token_type_ids=token_type_ids) + result = model(input_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_model_as_decoder( + self, + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + encoder_hidden_states, + encoder_attention_mask, + ): + config.add_cross_attention = True + model = YosoModel(config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + ) + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + encoder_hidden_states=encoder_hidden_states, + ) + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) + + def create_and_check_for_masked_lm( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = YosoForMaskedLM(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) + + def create_and_check_for_question_answering( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + model = YosoForQuestionAnswering(config=config) + model.to(torch_device) + model.eval() + result = model( + input_ids, + attention_mask=input_mask, + token_type_ids=token_type_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) + self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) + + def create_and_check_for_sequence_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = YosoForSequenceClassification(config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) + + def create_and_check_for_token_classification( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_labels = self.num_labels + model = YosoForTokenClassification(config=config) + model.to(torch_device) + model.eval() + result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) + + def create_and_check_for_multiple_choice( + self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels + ): + config.num_choices = self.num_choices + model = YosoForMultipleChoice(config=config) + model.to(torch_device) + model.eval() + multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() + result = model( + multiple_choice_inputs_ids, + attention_mask=multiple_choice_input_mask, + token_type_ids=multiple_choice_token_type_ids, + labels=choice_labels, + ) + self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + ( + config, + input_ids, + token_type_ids, + input_mask, + sequence_labels, + token_labels, + choice_labels, + ) = config_and_inputs + inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} + return config, inputs_dict + + +@require_torch +class YosoModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + YosoModel, + YosoForMaskedLM, + YosoForMultipleChoice, + YosoForQuestionAnswering, + YosoForSequenceClassification, + YosoForTokenClassification, + ) + if is_torch_available() + else () + ) + test_pruning = False + test_headmasking = False + test_torchscript = False + + all_generative_model_classes = () + pipeline_model_mapping = ( + { + "feature-extraction": YosoModel, + "fill-mask": YosoForMaskedLM, + "question-answering": YosoForQuestionAnswering, + "text-classification": YosoForSequenceClassification, + "token-classification": YosoForTokenClassification, + "zero-shot": YosoForSequenceClassification, + } + if is_torch_available() + else {} + ) + + def setUp(self): + self.model_tester = YosoModelTester(self) + self.config_tester = ConfigTester(self, config_class=YosoConfig, hidden_size=37) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_model_various_embeddings(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + for type in ["absolute", "relative_key", "relative_key_query"]: + config_and_inputs[0].position_embedding_type = type + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_for_masked_lm(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) + + def test_for_multiple_choice(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) + + def test_for_question_answering(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_question_answering(*config_and_inputs) + + def test_for_sequence_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) + + def test_for_token_classification(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_for_token_classification(*config_and_inputs) + + @slow + def test_model_from_pretrained(self): + for model_name in YOSO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + model = YosoModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_attention_outputs(self): + return + + +@require_torch +class YosoModelIntegrationTest(unittest.TestCase): + @slow + def test_inference_no_head(self): + model = YosoModel.from_pretrained("uw-madison/yoso-4096") + input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) + + with torch.no_grad(): + output = model(input_ids)[0] + + expected_shape = torch.Size((1, 6, 768)) + self.assertEqual(output.shape, expected_shape) + + expected_slice = torch.tensor( + [[[-0.0611, 0.1242, 0.0840], [0.0280, -0.0048, 0.1125], [0.0106, 0.0226, 0.0751]]] + ) + + self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_masked_lm(self): + model = YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096") + input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) + + with torch.no_grad(): + output = model(input_ids)[0] + + vocab_size = 50265 + + expected_shape = torch.Size((1, 6, vocab_size)) + self.assertEqual(output.shape, expected_shape) + + expected_slice = torch.tensor( + [[[-2.1313, -3.7285, -2.2407], [-2.7047, -3.3314, -2.6408], [0.0629, -2.5166, -0.3356]]] + ) + + self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4)) + + @slow + def test_inference_masked_lm_long_input(self): + model = YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096") + input_ids = torch.arange(4096).unsqueeze(0) + + with torch.no_grad(): + output = model(input_ids)[0] + + vocab_size = 50265 + + expected_shape = torch.Size((1, 4096, vocab_size)) + self.assertEqual(output.shape, expected_shape) + + expected_slice = torch.tensor( + [[[-2.3914, -4.3742, -5.0956], [-4.0988, -4.2384, -7.0406], [-3.1427, -3.7192, -6.6800]]] + ) + + self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/optimization/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/optimization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/optimization/test_optimization.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/optimization/test_optimization.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee8513dacde6afe17c05afe188f89f3aa35a5c6 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/optimization/test_optimization.py @@ -0,0 +1,186 @@ +# coding=utf-8 +# 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 os +import tempfile +import unittest + +from transformers import is_torch_available +from transformers.testing_utils import require_torch + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import ( + Adafactor, + AdamW, + get_constant_schedule, + get_constant_schedule_with_warmup, + get_cosine_schedule_with_warmup, + get_cosine_with_hard_restarts_schedule_with_warmup, + get_inverse_sqrt_schedule, + get_linear_schedule_with_warmup, + get_polynomial_decay_schedule_with_warmup, + ) + + +def unwrap_schedule(scheduler, num_steps=10): + lrs = [] + for _ in range(num_steps): + lrs.append(scheduler.get_lr()[0]) + scheduler.step() + return lrs + + +def unwrap_and_save_reload_schedule(scheduler, num_steps=10): + lrs = [] + for step in range(num_steps): + lrs.append(scheduler.get_lr()[0]) + scheduler.step() + if step == num_steps // 2: + with tempfile.TemporaryDirectory() as tmpdirname: + file_name = os.path.join(tmpdirname, "schedule.bin") + torch.save(scheduler.state_dict(), file_name) + + state_dict = torch.load(file_name) + scheduler.load_state_dict(state_dict) + return lrs + + +@require_torch +class OptimizationTest(unittest.TestCase): + def assertListAlmostEqual(self, list1, list2, tol): + self.assertEqual(len(list1), len(list2)) + for a, b in zip(list1, list2): + self.assertAlmostEqual(a, b, delta=tol) + + def test_adam_w(self): + w = torch.tensor([0.1, -0.2, -0.1], requires_grad=True) + target = torch.tensor([0.4, 0.2, -0.5]) + criterion = nn.MSELoss() + # No warmup, constant schedule, no gradient clipping + optimizer = AdamW(params=[w], lr=2e-1, weight_decay=0.0) + for _ in range(100): + loss = criterion(w, target) + loss.backward() + optimizer.step() + w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. + w.grad.zero_() + self.assertListAlmostEqual(w.tolist(), [0.4, 0.2, -0.5], tol=1e-2) + + def test_adafactor(self): + w = torch.tensor([0.1, -0.2, -0.1], requires_grad=True) + target = torch.tensor([0.4, 0.2, -0.5]) + criterion = nn.MSELoss() + # No warmup, constant schedule, no gradient clipping + optimizer = Adafactor( + params=[w], + lr=1e-2, + eps=(1e-30, 1e-3), + clip_threshold=1.0, + decay_rate=-0.8, + beta1=None, + weight_decay=0.0, + relative_step=False, + scale_parameter=False, + warmup_init=False, + ) + for _ in range(1000): + loss = criterion(w, target) + loss.backward() + optimizer.step() + w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. + w.grad.zero_() + self.assertListAlmostEqual(w.tolist(), [0.4, 0.2, -0.5], tol=1e-2) + + +@require_torch +class ScheduleInitTest(unittest.TestCase): + m = nn.Linear(50, 50) if is_torch_available() else None + optimizer = AdamW(m.parameters(), lr=10.0) if is_torch_available() else None + num_steps = 10 + + def assertListAlmostEqual(self, list1, list2, tol, msg=None): + self.assertEqual(len(list1), len(list2)) + for a, b in zip(list1, list2): + self.assertAlmostEqual(a, b, delta=tol, msg=msg) + + def test_schedulers(self): + common_kwargs = {"num_warmup_steps": 2, "num_training_steps": 10} + # schedulers doct format + # function: (sched_args_dict, expected_learning_rates) + scheds = { + get_constant_schedule: ({}, [10.0] * self.num_steps), + get_constant_schedule_with_warmup: ( + {"num_warmup_steps": 4}, + [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], + ), + get_linear_schedule_with_warmup: ( + {**common_kwargs}, + [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], + ), + get_cosine_schedule_with_warmup: ( + {**common_kwargs}, + [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], + ), + get_cosine_with_hard_restarts_schedule_with_warmup: ( + {**common_kwargs, "num_cycles": 2}, + [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], + ), + get_polynomial_decay_schedule_with_warmup: ( + {**common_kwargs, "power": 2.0, "lr_end": 1e-7}, + [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], + ), + get_inverse_sqrt_schedule: ( + {"num_warmup_steps": 2}, + [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], + ), + } + + for scheduler_func, data in scheds.items(): + kwargs, expected_learning_rates = data + + scheduler = scheduler_func(self.optimizer, **kwargs) + self.assertEqual(len([scheduler.get_lr()[0]]), 1) + lrs_1 = unwrap_schedule(scheduler, self.num_steps) + self.assertListAlmostEqual( + lrs_1, + expected_learning_rates, + tol=1e-2, + msg=f"failed for {scheduler_func} in normal scheduler", + ) + + scheduler = scheduler_func(self.optimizer, **kwargs) + if scheduler_func.__name__ != "get_constant_schedule": + LambdaScheduleWrapper.wrap_scheduler(scheduler) # wrap to test picklability of the schedule + lrs_2 = unwrap_and_save_reload_schedule(scheduler, self.num_steps) + self.assertListEqual(lrs_1, lrs_2, msg=f"failed for {scheduler_func} in save and reload") + + +class LambdaScheduleWrapper: + """See https://github.com/huggingface/transformers/issues/21689""" + + def __init__(self, fn): + self.fn = fn + + def __call__(self, *args, **kwargs): + return self.fn(*args, **kwargs) + + @classmethod + def wrap_scheduler(self, scheduler): + scheduler.lr_lambdas = list(map(self, scheduler.lr_lambdas)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/optimization/test_optimization_tf.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/optimization/test_optimization_tf.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a948c938dfdc440cae1ad16c0e5c25056b1aa3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/optimization/test_optimization_tf.py @@ -0,0 +1,100 @@ +# 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 unittest + +from transformers import is_tf_available +from transformers.testing_utils import require_tf + + +if is_tf_available(): + import tensorflow as tf + from tensorflow.python.eager import context + from tensorflow.python.framework import ops + + from transformers import GradientAccumulator, create_optimizer + + +@require_tf +class OptimizationFTest(unittest.TestCase): + def assertListAlmostEqual(self, list1, list2, tol): + self.assertEqual(len(list1), len(list2)) + for a, b in zip(list1, list2): + self.assertAlmostEqual(a, b, delta=tol) + + def testGradientAccumulator(self): + accumulator = GradientAccumulator() + accumulator([tf.constant([1.0, 2.0])]) + accumulator([tf.constant([-2.0, 1.0])]) + accumulator([tf.constant([-1.0, 2.0])]) + with self.assertRaises(ValueError): + accumulator([tf.constant([1.0, 1.0]), tf.constant([2.0, 2.0])]) + self.assertEqual(accumulator.step, 3) + self.assertEqual(len(accumulator.gradients), 1) + self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist(), [-2.0, 5.0], tol=1e-2) + accumulator.reset() + self.assertEqual(accumulator.step, 0) + self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist(), [0.0, 0.0], tol=1e-2) + + def testGradientAccumulatorDistributionStrategy(self): + context._context = None + ops.enable_eager_execution_internal() + physical_devices = tf.config.list_physical_devices("CPU") + if len(physical_devices) == 1: + tf.config.set_logical_device_configuration( + physical_devices[0], [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] + ) + devices = tf.config.list_logical_devices(device_type="CPU") + strategy = tf.distribute.MirroredStrategy(devices=devices[:2]) + + with strategy.scope(): + accumulator = GradientAccumulator() + variable = tf.Variable([4.0, 3.0]) + optimizer, _ = create_optimizer(5e-5, 10, 5) + gradient_placeholder = tf.Variable([0.0, 0.0], trainable=False) + + def accumulate_on_replica(gradient): + accumulator([gradient]) + + def apply_on_replica(): + optimizer.apply_gradients(list(zip(accumulator.gradients, [variable]))) + + @tf.function + def accumulate(grad1, grad2): + with strategy.scope(): + local_variables = strategy.experimental_local_results(gradient_placeholder) + local_variables[0].assign(grad1) + local_variables[1].assign(grad2) + strategy.run(accumulate_on_replica, args=(gradient_placeholder,)) + + @tf.function + def apply_grad(): + with strategy.scope(): + strategy.run(apply_on_replica) + + def _check_local_values(grad1, grad2): + values = strategy.experimental_local_results(accumulator._gradients[0]) + self.assertListAlmostEqual(values[0].value(), grad1, tol=1e-2) + self.assertListAlmostEqual(values[1].value(), grad2, tol=1e-2) + + accumulate([1.0, 2.0], [-1.0, 1.0]) + accumulate([3.0, -1.0], [-1.0, -1.0]) + accumulate([-2.0, 2.0], [3.0, -2.0]) + self.assertEqual(accumulator.step, 3) + _check_local_values([2.0, 3.0], [1.0, -2.0]) + apply_grad() + self.assertListAlmostEqual(variable.value(), [4.0, 3.0], tol=1e-2) + accumulator.reset() + self.assertEqual(accumulator.step, 0) + _check_local_values([0.0, 0.0], [0.0, 0.0]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/peft_integration/test_peft_integration.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/peft_integration/test_peft_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..50890b886ccf4bb8477efc08a6edbde924ec6877 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/peft_integration/test_peft_integration.py @@ -0,0 +1,496 @@ +# coding=utf-8 +# Copyright 2023 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 os +import tempfile +import unittest + +from huggingface_hub import hf_hub_download + +from transformers import AutoModelForCausalLM, OPTForCausalLM +from transformers.testing_utils import require_peft, require_torch, require_torch_gpu, slow, torch_device +from transformers.utils import is_torch_available + + +if is_torch_available(): + import torch + + +@require_peft +@require_torch +class PeftTesterMixin: + peft_test_model_ids = ("peft-internal-testing/tiny-OPTForCausalLM-lora",) + transformers_test_model_ids = ("hf-internal-testing/tiny-random-OPTForCausalLM",) + transformers_test_model_classes = (AutoModelForCausalLM, OPTForCausalLM) + + +# TODO: run it with CI after PEFT release. +@slow +class PeftIntegrationTester(unittest.TestCase, PeftTesterMixin): + """ + A testing suite that makes sure that the PeftModel class is correctly integrated into the transformers library. + """ + + def _check_lora_correctly_converted(self, model): + """ + Utility method to check if the model has correctly adapters injected on it. + """ + from peft.tuners.tuners_utils import BaseTunerLayer + + is_peft_loaded = False + + for _, m in model.named_modules(): + if isinstance(m, BaseTunerLayer): + is_peft_loaded = True + break + + return is_peft_loaded + + def test_peft_from_pretrained(self): + """ + Simple test that tests the basic usage of PEFT model through `from_pretrained`. + This checks if we pass a remote folder that contains an adapter config and adapter weights, it + should correctly load a model that has adapters injected on it. + """ + for model_id in self.peft_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id).to(torch_device) + + self.assertTrue(self._check_lora_correctly_converted(peft_model)) + self.assertTrue(peft_model._hf_peft_config_loaded) + # dummy generation + _ = peft_model.generate(input_ids=torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]]).to(torch_device)) + + def test_peft_state_dict(self): + """ + Simple test that checks if the returned state dict of `get_adapter_state_dict()` method contains + the expected keys. + """ + for model_id in self.peft_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id).to(torch_device) + + state_dict = peft_model.get_adapter_state_dict() + + for key in state_dict.keys(): + self.assertTrue("lora" in key) + + def test_peft_save_pretrained(self): + """ + Test that checks various combinations of `save_pretrained` with a model that has adapters loaded + on it. This checks if the saved model contains the expected files (adapter weights and adapter config). + """ + for model_id in self.peft_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id).to(torch_device) + + with tempfile.TemporaryDirectory() as tmpdirname: + peft_model.save_pretrained(tmpdirname) + + self.assertTrue("adapter_model.safetensors" in os.listdir(tmpdirname)) + self.assertTrue("adapter_config.json" in os.listdir(tmpdirname)) + + self.assertTrue("config.json" not in os.listdir(tmpdirname)) + self.assertTrue("pytorch_model.bin" not in os.listdir(tmpdirname)) + self.assertTrue("model.safetensors" not in os.listdir(tmpdirname)) + + peft_model = transformers_class.from_pretrained(tmpdirname).to(torch_device) + self.assertTrue(self._check_lora_correctly_converted(peft_model)) + + peft_model.save_pretrained(tmpdirname, safe_serialization=False) + self.assertTrue("adapter_model.bin" in os.listdir(tmpdirname)) + self.assertTrue("adapter_config.json" in os.listdir(tmpdirname)) + + peft_model = transformers_class.from_pretrained(tmpdirname).to(torch_device) + self.assertTrue(self._check_lora_correctly_converted(peft_model)) + + def test_peft_enable_disable_adapters(self): + """ + A test that checks if `enable_adapters` and `disable_adapters` methods work as expected. + """ + from peft import LoraConfig + + dummy_input = torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]]).to(torch_device) + + for model_id in self.transformers_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id).to(torch_device) + + peft_config = LoraConfig(init_lora_weights=False) + + peft_model.add_adapter(peft_config) + + peft_logits = peft_model(dummy_input).logits + + peft_model.disable_adapters() + + peft_logits_disabled = peft_model(dummy_input).logits + + peft_model.enable_adapters() + + peft_logits_enabled = peft_model(dummy_input).logits + + self.assertTrue(torch.allclose(peft_logits, peft_logits_enabled, atol=1e-12, rtol=1e-12)) + self.assertFalse(torch.allclose(peft_logits_enabled, peft_logits_disabled, atol=1e-12, rtol=1e-12)) + + def test_peft_add_adapter(self): + """ + Simple test that tests if `add_adapter` works as expected + """ + from peft import LoraConfig + + for model_id in self.transformers_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + model = transformers_class.from_pretrained(model_id).to(torch_device) + + peft_config = LoraConfig(init_lora_weights=False) + + model.add_adapter(peft_config) + + self.assertTrue(self._check_lora_correctly_converted(model)) + # dummy generation + _ = model.generate(input_ids=torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]]).to(torch_device)) + + def test_peft_add_adapter_from_pretrained(self): + """ + Simple test that tests if `add_adapter` works as expected + """ + from peft import LoraConfig + + for model_id in self.transformers_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + model = transformers_class.from_pretrained(model_id).to(torch_device) + + peft_config = LoraConfig(init_lora_weights=False) + + model.add_adapter(peft_config) + + self.assertTrue(self._check_lora_correctly_converted(model)) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_from_pretrained = transformers_class.from_pretrained(tmpdirname).to(torch_device) + self.assertTrue(self._check_lora_correctly_converted(model_from_pretrained)) + + def test_peft_add_adapter_modules_to_save(self): + """ + Simple test that tests if `add_adapter` works as expected when training with + modules to save. + """ + from peft import LoraConfig + from peft.utils import ModulesToSaveWrapper + + for model_id in self.transformers_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + dummy_input = torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]]).to(torch_device) + + model = transformers_class.from_pretrained(model_id).to(torch_device) + peft_config = LoraConfig(init_lora_weights=False, modules_to_save=["lm_head"]) + model.add_adapter(peft_config) + self._check_lora_correctly_converted(model) + + _has_modules_to_save_wrapper = False + for name, module in model.named_modules(): + if isinstance(module, ModulesToSaveWrapper): + _has_modules_to_save_wrapper = True + self.assertTrue(module.modules_to_save.default.weight.requires_grad) + self.assertTrue("lm_head" in name) + break + + self.assertTrue(_has_modules_to_save_wrapper) + state_dict = model.get_adapter_state_dict() + + self.assertTrue("lm_head.weight" in state_dict.keys()) + + logits = model(dummy_input).logits + loss = logits.mean() + loss.backward() + + for _, param in model.named_parameters(): + if param.requires_grad: + self.assertTrue(param.grad is not None) + + def test_peft_add_adapter_training_gradient_checkpointing(self): + """ + Simple test that tests if `add_adapter` works as expected when training with + gradient checkpointing. + """ + from peft import LoraConfig + + for model_id in self.transformers_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + model = transformers_class.from_pretrained(model_id).to(torch_device) + + peft_config = LoraConfig(init_lora_weights=False) + + model.add_adapter(peft_config) + + self.assertTrue(self._check_lora_correctly_converted(model)) + + # When attaching adapters the input embeddings will stay frozen, this will + # lead to the output embedding having requires_grad=False. + dummy_input = torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]]).to(torch_device) + frozen_output = model.get_input_embeddings()(dummy_input) + self.assertTrue(frozen_output.requires_grad is False) + + model.gradient_checkpointing_enable() + + # Since here we attached the hook, the input should have requires_grad to set + # properly + non_frozen_output = model.get_input_embeddings()(dummy_input) + self.assertTrue(non_frozen_output.requires_grad is True) + + # To repro the Trainer issue + dummy_input.requires_grad = False + + for name, param in model.named_parameters(): + if "lora" in name.lower(): + self.assertTrue(param.requires_grad) + + logits = model(dummy_input).logits + loss = logits.mean() + loss.backward() + + for name, param in model.named_parameters(): + if param.requires_grad: + self.assertTrue("lora" in name.lower()) + self.assertTrue(param.grad is not None) + + def test_peft_add_multi_adapter(self): + """ + Simple test that tests the basic usage of PEFT model through `from_pretrained`. This test tests if + add_adapter works as expected in multi-adapter setting. + """ + from peft import LoraConfig + from peft.tuners.tuners_utils import BaseTunerLayer + + dummy_input = torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]]).to(torch_device) + + for model_id in self.transformers_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + is_peft_loaded = False + model = transformers_class.from_pretrained(model_id).to(torch_device) + + logits_original_model = model(dummy_input).logits + + peft_config = LoraConfig(init_lora_weights=False) + + model.add_adapter(peft_config) + + logits_adapter_1 = model(dummy_input) + + model.add_adapter(peft_config, adapter_name="adapter-2") + + logits_adapter_2 = model(dummy_input) + + for _, m in model.named_modules(): + if isinstance(m, BaseTunerLayer): + is_peft_loaded = True + break + + self.assertTrue(is_peft_loaded) + + # dummy generation + _ = model.generate(input_ids=dummy_input) + + model.set_adapter("default") + self.assertTrue(model.active_adapters() == ["default"]) + self.assertTrue(model.active_adapter() == "default") + + model.set_adapter("adapter-2") + self.assertTrue(model.active_adapters() == ["adapter-2"]) + self.assertTrue(model.active_adapter() == "adapter-2") + + # Logits comparison + self.assertFalse( + torch.allclose(logits_adapter_1.logits, logits_adapter_2.logits, atol=1e-6, rtol=1e-6) + ) + self.assertFalse(torch.allclose(logits_original_model, logits_adapter_2.logits, atol=1e-6, rtol=1e-6)) + + model.set_adapter(["adapter-2", "default"]) + self.assertTrue(model.active_adapters() == ["adapter-2", "default"]) + self.assertTrue(model.active_adapter() == "adapter-2") + + logits_adapter_mixed = model(dummy_input) + self.assertFalse( + torch.allclose(logits_adapter_1.logits, logits_adapter_mixed.logits, atol=1e-6, rtol=1e-6) + ) + + self.assertFalse( + torch.allclose(logits_adapter_2.logits, logits_adapter_mixed.logits, atol=1e-6, rtol=1e-6) + ) + + # multi active adapter saving not supported + with self.assertRaises(ValueError), tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + @require_torch_gpu + def test_peft_from_pretrained_kwargs(self): + """ + Simple test that tests the basic usage of PEFT model through `from_pretrained` + additional kwargs + and see if the integraiton behaves as expected. + """ + for model_id in self.peft_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id, load_in_8bit=True, device_map="auto") + + module = peft_model.model.decoder.layers[0].self_attn.v_proj + self.assertTrue(module.__class__.__name__ == "Linear8bitLt") + self.assertTrue(peft_model.hf_device_map is not None) + + # dummy generation + _ = peft_model.generate(input_ids=torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]]).to(torch_device)) + + @require_torch_gpu + def test_peft_save_quantized(self): + """ + Simple test that tests the basic usage of PEFT model save_pretrained with quantized base models + """ + # 4bit + for model_id in self.peft_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id, load_in_4bit=True, device_map="auto") + + module = peft_model.model.decoder.layers[0].self_attn.v_proj + self.assertTrue(module.__class__.__name__ == "Linear4bit") + self.assertTrue(peft_model.hf_device_map is not None) + + with tempfile.TemporaryDirectory() as tmpdirname: + peft_model.save_pretrained(tmpdirname) + self.assertTrue("adapter_model.safetensors" in os.listdir(tmpdirname)) + self.assertTrue("adapter_config.json" in os.listdir(tmpdirname)) + self.assertTrue("pytorch_model.bin" not in os.listdir(tmpdirname)) + self.assertTrue("model.safetensors" not in os.listdir(tmpdirname)) + + # 8-bit + for model_id in self.peft_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id, load_in_8bit=True, device_map="auto") + + module = peft_model.model.decoder.layers[0].self_attn.v_proj + self.assertTrue(module.__class__.__name__ == "Linear8bitLt") + self.assertTrue(peft_model.hf_device_map is not None) + + with tempfile.TemporaryDirectory() as tmpdirname: + peft_model.save_pretrained(tmpdirname) + + self.assertTrue("adapter_model.safetensors" in os.listdir(tmpdirname)) + self.assertTrue("adapter_config.json" in os.listdir(tmpdirname)) + self.assertTrue("pytorch_model.bin" not in os.listdir(tmpdirname)) + self.assertTrue("model.safetensors" not in os.listdir(tmpdirname)) + + @require_torch_gpu + def test_peft_save_quantized_regression(self): + """ + Simple test that tests the basic usage of PEFT model save_pretrained with quantized base models + Regression test to make sure everything works as expected before the safetensors integration. + """ + # 4bit + for model_id in self.peft_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id, load_in_4bit=True, device_map="auto") + + module = peft_model.model.decoder.layers[0].self_attn.v_proj + self.assertTrue(module.__class__.__name__ == "Linear4bit") + self.assertTrue(peft_model.hf_device_map is not None) + + with tempfile.TemporaryDirectory() as tmpdirname: + peft_model.save_pretrained(tmpdirname, safe_serialization=False) + self.assertTrue("adapter_model.bin" in os.listdir(tmpdirname)) + self.assertTrue("adapter_config.json" in os.listdir(tmpdirname)) + self.assertTrue("pytorch_model.bin" not in os.listdir(tmpdirname)) + self.assertTrue("model.safetensors" not in os.listdir(tmpdirname)) + + # 8-bit + for model_id in self.peft_test_model_ids: + for transformers_class in self.transformers_test_model_classes: + peft_model = transformers_class.from_pretrained(model_id, load_in_8bit=True, device_map="auto") + + module = peft_model.model.decoder.layers[0].self_attn.v_proj + self.assertTrue(module.__class__.__name__ == "Linear8bitLt") + self.assertTrue(peft_model.hf_device_map is not None) + + with tempfile.TemporaryDirectory() as tmpdirname: + peft_model.save_pretrained(tmpdirname, safe_serialization=False) + + self.assertTrue("adapter_model.bin" in os.listdir(tmpdirname)) + self.assertTrue("adapter_config.json" in os.listdir(tmpdirname)) + self.assertTrue("pytorch_model.bin" not in os.listdir(tmpdirname)) + self.assertTrue("model.safetensors" not in os.listdir(tmpdirname)) + + def test_peft_pipeline(self): + """ + Simple test that tests the basic usage of PEFT model + pipeline + """ + from transformers import pipeline + + for model_id in self.peft_test_model_ids: + pipe = pipeline("text-generation", model_id) + _ = pipe("Hello") + + def test_peft_add_adapter_with_state_dict(self): + """ + Simple test that tests the basic usage of PEFT model through `from_pretrained`. This test tests if + add_adapter works as expected with a state_dict being passed. + """ + from peft import LoraConfig + + dummy_input = torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]]).to(torch_device) + + for model_id, peft_model_id in zip(self.transformers_test_model_ids, self.peft_test_model_ids): + for transformers_class in self.transformers_test_model_classes: + model = transformers_class.from_pretrained(model_id).to(torch_device) + + peft_config = LoraConfig(init_lora_weights=False) + + with self.assertRaises(ValueError): + model.load_adapter(peft_model_id=None) + + state_dict_path = hf_hub_download(peft_model_id, "adapter_model.bin") + + dummy_state_dict = torch.load(state_dict_path) + + model.load_adapter(adapter_state_dict=dummy_state_dict, peft_config=peft_config) + with self.assertRaises(ValueError): + model.load_adapter(model.load_adapter(adapter_state_dict=dummy_state_dict, peft_config=None)) + self.assertTrue(self._check_lora_correctly_converted(model)) + + # dummy generation + _ = model.generate(input_ids=dummy_input) + + def test_peft_from_pretrained_hub_kwargs(self): + """ + Tests different combinations of PEFT model + from_pretrained + hub kwargs + """ + peft_model_id = "peft-internal-testing/tiny-opt-lora-revision" + + # This should not work + with self.assertRaises(OSError): + _ = AutoModelForCausalLM.from_pretrained(peft_model_id) + + adapter_kwargs = {"revision": "test"} + + # This should work + model = AutoModelForCausalLM.from_pretrained(peft_model_id, adapter_kwargs=adapter_kwargs) + self.assertTrue(self._check_lora_correctly_converted(model)) + + model = OPTForCausalLM.from_pretrained(peft_model_id, adapter_kwargs=adapter_kwargs) + self.assertTrue(self._check_lora_correctly_converted(model)) + + adapter_kwargs = {"revision": "main", "subfolder": "test_subfolder"} + + model = AutoModelForCausalLM.from_pretrained(peft_model_id, adapter_kwargs=adapter_kwargs) + self.assertTrue(self._check_lora_correctly_converted(model)) + + model = OPTForCausalLM.from_pretrained(peft_model_id, adapter_kwargs=adapter_kwargs) + self.assertTrue(self._check_lora_correctly_converted(model)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_audio_classification.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_audio_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..48c39ff663fbe832bd7ed8c9d8d6e59fd6f17c41 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_audio_classification.py @@ -0,0 +1,135 @@ +# Copyright 2021 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 unittest + +import numpy as np + +from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING +from transformers.pipelines import AudioClassificationPipeline, pipeline +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_torch, + require_torchaudio, + slow, +) + +from .test_pipelines_common import ANY + + +@is_pipeline_test +class AudioClassificationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING + tf_model_mapping = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + audio_classifier = AudioClassificationPipeline(model=model, feature_extractor=processor) + + # test with a raw waveform + audio = np.zeros((34000,)) + audio2 = np.zeros((14000,)) + return audio_classifier, [audio2, audio] + + def run_pipeline_test(self, audio_classifier, examples): + audio2, audio = examples + output = audio_classifier(audio) + # by default a model is initialized with num_labels=2 + self.assertEqual( + output, + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + ) + output = audio_classifier(audio, top_k=1) + self.assertEqual( + output, + [ + {"score": ANY(float), "label": ANY(str)}, + ], + ) + + self.run_torchaudio(audio_classifier) + + @require_torchaudio + def run_torchaudio(self, audio_classifier): + import datasets + + # test with a local file + dataset = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + audio = dataset[0]["audio"]["array"] + output = audio_classifier(audio) + self.assertEqual( + output, + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + ) + + @require_torch + def test_small_model_pt(self): + model = "anton-l/wav2vec2-random-tiny-classifier" + + audio_classifier = pipeline("audio-classification", model=model) + + audio = np.ones((8000,)) + output = audio_classifier(audio, top_k=4) + + EXPECTED_OUTPUT = [ + {"score": 0.0842, "label": "no"}, + {"score": 0.0838, "label": "up"}, + {"score": 0.0837, "label": "go"}, + {"score": 0.0834, "label": "right"}, + ] + EXPECTED_OUTPUT_PT_2 = [ + {"score": 0.0845, "label": "stop"}, + {"score": 0.0844, "label": "on"}, + {"score": 0.0841, "label": "right"}, + {"score": 0.0834, "label": "left"}, + ] + self.assertIn(nested_simplify(output, decimals=4), [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]) + + audio_dict = {"array": np.ones((8000,)), "sampling_rate": audio_classifier.feature_extractor.sampling_rate} + output = audio_classifier(audio_dict, top_k=4) + self.assertIn(nested_simplify(output, decimals=4), [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2]) + + @require_torch + @slow + def test_large_model_pt(self): + import datasets + + model = "superb/wav2vec2-base-superb-ks" + + audio_classifier = pipeline("audio-classification", model=model) + dataset = datasets.load_dataset("anton-l/superb_dummy", "ks", split="test") + + audio = np.array(dataset[3]["speech"], dtype=np.float32) + output = audio_classifier(audio, top_k=4) + self.assertEqual( + nested_simplify(output, decimals=3), + [ + {"score": 0.981, "label": "go"}, + {"score": 0.007, "label": "up"}, + {"score": 0.006, "label": "_unknown_"}, + {"score": 0.001, "label": "down"}, + ], + ) + + @require_tf + @unittest.skip("Audio classification is not implemented for TF") + def test_small_model_tf(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.py new file mode 100644 index 0000000000000000000000000000000000000000..2ccaf71255670ee6681ca84ebc2fe87eb5cc64d6 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.py @@ -0,0 +1,1484 @@ +# Copyright 2021 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 unittest + +import numpy as np +import pytest +from datasets import Audio, load_dataset +from huggingface_hub import hf_hub_download, snapshot_download + +from transformers import ( + MODEL_FOR_CTC_MAPPING, + MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING, + AutoFeatureExtractor, + AutoProcessor, + AutoTokenizer, + Speech2TextForConditionalGeneration, + Wav2Vec2ForCTC, + WhisperForConditionalGeneration, +) +from transformers.pipelines import AutomaticSpeechRecognitionPipeline, pipeline +from transformers.pipelines.audio_utils import chunk_bytes_iter +from transformers.pipelines.automatic_speech_recognition import _find_timestamp_sequence, chunk_iter +from transformers.testing_utils import ( + is_pipeline_test, + is_torch_available, + nested_simplify, + require_pyctcdecode, + require_tf, + require_torch, + require_torch_accelerator, + require_torchaudio, + slow, + torch_device, +) + +from .test_pipelines_common import ANY + + +if is_torch_available(): + import torch + + +# We can't use this mixin because it assumes TF support. +# from .test_pipelines_common import CustomInputPipelineCommonMixin + + +@is_pipeline_test +class AutomaticSpeechRecognitionPipelineTests(unittest.TestCase): + model_mapping = dict( + (list(MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING.items()) if MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING else []) + + (MODEL_FOR_CTC_MAPPING.items() if MODEL_FOR_CTC_MAPPING else []) + ) + + def get_test_pipeline(self, model, tokenizer, processor): + if tokenizer is None: + # Side effect of no Fast Tokenizer class for these model, so skipping + # But the slow tokenizer test should still run as they're quite small + self.skipTest("No tokenizer available") + return + # return None, None + + speech_recognizer = AutomaticSpeechRecognitionPipeline( + model=model, tokenizer=tokenizer, feature_extractor=processor + ) + + # test with a raw waveform + audio = np.zeros((34000,)) + audio2 = np.zeros((14000,)) + return speech_recognizer, [audio, audio2] + + def run_pipeline_test(self, speech_recognizer, examples): + audio = np.zeros((34000,)) + outputs = speech_recognizer(audio) + self.assertEqual(outputs, {"text": ANY(str)}) + + # Striding + audio = {"raw": audio, "stride": (0, 4000), "sampling_rate": speech_recognizer.feature_extractor.sampling_rate} + if speech_recognizer.type == "ctc": + outputs = speech_recognizer(audio) + self.assertEqual(outputs, {"text": ANY(str)}) + elif "Whisper" in speech_recognizer.model.__class__.__name__: + outputs = speech_recognizer(audio) + self.assertEqual(outputs, {"text": ANY(str)}) + else: + # Non CTC models cannot use striding. + with self.assertRaises(ValueError): + outputs = speech_recognizer(audio) + + # Timestamps + audio = np.zeros((34000,)) + if speech_recognizer.type == "ctc": + outputs = speech_recognizer(audio, return_timestamps="char") + self.assertIsInstance(outputs["chunks"], list) + n = len(outputs["chunks"]) + self.assertEqual( + outputs, + { + "text": ANY(str), + "chunks": [{"text": ANY(str), "timestamp": (ANY(float), ANY(float))} for i in range(n)], + }, + ) + + outputs = speech_recognizer(audio, return_timestamps="word") + self.assertIsInstance(outputs["chunks"], list) + n = len(outputs["chunks"]) + self.assertEqual( + outputs, + { + "text": ANY(str), + "chunks": [{"text": ANY(str), "timestamp": (ANY(float), ANY(float))} for i in range(n)], + }, + ) + elif "Whisper" in speech_recognizer.model.__class__.__name__: + outputs = speech_recognizer(audio, return_timestamps=True) + self.assertIsInstance(outputs["chunks"], list) + nb_chunks = len(outputs["chunks"]) + self.assertGreater(nb_chunks, 0) + self.assertEqual( + outputs, + { + "text": ANY(str), + "chunks": [{"text": ANY(str), "timestamp": (ANY(float), ANY(float))} for i in range(nb_chunks)], + }, + ) + else: + # Non CTC models cannot use return_timestamps + with self.assertRaisesRegex( + ValueError, "^We cannot return_timestamps yet on non-CTC models apart from Whisper!$" + ): + outputs = speech_recognizer(audio, return_timestamps="char") + + @require_torch + @slow + def test_pt_defaults(self): + pipeline("automatic-speech-recognition", framework="pt") + + @require_torch + def test_small_model_pt(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="facebook/s2t-small-mustc-en-fr-st", + tokenizer="facebook/s2t-small-mustc-en-fr-st", + framework="pt", + ) + waveform = np.tile(np.arange(1000, dtype=np.float32), 34) + output = speech_recognizer(waveform) + self.assertEqual(output, {"text": "(Applaudissements)"}) + output = speech_recognizer(waveform, chunk_length_s=10) + self.assertEqual(output, {"text": "(Applaudissements)"}) + + # Non CTC models cannot use return_timestamps + with self.assertRaisesRegex( + ValueError, "^We cannot return_timestamps yet on non-CTC models apart from Whisper!$" + ): + _ = speech_recognizer(waveform, return_timestamps="char") + + @slow + @require_torch_accelerator + def test_whisper_fp16(self): + speech_recognizer = pipeline( + model="openai/whisper-base", + device=torch_device, + torch_dtype=torch.float16, + ) + waveform = np.tile(np.arange(1000, dtype=np.float32), 34) + speech_recognizer(waveform) + + @require_torch + def test_small_model_pt_seq2seq(self): + speech_recognizer = pipeline( + model="hf-internal-testing/tiny-random-speech-encoder-decoder", + framework="pt", + ) + + waveform = np.tile(np.arange(1000, dtype=np.float32), 34) + output = speech_recognizer(waveform) + self.assertEqual(output, {"text": "あл ش 湯 清 ه ܬ া लᆨしث ल eか u w 全 u"}) + + @require_torch + def test_small_model_pt_seq2seq_gen_kwargs(self): + speech_recognizer = pipeline( + model="hf-internal-testing/tiny-random-speech-encoder-decoder", + framework="pt", + ) + + waveform = np.tile(np.arange(1000, dtype=np.float32), 34) + output = speech_recognizer(waveform, max_new_tokens=10, generate_kwargs={"num_beams": 2}) + self.assertEqual(output, {"text": "あл † γ ت ב オ 束 泣 足"}) + + @slow + @require_torch + @require_pyctcdecode + def test_large_model_pt_with_lm(self): + dataset = load_dataset("Narsil/asr_dummy", streaming=True) + third_item = next(iter(dataset["test"].skip(3))) + filename = third_item["file"] + + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm", + framework="pt", + ) + self.assertEqual(speech_recognizer.type, "ctc_with_lm") + + output = speech_recognizer(filename) + self.assertEqual( + output, + {"text": "y en las ramas medio sumergidas revoloteaban algunos pájaros de quimérico y legendario plumaje"}, + ) + + # Override back to pure CTC + speech_recognizer.type = "ctc" + output = speech_recognizer(filename) + # plumajre != plumaje + self.assertEqual( + output, + { + "text": ( + "y en las ramas medio sumergidas revoloteaban algunos pájaros de quimérico y legendario plumajre" + ) + }, + ) + + speech_recognizer.type = "ctc_with_lm" + # Simple test with CTC with LM, chunking + timestamps + output = speech_recognizer(filename, chunk_length_s=2.0, return_timestamps="word") + self.assertEqual( + output, + { + "text": ( + "y en las ramas medio sumergidas revoloteaban algunos pájaros de quimérico y legendario plumajcri" + ), + "chunks": [ + {"text": "y", "timestamp": (0.52, 0.54)}, + {"text": "en", "timestamp": (0.6, 0.68)}, + {"text": "las", "timestamp": (0.74, 0.84)}, + {"text": "ramas", "timestamp": (0.94, 1.24)}, + {"text": "medio", "timestamp": (1.32, 1.52)}, + {"text": "sumergidas", "timestamp": (1.56, 2.22)}, + {"text": "revoloteaban", "timestamp": (2.36, 3.0)}, + {"text": "algunos", "timestamp": (3.06, 3.38)}, + {"text": "pájaros", "timestamp": (3.46, 3.86)}, + {"text": "de", "timestamp": (3.92, 4.0)}, + {"text": "quimérico", "timestamp": (4.08, 4.6)}, + {"text": "y", "timestamp": (4.66, 4.68)}, + {"text": "legendario", "timestamp": (4.74, 5.26)}, + {"text": "plumajcri", "timestamp": (5.34, 5.74)}, + ], + }, + ) + # CTC + LM models cannot use return_timestamps="char" + with self.assertRaisesRegex( + ValueError, "^CTC with LM can only predict word level timestamps, set `return_timestamps='word'`$" + ): + _ = speech_recognizer(filename, return_timestamps="char") + + @require_tf + def test_small_model_tf(self): + self.skipTest("Tensorflow not supported yet.") + + @require_torch + def test_torch_small_no_tokenizer_files(self): + # test that model without tokenizer file cannot be loaded + with pytest.raises(OSError): + pipeline( + task="automatic-speech-recognition", + model="patrickvonplaten/tiny-wav2vec2-no-tokenizer", + framework="pt", + ) + + @require_torch + @slow + def test_torch_large(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="facebook/wav2vec2-base-960h", + tokenizer="facebook/wav2vec2-base-960h", + framework="pt", + ) + waveform = np.tile(np.arange(1000, dtype=np.float32), 34) + output = speech_recognizer(waveform) + self.assertEqual(output, {"text": ""}) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + output = speech_recognizer(filename) + self.assertEqual(output, {"text": "A MAN SAID TO THE UNIVERSE SIR I EXIST"}) + + @slow + @require_torch + @slow + def test_return_timestamps_in_preprocess(self): + pipe = pipeline( + task="automatic-speech-recognition", + model="openai/whisper-tiny", + chunk_length_s=8, + stride_length_s=1, + ) + data = load_dataset("librispeech_asr", "clean", split="test", streaming=True) + sample = next(iter(data)) + pipe.model.config.forced_decoder_ids = pipe.tokenizer.get_decoder_prompt_ids(language="en", task="transcribe") + + res = pipe(sample["audio"]["array"]) + self.assertEqual(res, {"text": " Conquered returned to its place amidst the tents."}) + res = pipe(sample["audio"]["array"], return_timestamps=True) + self.assertEqual( + res, + { + "text": " Conquered returned to its place amidst the tents.", + "chunks": [{"timestamp": (0.0, 3.36), "text": " Conquered returned to its place amidst the tents."}], + }, + ) + pipe.model.generation_config.alignment_heads = [[2, 2], [3, 0], [3, 2], [3, 3], [3, 4], [3, 5]] + res = pipe(sample["audio"]["array"], return_timestamps="word") + + # fmt: off + self.assertEqual( + res, + { + 'text': ' Conquered returned to its place amidst the tents.', + 'chunks': [ + {'text': ' Conquered', 'timestamp': (0.5, 1.2)}, + {'text': ' returned', 'timestamp': (1.2, 1.64)}, + {'text': ' to', 'timestamp': (1.64, 1.84)}, + {'text': ' its', 'timestamp': (1.84, 2.02)}, + {'text': ' place', 'timestamp': (2.02, 2.28)}, + {'text': ' amidst', 'timestamp': (2.28, 2.8)}, + {'text': ' the', 'timestamp': (2.8, 2.98)}, + {'text': ' tents.', 'timestamp': (2.98, 3.48)}, + ], + }, + ) + # fmt: on + + @require_torch + def test_return_timestamps_in_init(self): + # segment-level timestamps are accepted + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny") + tokenizer = AutoTokenizer.from_pretrained("openai/whisper-tiny") + feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-tiny") + + dummy_speech = np.ones(100) + + pipe = pipeline( + task="automatic-speech-recognition", + model=model, + feature_extractor=feature_extractor, + tokenizer=tokenizer, + chunk_length_s=8, + stride_length_s=1, + return_timestamps=True, + ) + + _ = pipe(dummy_speech) + + # word-level timestamps are accepted + pipe = pipeline( + task="automatic-speech-recognition", + model=model, + feature_extractor=feature_extractor, + tokenizer=tokenizer, + chunk_length_s=8, + stride_length_s=1, + return_timestamps="word", + ) + + _ = pipe(dummy_speech) + + # char-level timestamps are not accepted + with self.assertRaisesRegex( + ValueError, + "^Whisper cannot return `char` timestamps, only word level or segment level timestamps. " + "Use `return_timestamps='word'` or `return_timestamps=True` respectively.$", + ): + pipe = pipeline( + task="automatic-speech-recognition", + model=model, + feature_extractor=feature_extractor, + tokenizer=tokenizer, + chunk_length_s=8, + stride_length_s=1, + return_timestamps="char", + ) + + _ = pipe(dummy_speech) + + @require_torch + @slow + def test_torch_whisper(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="openai/whisper-tiny", + framework="pt", + ) + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + output = speech_recognizer(filename) + self.assertEqual(output, {"text": " A man said to the universe, Sir, I exist."}) + + output = speech_recognizer([filename], chunk_length_s=5, batch_size=4) + self.assertEqual(output, [{"text": " A man said to the universe, Sir, I exist."}]) + + @slow + def test_find_longest_common_subsequence(self): + max_source_positions = 1500 + processor = AutoProcessor.from_pretrained("openai/whisper-tiny") + + previous_sequence = [[51492, 406, 3163, 1953, 466, 13, 51612, 51612]] + self.assertEqual( + processor.decode(previous_sequence[0], output_offsets=True), + { + "text": " not worth thinking about.", + "offsets": [{"text": " not worth thinking about.", "timestamp": (22.56, 24.96)}], + }, + ) + + # Merge when the previous sequence is a suffix of the next sequence + # fmt: off + next_sequences_1 = [ + [50364, 295, 6177, 3391, 11, 19817, 3337, 507, 307, 406, 3163, 1953, 466, 13, 50614, 50614, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 50834, 50257] + ] + # fmt: on + self.assertEqual( + processor.decode(next_sequences_1[0], output_offsets=True), + { + "text": ( + " of spectators, retrievality is not worth thinking about. His instant panic was followed by a" + " small, sharp blow high on his chest.<|endoftext|>" + ), + "offsets": [ + {"text": " of spectators, retrievality is not worth thinking about.", "timestamp": (0.0, 5.0)}, + { + "text": " His instant panic was followed by a small, sharp blow high on his chest.", + "timestamp": (5.0, 9.4), + }, + ], + }, + ) + merge = _find_timestamp_sequence( + [[previous_sequence, (480_000, 0, 0)], [next_sequences_1, (480_000, 120_000, 0)]], + processor.tokenizer, + processor.feature_extractor, + max_source_positions, + ) + + # fmt: off + self.assertEqual( + merge, + [51492, 406, 3163, 1953, 466, 13, 51739, 51739, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 51959], + ) + # fmt: on + self.assertEqual( + processor.decode(merge, output_offsets=True), + { + "text": ( + " not worth thinking about. His instant panic was followed by a small, sharp blow high on his" + " chest." + ), + "offsets": [ + {"text": " not worth thinking about.", "timestamp": (22.56, 27.5)}, + { + "text": " His instant panic was followed by a small, sharp blow high on his chest.", + "timestamp": (27.5, 31.900000000000002), + }, + ], + }, + ) + + # Merge when the sequence is in the middle of the 1st next sequence + # fmt: off + next_sequences_2 = [ + [50364, 295, 6177, 3391, 11, 19817, 3337, 507, 307, 406, 3163, 1953, 466, 13, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 50834, 50257] + ] + # fmt: on + # {'text': ' of spectators, retrievality is not worth thinking about. His instant panic was followed by a small, sharp blow high on his chest.','timestamp': (0.0, 9.4)} + merge = _find_timestamp_sequence( + [[previous_sequence, (480_000, 0, 0)], [next_sequences_2, (480_000, 120_000, 0)]], + processor.tokenizer, + processor.feature_extractor, + max_source_positions, + ) + # fmt: off + self.assertEqual( + merge, + [51492, 406, 3163, 1953, 466, 13, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 51959], + ) + # fmt: on + self.assertEqual( + processor.decode(merge, output_offsets=True), + { + "text": ( + " not worth thinking about. His instant panic was followed by a small, sharp blow high on his" + " chest." + ), + "offsets": [ + { + "text": ( + " not worth thinking about. His instant panic was followed by a small, sharp blow high on" + " his chest." + ), + "timestamp": (22.56, 31.900000000000002), + }, + ], + }, + ) + + # Merge when the previous sequence is not included in the current sequence + next_sequences_3 = [[50364, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 50584, 50257]] # fmt: skip + # {'text': ' His instant panic was followed by a small, sharp blow high on his chest.','timestamp': (0.0, 9.4)} + merge = _find_timestamp_sequence( + [[previous_sequence, (480_000, 0, 0)], [next_sequences_3, (480_000, 120_000, 0)]], + processor.tokenizer, + processor.feature_extractor, + max_source_positions, + ) + self.assertEqual( + merge, + [51492, 406, 3163, 1953, 466, 13, 51612, 51612, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 51832], + ) # fmt: skip + self.assertEqual( + processor.decode(merge, output_offsets=True), + { + "text": ( + " not worth thinking about. His instant panic was followed by a small, sharp blow high on his" + " chest." + ), + "offsets": [ + {"text": " not worth thinking about.", "timestamp": (22.56, 24.96)}, + { + "text": " His instant panic was followed by a small, sharp blow high on his chest.", + "timestamp": (24.96, 29.36), + }, + ], + }, + ) + # last case is when the sequence is not in the first next predicted start and end of timestamp + next_sequences_3 = [ + [50364, 2812, 9836, 14783, 390, 406, 3163, 1953, 466, 13, 50634, 50634, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 50934] + ] # fmt: skip + merge = _find_timestamp_sequence( + [[previous_sequence, (480_000, 0, 0)], [next_sequences_3, (480_000, 167_000, 0)]], + processor.tokenizer, + processor.feature_extractor, + max_source_positions, + ) + self.assertEqual( + merge, + [51492, 406, 3163, 1953, 466, 13, 51612, 51612, 2812, 9836, 14783, 390, 6263, 538, 257, 1359, 11, 8199, 6327, 1090, 322, 702, 7443, 13, 51912] + ) # fmt: skip + self.assertEqual( + processor.decode(merge, output_offsets=True), + { + "text": ( + " not worth thinking about. His instant panic was followed by a small, sharp blow high on his" + " chest." + ), + "offsets": [ + {"text": " not worth thinking about.", "timestamp": (22.56, 24.96)}, + { + "text": " His instant panic was followed by a small, sharp blow high on his chest.", + "timestamp": (24.96, 30.96), + }, + ], + }, + ) + + @slow + @require_torch + def test_whisper_timestamp_prediction(self): + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + array = np.concatenate( + [ds[40]["audio"]["array"], ds[41]["audio"]["array"], ds[42]["audio"]["array"], ds[43]["audio"]["array"]] + ) + pipe = pipeline( + model="openai/whisper-small", + return_timestamps=True, + ) + + output = pipe(ds[40]["audio"]) + self.assertDictEqual( + output, + { + "text": " A man said to the universe, Sir, I exist.", + "chunks": [{"text": " A man said to the universe, Sir, I exist.", "timestamp": (0.0, 4.26)}], + }, + ) + + output = pipe(array, chunk_length_s=10) + self.assertDictEqual( + nested_simplify(output), + { + "chunks": [ + {"text": " A man said to the universe, Sir, I exist.", "timestamp": (0.0, 5.5)}, + { + "text": ( + " Sweat covered Brion's body, trickling into the " + "tight-loan cloth that was the only garment he wore, the " + "cut" + ), + "timestamp": (5.5, 11.95), + }, + { + "text": ( + " on his chest still dripping blood, the ache of his " + "overstrained eyes, even the soaring arena around him " + "with" + ), + "timestamp": (11.95, 19.61), + }, + { + "text": " the thousands of spectators, retrievality is not worth thinking about.", + "timestamp": (19.61, 25.0), + }, + { + "text": " His instant panic was followed by a small, sharp blow high on his chest.", + "timestamp": (25.0, 29.4), + }, + ], + "text": ( + " A man said to the universe, Sir, I exist. Sweat covered Brion's " + "body, trickling into the tight-loan cloth that was the only garment " + "he wore, the cut on his chest still dripping blood, the ache of his " + "overstrained eyes, even the soaring arena around him with the " + "thousands of spectators, retrievality is not worth thinking about. " + "His instant panic was followed by a small, sharp blow high on his " + "chest." + ), + }, + ) + + output = pipe(array) + self.assertDictEqual( + output, + { + "chunks": [ + {"text": " A man said to the universe, Sir, I exist.", "timestamp": (0.0, 5.5)}, + { + "text": ( + " Sweat covered Brion's body, trickling into the " + "tight-loan cloth that was the only garment" + ), + "timestamp": (5.5, 10.18), + }, + {"text": " he wore.", "timestamp": (10.18, 11.68)}, + {"text": " The cut on his chest still dripping blood.", "timestamp": (11.68, 14.92)}, + {"text": " The ache of his overstrained eyes.", "timestamp": (14.92, 17.6)}, + { + "text": ( + " Even the soaring arena around him with the thousands of spectators were trivialities" + ), + "timestamp": (17.6, 22.56), + }, + {"text": " not worth thinking about.", "timestamp": (22.56, 24.96)}, + ], + "text": ( + " A man said to the universe, Sir, I exist. Sweat covered Brion's " + "body, trickling into the tight-loan cloth that was the only garment " + "he wore. The cut on his chest still dripping blood. The ache of his " + "overstrained eyes. Even the soaring arena around him with the " + "thousands of spectators were trivialities not worth thinking about." + ), + }, + ) + + @require_torch + @slow + def test_torch_speech_encoder_decoder(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="facebook/s2t-wav2vec2-large-en-de", + feature_extractor="facebook/s2t-wav2vec2-large-en-de", + framework="pt", + ) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + output = speech_recognizer(filename) + self.assertEqual(output, {"text": 'Ein Mann sagte zum Universum : " Sir, ich existiert! "'}) + + @slow + @require_torch + def test_simple_wav2vec2(self): + model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") + tokenizer = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h") + feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h") + + asr = AutomaticSpeechRecognitionPipeline(model=model, tokenizer=tokenizer, feature_extractor=feature_extractor) + + waveform = np.tile(np.arange(1000, dtype=np.float32), 34) + output = asr(waveform) + self.assertEqual(output, {"text": ""}) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + output = asr(filename) + self.assertEqual(output, {"text": "A MAN SAID TO THE UNIVERSE SIR I EXIST"}) + + filename = ds[40]["file"] + with open(filename, "rb") as f: + data = f.read() + output = asr(data) + self.assertEqual(output, {"text": "A MAN SAID TO THE UNIVERSE SIR I EXIST"}) + + @slow + @require_torch + @require_torchaudio + def test_simple_s2t(self): + model = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-mustc-en-it-st") + tokenizer = AutoTokenizer.from_pretrained("facebook/s2t-small-mustc-en-it-st") + feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/s2t-small-mustc-en-it-st") + + asr = AutomaticSpeechRecognitionPipeline(model=model, tokenizer=tokenizer, feature_extractor=feature_extractor) + + waveform = np.tile(np.arange(1000, dtype=np.float32), 34) + + output = asr(waveform) + self.assertEqual(output, {"text": "(Applausi)"}) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + output = asr(filename) + self.assertEqual(output, {"text": "Un uomo disse all'universo: \"Signore, io esisto."}) + + filename = ds[40]["file"] + with open(filename, "rb") as f: + data = f.read() + output = asr(data) + self.assertEqual(output, {"text": "Un uomo disse all'universo: \"Signore, io esisto."}) + + @slow + @require_torch + @require_torchaudio + def test_simple_whisper_asr(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="openai/whisper-tiny.en", + framework="pt", + ) + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + filename = ds[0]["file"] + output = speech_recognizer(filename) + self.assertEqual( + output, + {"text": " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel."}, + ) + output = speech_recognizer(filename, return_timestamps=True) + self.assertEqual( + output, + { + "text": " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.", + "chunks": [ + { + "text": ( + " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel." + ), + "timestamp": (0.0, 5.44), + } + ], + }, + ) + speech_recognizer.model.generation_config.alignment_heads = [[2, 2], [3, 0], [3, 2], [3, 3], [3, 4], [3, 5]] + output = speech_recognizer(filename, return_timestamps="word") + # fmt: off + self.assertEqual( + output, + { + 'text': ' Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.', + 'chunks': [ + {'text': ' Mr.', 'timestamp': (0.38, 1.04)}, + {'text': ' Quilter', 'timestamp': (1.04, 1.18)}, + {'text': ' is', 'timestamp': (1.18, 1.44)}, + {'text': ' the', 'timestamp': (1.44, 1.58)}, + {'text': ' apostle', 'timestamp': (1.58, 1.98)}, + {'text': ' of', 'timestamp': (1.98, 2.32)}, + {'text': ' the', 'timestamp': (2.32, 2.46)}, + {'text': ' middle', 'timestamp': (2.46, 2.56)}, + {'text': ' classes,', 'timestamp': (2.56, 3.4)}, + {'text': ' and', 'timestamp': (3.4, 3.54)}, + {'text': ' we', 'timestamp': (3.54, 3.62)}, + {'text': ' are', 'timestamp': (3.62, 3.72)}, + {'text': ' glad', 'timestamp': (3.72, 4.0)}, + {'text': ' to', 'timestamp': (4.0, 4.26)}, + {'text': ' welcome', 'timestamp': (4.26, 4.56)}, + {'text': ' his', 'timestamp': (4.56, 4.92)}, + {'text': ' gospel.', 'timestamp': (4.92, 5.84)} + ] + } + ) + # fmt: on + + # Whisper can only predict segment level timestamps or word level, not character level + with self.assertRaisesRegex( + ValueError, + "^Whisper cannot return `char` timestamps, only word level or segment level timestamps. " + "Use `return_timestamps='word'` or `return_timestamps=True` respectively.$", + ): + _ = speech_recognizer(filename, return_timestamps="char") + + @slow + @require_torch + @require_torchaudio + def test_simple_whisper_translation(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="openai/whisper-large", + framework="pt", + ) + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + output = speech_recognizer(filename) + self.assertEqual(output, {"text": " A man said to the universe, Sir, I exist."}) + + model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large") + tokenizer = AutoTokenizer.from_pretrained("openai/whisper-large") + feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-large") + + speech_recognizer_2 = AutomaticSpeechRecognitionPipeline( + model=model, tokenizer=tokenizer, feature_extractor=feature_extractor + ) + output_2 = speech_recognizer_2(filename) + self.assertEqual(output, output_2) + + # either use generate_kwargs or set the model's generation_config + # model.generation_config.task = "transcribe" + # model.generation_config.lang = "<|it|>" + speech_translator = AutomaticSpeechRecognitionPipeline( + model=model, + tokenizer=tokenizer, + feature_extractor=feature_extractor, + generate_kwargs={"task": "transcribe", "language": "<|it|>"}, + ) + output_3 = speech_translator(filename) + self.assertEqual(output_3, {"text": " Un uomo ha detto all'universo, Sir, esiste."}) + + @slow + @require_torch + def test_whisper_language(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="openai/whisper-tiny.en", + framework="pt", + ) + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + filename = ds[0]["file"] + + # 1. English-only model compatible with no language argument + output = speech_recognizer(filename) + self.assertEqual( + output, + {"text": " Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel."}, + ) + + # 2. English-only Whisper does not accept the language argument + with self.assertRaisesRegex( + ValueError, + "Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, " + "pass `is_multilingual=True` to generate, or update the generation config.", + ): + _ = speech_recognizer(filename, generate_kwargs={"language": "en"}) + + # 3. Multilingual model accepts language argument + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="openai/whisper-tiny", + framework="pt", + ) + output = speech_recognizer(filename, generate_kwargs={"language": "en"}) + self.assertEqual( + output, + {"text": " Mr. Quilter is the apostle of the middle classes and we are glad to welcome his gospel."}, + ) + + @slow + @require_torch + @require_torchaudio + def test_xls_r_to_en(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="facebook/wav2vec2-xls-r-1b-21-to-en", + feature_extractor="facebook/wav2vec2-xls-r-1b-21-to-en", + framework="pt", + ) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + output = speech_recognizer(filename) + self.assertEqual(output, {"text": "A man said to the universe: “Sir, I exist."}) + + @slow + @require_torch + @require_torchaudio + def test_xls_r_from_en(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="facebook/wav2vec2-xls-r-1b-en-to-15", + feature_extractor="facebook/wav2vec2-xls-r-1b-en-to-15", + framework="pt", + ) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + output = speech_recognizer(filename) + self.assertEqual(output, {"text": "Ein Mann sagte zu dem Universum, Sir, ich bin da."}) + + @slow + @require_torch + @require_torchaudio + def test_speech_to_text_leveraged(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="patrickvonplaten/wav2vec2-2-bart-base", + feature_extractor="patrickvonplaten/wav2vec2-2-bart-base", + tokenizer=AutoTokenizer.from_pretrained("patrickvonplaten/wav2vec2-2-bart-base"), + framework="pt", + ) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + filename = ds[40]["file"] + + output = speech_recognizer(filename) + self.assertEqual(output, {"text": "a man said to the universe sir i exist"}) + + @slow + @require_torch_accelerator + def test_wav2vec2_conformer_float16(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="facebook/wav2vec2-conformer-rope-large-960h-ft", + device=torch_device, + torch_dtype=torch.float16, + framework="pt", + ) + + dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + sample = dataset[0]["audio"] + + output = speech_recognizer(sample) + self.assertEqual( + output, + {"text": "MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL"}, + ) + + @require_torch + def test_chunking_fast(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="hf-internal-testing/tiny-random-wav2vec2", + chunk_length_s=10.0, + ) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + audio = ds[40]["audio"]["array"] + + n_repeats = 2 + audio_tiled = np.tile(audio, n_repeats) + output = speech_recognizer([audio_tiled], batch_size=2) + self.assertEqual(output, [{"text": ANY(str)}]) + self.assertEqual(output[0]["text"][:6], "ZBT ZC") + + @require_torch + def test_return_timestamps_ctc_fast(self): + speech_recognizer = pipeline( + task="automatic-speech-recognition", + model="hf-internal-testing/tiny-random-wav2vec2", + ) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + # Take short audio to keep the test readable + audio = ds[40]["audio"]["array"][:800] + + output = speech_recognizer(audio, return_timestamps="char") + self.assertEqual( + output, + { + "text": "ZBT ZX G", + "chunks": [ + {"text": " ", "timestamp": (0.0, 0.012)}, + {"text": "Z", "timestamp": (0.012, 0.016)}, + {"text": "B", "timestamp": (0.016, 0.02)}, + {"text": "T", "timestamp": (0.02, 0.024)}, + {"text": " ", "timestamp": (0.024, 0.028)}, + {"text": "Z", "timestamp": (0.028, 0.032)}, + {"text": "X", "timestamp": (0.032, 0.036)}, + {"text": " ", "timestamp": (0.036, 0.04)}, + {"text": "G", "timestamp": (0.04, 0.044)}, + ], + }, + ) + + output = speech_recognizer(audio, return_timestamps="word") + self.assertEqual( + output, + { + "text": "ZBT ZX G", + "chunks": [ + {"text": "ZBT", "timestamp": (0.012, 0.024)}, + {"text": "ZX", "timestamp": (0.028, 0.036)}, + {"text": "G", "timestamp": (0.04, 0.044)}, + ], + }, + ) + + @require_torch + @require_pyctcdecode + def test_chunking_fast_with_lm(self): + speech_recognizer = pipeline( + model="hf-internal-testing/processor_with_lm", + chunk_length_s=10.0, + ) + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + audio = ds[40]["audio"]["array"] + + n_repeats = 2 + audio_tiled = np.tile(audio, n_repeats) + # Batch_size = 1 + output1 = speech_recognizer([audio_tiled], batch_size=1) + self.assertEqual(output1, [{"text": ANY(str)}]) + self.assertEqual(output1[0]["text"][:6], " 0: + models_are_equal = False + + return models_are_equal + + def check_models_equal_tf(self, model1, model2): + models_are_equal = True + for model1_p, model2_p in zip(model1.weights, model2.weights): + if np.abs(model1_p.numpy() - model2_p.numpy()).sum() > 1e-5: + models_are_equal = False + + return models_are_equal + + +class CustomPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "maybe_arg" in kwargs: + preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"] + return preprocess_kwargs, {}, {} + + def preprocess(self, text, maybe_arg=2): + input_ids = self.tokenizer(text, return_tensors="pt") + return input_ids + + def _forward(self, model_inputs): + outputs = self.model(**model_inputs) + return outputs + + def postprocess(self, model_outputs): + return model_outputs["logits"].softmax(-1).numpy() + + +@is_pipeline_test +class CustomPipelineTest(unittest.TestCase): + def test_warning_logs(self): + transformers_logging.set_verbosity_debug() + logger_ = transformers_logging.get_logger("transformers.pipelines.base") + + alias = "text-classification" + # Get the original task, so we can restore it at the end. + # (otherwise the subsequential tests in `TextClassificationPipelineTests` will fail) + _, original_task, _ = PIPELINE_REGISTRY.check_task(alias) + + try: + with CaptureLogger(logger_) as cm: + PIPELINE_REGISTRY.register_pipeline(alias, PairClassificationPipeline) + self.assertIn(f"{alias} is already registered", cm.out) + finally: + # restore + PIPELINE_REGISTRY.supported_tasks[alias] = original_task + + def test_register_pipeline(self): + PIPELINE_REGISTRY.register_pipeline( + "custom-text-classification", + pipeline_class=PairClassificationPipeline, + pt_model=AutoModelForSequenceClassification if is_torch_available() else None, + tf_model=TFAutoModelForSequenceClassification if is_tf_available() else None, + default={"pt": "hf-internal-testing/tiny-random-distilbert"}, + type="text", + ) + assert "custom-text-classification" in PIPELINE_REGISTRY.get_supported_tasks() + + _, task_def, _ = PIPELINE_REGISTRY.check_task("custom-text-classification") + self.assertEqual(task_def["pt"], (AutoModelForSequenceClassification,) if is_torch_available() else ()) + self.assertEqual(task_def["tf"], (TFAutoModelForSequenceClassification,) if is_tf_available() else ()) + self.assertEqual(task_def["type"], "text") + self.assertEqual(task_def["impl"], PairClassificationPipeline) + self.assertEqual(task_def["default"], {"model": {"pt": "hf-internal-testing/tiny-random-distilbert"}}) + + # Clean registry for next tests. + del PIPELINE_REGISTRY.supported_tasks["custom-text-classification"] + + @require_torch_or_tf + def test_dynamic_pipeline(self): + PIPELINE_REGISTRY.register_pipeline( + "pair-classification", + pipeline_class=PairClassificationPipeline, + pt_model=AutoModelForSequenceClassification if is_torch_available() else None, + tf_model=TFAutoModelForSequenceClassification if is_tf_available() else None, + ) + + classifier = pipeline("pair-classification", model="hf-internal-testing/tiny-random-bert") + + # Clean registry as we won't need the pipeline to be in it for the rest to work. + del PIPELINE_REGISTRY.supported_tasks["pair-classification"] + + with tempfile.TemporaryDirectory() as tmp_dir: + classifier.save_pretrained(tmp_dir) + # checks + self.assertDictEqual( + classifier.model.config.custom_pipelines, + { + "pair-classification": { + "impl": "custom_pipeline.PairClassificationPipeline", + "pt": ("AutoModelForSequenceClassification",) if is_torch_available() else (), + "tf": ("TFAutoModelForSequenceClassification",) if is_tf_available() else (), + } + }, + ) + # Fails if the user forget to pass along `trust_remote_code=True` + with self.assertRaises(ValueError): + _ = pipeline(model=tmp_dir) + + new_classifier = pipeline(model=tmp_dir, trust_remote_code=True) + # Using trust_remote_code=False forces the traditional pipeline tag + old_classifier = pipeline("text-classification", model=tmp_dir, trust_remote_code=False) + # Can't make an isinstance check because the new_classifier is from the PairClassificationPipeline class of a + # dynamic module + self.assertEqual(new_classifier.__class__.__name__, "PairClassificationPipeline") + self.assertEqual(new_classifier.task, "pair-classification") + results = new_classifier("I hate you", second_text="I love you") + self.assertDictEqual( + nested_simplify(results), + {"label": "LABEL_0", "score": 0.505, "logits": [-0.003, -0.024]}, + ) + + self.assertEqual(old_classifier.__class__.__name__, "TextClassificationPipeline") + self.assertEqual(old_classifier.task, "text-classification") + results = old_classifier("I hate you", text_pair="I love you") + self.assertListEqual( + nested_simplify(results), + [{"label": "LABEL_0", "score": 0.505}], + ) + + @require_torch_or_tf + def test_cached_pipeline_has_minimum_calls_to_head(self): + # Make sure we have cached the pipeline. + _ = pipeline("text-classification", model="hf-internal-testing/tiny-random-bert") + with RequestCounter() as counter: + _ = pipeline("text-classification", model="hf-internal-testing/tiny-random-bert") + self.assertEqual(counter["GET"], 0) + self.assertEqual(counter["HEAD"], 1) + self.assertEqual(counter.total_calls, 1) + + @require_torch + def test_chunk_pipeline_batching_single_file(self): + # Make sure we have cached the pipeline. + pipe = pipeline(model="hf-internal-testing/tiny-random-Wav2Vec2ForCTC") + ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") + audio = ds[40]["audio"]["array"] + + pipe = pipeline(model="hf-internal-testing/tiny-random-Wav2Vec2ForCTC") + # For some reason scoping doesn't work if not using `self.` + self.COUNT = 0 + forward = pipe.model.forward + + def new_forward(*args, **kwargs): + self.COUNT += 1 + return forward(*args, **kwargs) + + pipe.model.forward = new_forward + + for out in pipe(audio, return_timestamps="char", chunk_length_s=3, stride_length_s=[1, 1], batch_size=1024): + pass + + self.assertEqual(self.COUNT, 1) + + +@require_torch +@is_staging_test +class DynamicPipelineTester(unittest.TestCase): + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "I", "love", "hate", "you"] + + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + try: + delete_repo(token=cls._token, repo_id="test-dynamic-pipeline") + except HTTPError: + pass + + def test_push_to_hub_dynamic_pipeline(self): + from transformers import BertConfig, BertForSequenceClassification, BertTokenizer + + PIPELINE_REGISTRY.register_pipeline( + "pair-classification", + pipeline_class=PairClassificationPipeline, + pt_model=AutoModelForSequenceClassification, + ) + + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertForSequenceClassification(config).eval() + + with tempfile.TemporaryDirectory() as tmp_dir: + create_repo(f"{USER}/test-dynamic-pipeline", token=self._token) + repo = Repository(tmp_dir, clone_from=f"{USER}/test-dynamic-pipeline", token=self._token) + + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = BertTokenizer(vocab_file) + + classifier = pipeline("pair-classification", model=model, tokenizer=tokenizer) + + # Clean registry as we won't need the pipeline to be in it for the rest to work. + del PIPELINE_REGISTRY.supported_tasks["pair-classification"] + + classifier.save_pretrained(tmp_dir) + # checks + self.assertDictEqual( + classifier.model.config.custom_pipelines, + { + "pair-classification": { + "impl": "custom_pipeline.PairClassificationPipeline", + "pt": ("AutoModelForSequenceClassification",), + "tf": (), + } + }, + ) + + repo.push_to_hub() + + # Fails if the user forget to pass along `trust_remote_code=True` + with self.assertRaises(ValueError): + _ = pipeline(model=f"{USER}/test-dynamic-pipeline") + + new_classifier = pipeline(model=f"{USER}/test-dynamic-pipeline", trust_remote_code=True) + # Can't make an isinstance check because the new_classifier is from the PairClassificationPipeline class of a + # dynamic module + self.assertEqual(new_classifier.__class__.__name__, "PairClassificationPipeline") + + results = classifier("I hate you", second_text="I love you") + new_results = new_classifier("I hate you", second_text="I love you") + self.assertDictEqual(nested_simplify(results), nested_simplify(new_results)) + + # Using trust_remote_code=False forces the traditional pipeline tag + old_classifier = pipeline( + "text-classification", model=f"{USER}/test-dynamic-pipeline", trust_remote_code=False + ) + self.assertEqual(old_classifier.__class__.__name__, "TextClassificationPipeline") + self.assertEqual(old_classifier.task, "text-classification") + new_results = old_classifier("I hate you", text_pair="I love you") + self.assertListEqual( + nested_simplify([{"label": results["label"], "score": results["score"]}]), nested_simplify(new_results) + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_conversational.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_conversational.py new file mode 100644 index 0000000000000000000000000000000000000000..e80d6a646f99066d427fa2107d3155a23b47e879 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_conversational.py @@ -0,0 +1,439 @@ +# 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 gc +import unittest + +from transformers import ( + MODEL_FOR_CAUSAL_LM_MAPPING, + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + AutoTokenizer, + BlenderbotSmallForConditionalGeneration, + BlenderbotSmallTokenizer, + Conversation, + ConversationalPipeline, + TFAutoModelForCausalLM, + pipeline, +) +from transformers.testing_utils import ( + backend_empty_cache, + is_pipeline_test, + is_torch_available, + require_tf, + require_torch, + slow, + torch_device, +) + +from .test_pipelines_common import ANY + + +@is_pipeline_test +class ConversationalPipelineTests(unittest.TestCase): + def tearDown(self): + super().tearDown() + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + if is_torch_available(): + backend_empty_cache(torch_device) + + model_mapping = dict( + list(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()) + if MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + else [] + list(MODEL_FOR_CAUSAL_LM_MAPPING.items()) + if MODEL_FOR_CAUSAL_LM_MAPPING + else [] + ) + tf_model_mapping = dict( + list(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()) + if TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + else [] + list(TF_MODEL_FOR_CAUSAL_LM_MAPPING.items()) + if TF_MODEL_FOR_CAUSAL_LM_MAPPING + else [] + ) + + def get_test_pipeline(self, model, tokenizer, processor): + conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer) + return conversation_agent, [Conversation("Hi there!")] + + def run_pipeline_test(self, conversation_agent, _): + # Simple + outputs = conversation_agent(Conversation("Hi there!"), max_new_tokens=5) + self.assertEqual( + outputs, + Conversation([{"role": "user", "content": "Hi there!"}, {"role": "assistant", "content": ANY(str)}]), + ) + + # Single list + outputs = conversation_agent([Conversation("Hi there!")], max_new_tokens=5) + self.assertEqual( + outputs, + Conversation([{"role": "user", "content": "Hi there!"}, {"role": "assistant", "content": ANY(str)}]), + ) + + # Batch + conversation_1 = Conversation("Going to the movies tonight - any suggestions?") + conversation_2 = Conversation("What's the last book you have read?") + self.assertEqual(len(conversation_1), 1) + self.assertEqual(len(conversation_2), 1) + + outputs = conversation_agent([conversation_1, conversation_2], max_new_tokens=5) + self.assertEqual(outputs, [conversation_1, conversation_2]) + self.assertEqual( + outputs, + [ + Conversation( + [ + {"role": "user", "content": "Going to the movies tonight - any suggestions?"}, + {"role": "assistant", "content": ANY(str)}, + ], + ), + Conversation( + [ + {"role": "user", "content": "What's the last book you have read?"}, + {"role": "assistant", "content": ANY(str)}, + ] + ), + ], + ) + + # One conversation with history + conversation_2.add_message({"role": "user", "content": "Why do you recommend it?"}) + outputs = conversation_agent(conversation_2, max_new_tokens=5) + self.assertEqual(outputs, conversation_2) + self.assertEqual( + outputs, + Conversation( + [ + {"role": "user", "content": "What's the last book you have read?"}, + {"role": "assistant", "content": ANY(str)}, + {"role": "user", "content": "Why do you recommend it?"}, + {"role": "assistant", "content": ANY(str)}, + ] + ), + ) + + @require_torch + @slow + def test_integration_torch_conversation(self): + # When + conversation_agent = pipeline(task="conversational", device=torch_device) + conversation_1 = Conversation("Going to the movies tonight - any suggestions?") + conversation_2 = Conversation("What's the last book you have read?") + # Then + self.assertEqual(len(conversation_1.past_user_inputs), 0) + self.assertEqual(len(conversation_2.past_user_inputs), 0) + # When + result = conversation_agent([conversation_1, conversation_2], do_sample=False, max_length=1000) + # Then + self.assertEqual(result, [conversation_1, conversation_2]) + self.assertEqual(len(result[0].past_user_inputs), 1) + self.assertEqual(len(result[1].past_user_inputs), 1) + self.assertEqual(len(result[0].generated_responses), 1) + self.assertEqual(len(result[1].generated_responses), 1) + self.assertEqual(result[0].past_user_inputs[0], "Going to the movies tonight - any suggestions?") + self.assertEqual(result[0].generated_responses[0], "The Big Lebowski") + self.assertEqual(result[1].past_user_inputs[0], "What's the last book you have read?") + self.assertEqual(result[1].generated_responses[0], "The Last Question") + # When + conversation_2.add_user_input("Why do you recommend it?") + result = conversation_agent(conversation_2, do_sample=False, max_length=1000) + # Then + self.assertEqual(result, conversation_2) + self.assertEqual(len(result.past_user_inputs), 2) + self.assertEqual(len(result.generated_responses), 2) + self.assertEqual(result.past_user_inputs[1], "Why do you recommend it?") + self.assertEqual(result.generated_responses[1], "It's a good book.") + + @require_torch + @slow + def test_integration_torch_conversation_truncated_history(self): + # When + conversation_agent = pipeline(task="conversational", min_length_for_response=24, device=torch_device) + conversation_1 = Conversation("Going to the movies tonight - any suggestions?") + # Then + self.assertEqual(len(conversation_1.past_user_inputs), 0) + # When + result = conversation_agent(conversation_1, do_sample=False, max_length=36) + # Then + self.assertEqual(result, conversation_1) + self.assertEqual(len(result.past_user_inputs), 1) + self.assertEqual(len(result.generated_responses), 1) + self.assertEqual(result.past_user_inputs[0], "Going to the movies tonight - any suggestions?") + self.assertEqual(result.generated_responses[0], "The Big Lebowski") + # When + conversation_1.add_user_input("Is it an action movie?") + result = conversation_agent(conversation_1, do_sample=False, max_length=36) + # Then + self.assertEqual(result, conversation_1) + self.assertEqual(len(result.past_user_inputs), 2) + self.assertEqual(len(result.generated_responses), 2) + self.assertEqual(result.past_user_inputs[1], "Is it an action movie?") + self.assertEqual(result.generated_responses[1], "It's a comedy.") + + @require_torch + def test_small_model_pt(self): + tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small") + model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small") + conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer) + conversation = Conversation("hello") + output = conversation_agent(conversation) + self.assertEqual(output, Conversation(past_user_inputs=["hello"], generated_responses=["Hi"])) + + @require_tf + def test_small_model_tf(self): + tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small") + model = TFAutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small") + conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer) + conversation = Conversation("hello") + output = conversation_agent(conversation) + self.assertEqual(output, Conversation(past_user_inputs=["hello"], generated_responses=["Hi"])) + + @require_torch + @slow + def test_integration_torch_conversation_dialogpt_input_ids(self): + tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small") + model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small") + conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer) + + conversation_1 = Conversation("hello") + inputs = conversation_agent.preprocess(conversation_1) + self.assertEqual(inputs["input_ids"].tolist(), [[31373, 50256]]) + + conversation_2 = Conversation("how are you ?", past_user_inputs=["hello"], generated_responses=["Hi there!"]) + inputs = conversation_agent.preprocess(conversation_2) + self.assertEqual( + inputs["input_ids"].tolist(), [[31373, 50256, 17250, 612, 0, 50256, 4919, 389, 345, 5633, 50256]] + ) + + @unittest.skip("Model is curently gated") + @require_torch + @slow + def test_integration_torch_conversation_llama2_input_ids(self): + tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf", use_default_system_prompt=True) + + conversation = Conversation( + "What is so great about #1?", + past_user_inputs=["I am going to Paris, what should I see?"], + generated_responses=[ + """\ +Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris: + +1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city. +2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa. +3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows. + +These are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world.""" + ], + ) + inputs = tokenizer._build_conversation_input_ids(conversation) + EXPECTED_INPUTS_IDS = [ 1, 518, 25580, 29962, 3532, 14816, 29903, 6778, 13, 3492, 526, 263, 8444, 29892, 3390, 1319, 322, 15993, 20255, 29889, 29849, 1234, 408, 1371, 3730, 408, 1950, 29892, 1550, 1641, 9109, 29889, 29871, 3575, 6089, 881, 451, 3160, 738, 10311, 1319, 29892, 443, 621, 936, 29892, 11021, 391, 29892, 7916, 391, 29892, 304, 27375, 29892, 18215, 29892, 470, 27302, 2793, 29889, 3529, 9801, 393, 596, 20890, 526, 5374, 635, 443, 5365, 1463, 322, 6374, 297, 5469, 29889, 13, 13, 3644, 263, 1139, 947, 451, 1207, 738, 4060, 29892, 470, 338, 451, 2114, 1474, 16165, 261, 296, 29892, 5649, 2020, 2012, 310, 22862, 1554, 451, 1959, 29889, 960, 366, 1016, 29915, 29873, 1073, 278, 1234, 304, 263, 1139, 29892, 3113, 1016, 29915, 29873, 6232, 2089, 2472, 29889, 13, 29966, 829, 14816, 29903, 6778, 13, 13, 29902, 626, 2675, 304, 3681, 29892, 825, 881, 306, 1074, 29973, 518, 29914, 25580, 29962, 3681, 29892, 278, 7483, 310, 3444, 29892, 338, 2998, 363, 967, 380, 27389, 11258, 29892, 1616, 19133, 29879, 29892, 15839, 2982, 22848, 29892, 322, 6017, 7716, 25005, 29889, 2266, 526, 777, 310, 278, 2246, 19650, 1953, 304, 1074, 297, 3681, 29901, 13, 13, 29896, 29889, 450, 382, 2593, 295, 23615, 29901, 450, 9849, 293, 382, 2593, 295, 23615, 338, 697, 310, 278, 1556, 5936, 13902, 2982, 22848, 297, 278, 3186, 322, 16688, 2078, 271, 400, 5086, 8386, 310, 278, 4272, 29889, 13, 29906, 29889, 450, 4562, 12675, 6838, 29901, 450, 4562, 12675, 338, 697, 310, 278, 3186, 29915, 29879, 10150, 322, 1556, 13834, 19133, 29879, 29892, 27261, 385, 21210, 573, 4333, 310, 1616, 322, 24238, 29879, 29892, 3704, 278, 2598, 29874, 29420, 29889, 13, 29941, 29889, 24337, 29899, 29928, 420, 315, 21471, 29901, 910, 9560, 274, 21471, 338, 697, 310, 278, 1556, 13834, 2982, 22848, 297, 3681, 322, 338, 2998, 363, 967, 22883, 293, 11258, 322, 380, 27389, 380, 7114, 12917, 5417, 29889, 13, 13, 1349, 968, 526, 925, 263, 2846, 310, 278, 1784, 19650, 1953, 393, 3681, 756, 304, 5957, 29889, 2973, 577, 1568, 304, 1074, 322, 437, 29892, 372, 29915, 29879, 694, 4997, 393, 3681, 338, 697, 310, 278, 1556, 5972, 6282, 391, 15422, 800, 297, 278, 3186, 29889, 29871, 2, 1, 518, 25580, 29962, 1724, 338, 577, 2107, 1048, 396, 29896, 29973, 518, 29914, 25580, 29962] # fmt: skip + self.assertEqual(inputs, EXPECTED_INPUTS_IDS) + + model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf") + conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer) + EXPECTED_TEXT = "what topic you want to focus on and create content around it. This will help you stand out from other creators and attract a specific audience.\n\nStep 2: Set Up Your Channel\nCreate your YouTube account and customize your channel with your branding and logo. Make sure your channel name and profile picture are consistent with your niche.\n\nStep 3: Plan Your Content\nDevelop a content strategy that includes the type of content you want to create, how often you will post, and when you will post. Consider creating a content calendar to help you stay organized.\n\nStep 4: Invest in Quality Equipment\nInvest in good quality camera and microphone equipment to ensure your videos look and sound professional. You don't need to break the bank, but investing in good equipment will make a big difference in the quality of your videos.\n\nStep 5: Optimize Your Videos for Search\nUse keywords in your video titles, descriptions, and tags to help people find your videos when they search for topics related to your niche" + conversation = Conversation( + "<>\n Only answer with emojis, and charades\n<>\n\nHow can I build a house in 10 steps?" + ) + result = conversation_agent(conversation) + self.assertEqual(result.generated_responses[-1], EXPECTED_TEXT) + + @require_torch + @slow + def test_integration_torch_conversation_blenderbot_400M_input_ids(self): + tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill") + model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot-400M-distill") + conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer) + + # test1 + conversation_1 = Conversation("hello") + inputs = conversation_agent.preprocess(conversation_1) + self.assertEqual(inputs["input_ids"].tolist(), [[1710, 86, 2]]) + + # test2 + conversation_1 = Conversation( + "I like lasagne.", + past_user_inputs=["hello"], + generated_responses=[ + " Do you like lasagne? It is a traditional Italian dish consisting of a shepherd's pie." + ], + ) + inputs = conversation_agent.preprocess(conversation_1) + self.assertEqual( + inputs["input_ids"].tolist(), + [ + # This should be compared with the same conversation on ParlAI `safe_interactive` demo. + [ + 1710, # hello + 86, + 228, # Double space + 228, + 946, + 304, + 398, + 6881, + 558, + 964, + 38, + 452, + 315, + 265, + 6252, + 452, + 322, + 968, + 6884, + 3146, + 278, + 306, + 265, + 617, + 87, + 388, + 75, + 341, + 286, + 521, + 21, + 228, # Double space + 228, + 281, # I like lasagne. + 398, + 6881, + 558, + 964, + 21, + 2, # EOS + ], + ], + ) + + @require_torch + @slow + def test_integration_torch_conversation_blenderbot_400M(self): + tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill") + model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot-400M-distill") + conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer) + + conversation_1 = Conversation("hello") + result = conversation_agent( + conversation_1, + ) + self.assertEqual( + result.generated_responses[0], + # ParlAI implementation output, we have a different one, but it's our + # second best, you can check by using num_return_sequences=10 + # " Hello! How are you? I'm just getting ready to go to work, how about you?", + " Hello! How are you doing today? I just got back from a walk with my dog.", + ) + + conversation_1 = Conversation("Lasagne hello") + result = conversation_agent(conversation_1, encoder_no_repeat_ngram_size=3) + self.assertEqual( + result.generated_responses[0], + " Do you like lasagne? It is a traditional Italian dish consisting of a shepherd's pie.", + ) + + conversation_1 = Conversation( + "Lasagne hello Lasagne is my favorite Italian dish. Do you like lasagne? I like lasagne." + ) + result = conversation_agent( + conversation_1, + encoder_no_repeat_ngram_size=3, + ) + self.assertEqual( + result.generated_responses[0], + " Me too. I like how it can be topped with vegetables, meats, and condiments.", + ) + + @require_torch + @slow + def test_integration_torch_conversation_encoder_decoder(self): + # When + tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M") + model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot_small-90M") + conversation_agent = ConversationalPipeline(model=model, tokenizer=tokenizer, device=torch_device) + + conversation_1 = Conversation("My name is Sarah and I live in London") + conversation_2 = Conversation("Going to the movies tonight, What movie would you recommend? ") + # Then + self.assertEqual(len(conversation_1.past_user_inputs), 0) + self.assertEqual(len(conversation_2.past_user_inputs), 0) + # When + result = conversation_agent([conversation_1, conversation_2], do_sample=False, max_length=1000) + # Then + self.assertEqual(result, [conversation_1, conversation_2]) + self.assertEqual(len(result[0].past_user_inputs), 1) + self.assertEqual(len(result[1].past_user_inputs), 1) + self.assertEqual(len(result[0].generated_responses), 1) + self.assertEqual(len(result[1].generated_responses), 1) + self.assertEqual(result[0].past_user_inputs[0], "My name is Sarah and I live in London") + self.assertEqual( + result[0].generated_responses[0], + "hi sarah, i live in london as well. do you have any plans for the weekend?", + ) + self.assertEqual( + result[1].past_user_inputs[0], "Going to the movies tonight, What movie would you recommend? " + ) + self.assertEqual( + result[1].generated_responses[0], "i don't know... i'm not really sure. what movie are you going to see?" + ) + # When + conversation_1.add_user_input("Not yet, what about you?") + conversation_2.add_user_input("What's your name?") + result = conversation_agent([conversation_1, conversation_2], do_sample=False, max_length=1000) + # Then + self.assertEqual(result, [conversation_1, conversation_2]) + self.assertEqual(len(result[0].past_user_inputs), 2) + self.assertEqual(len(result[1].past_user_inputs), 2) + self.assertEqual(len(result[0].generated_responses), 2) + self.assertEqual(len(result[1].generated_responses), 2) + self.assertEqual(result[0].past_user_inputs[1], "Not yet, what about you?") + self.assertEqual(result[0].generated_responses[1], "i don't have any plans yet. i'm not sure what to do yet.") + self.assertEqual(result[1].past_user_inputs[1], "What's your name?") + self.assertEqual(result[1].generated_responses[1], "i don't have a name, but i'm going to see a horror movie.") + + @require_torch + @slow + def test_from_pipeline_conversation(self): + model_id = "facebook/blenderbot_small-90M" + + # from model id + conversation_agent_from_model_id = pipeline("conversational", model=model_id, tokenizer=model_id) + + # from model object + model = BlenderbotSmallForConditionalGeneration.from_pretrained(model_id) + tokenizer = BlenderbotSmallTokenizer.from_pretrained(model_id) + conversation_agent_from_model = pipeline("conversational", model=model, tokenizer=tokenizer) + + conversation = Conversation("My name is Sarah and I live in London") + conversation_copy = Conversation("My name is Sarah and I live in London") + + result_model_id = conversation_agent_from_model_id([conversation]) + result_model = conversation_agent_from_model([conversation_copy]) + + # check for equality + self.assertEqual( + result_model_id.generated_responses[0], + "hi sarah, i live in london as well. do you have any plans for the weekend?", + ) + self.assertEqual( + result_model_id.generated_responses[0], + result_model.generated_responses[0], + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_depth_estimation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_depth_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..009aa1c942d24a87050ef0efb207a9fe858cc552 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_depth_estimation.py @@ -0,0 +1,116 @@ +# Copyright 2021 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 unittest + +from huggingface_hub.utils import insecure_hashlib + +from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available +from transformers.pipelines import DepthEstimationPipeline, pipeline +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_timm, + require_torch, + require_vision, + slow, +) + +from .test_pipelines_common import ANY + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +def hashimage(image: Image) -> str: + m = insecure_hashlib.md5(image.tobytes()) + return m.hexdigest() + + +@is_pipeline_test +@require_vision +@require_timm +@require_torch +class DepthEstimationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_DEPTH_ESTIMATION_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + depth_estimator = DepthEstimationPipeline(model=model, image_processor=processor) + return depth_estimator, [ + "./tests/fixtures/tests_samples/COCO/000000039769.png", + "./tests/fixtures/tests_samples/COCO/000000039769.png", + ] + + def run_pipeline_test(self, depth_estimator, examples): + outputs = depth_estimator("./tests/fixtures/tests_samples/COCO/000000039769.png") + self.assertEqual({"predicted_depth": ANY(torch.Tensor), "depth": ANY(Image.Image)}, outputs) + import datasets + + dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test") + outputs = depth_estimator( + [ + Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), + "http://images.cocodataset.org/val2017/000000039769.jpg", + # RGBA + dataset[0]["file"], + # LA + dataset[1]["file"], + # L + dataset[2]["file"], + ] + ) + self.assertEqual( + [ + {"predicted_depth": ANY(torch.Tensor), "depth": ANY(Image.Image)}, + {"predicted_depth": ANY(torch.Tensor), "depth": ANY(Image.Image)}, + {"predicted_depth": ANY(torch.Tensor), "depth": ANY(Image.Image)}, + {"predicted_depth": ANY(torch.Tensor), "depth": ANY(Image.Image)}, + {"predicted_depth": ANY(torch.Tensor), "depth": ANY(Image.Image)}, + ], + outputs, + ) + + @require_tf + @unittest.skip("Depth estimation is not implemented in TF") + def test_small_model_tf(self): + pass + + @slow + @require_torch + def test_large_model_pt(self): + model_id = "Intel/dpt-large" + depth_estimator = pipeline("depth-estimation", model=model_id) + outputs = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg") + outputs["depth"] = hashimage(outputs["depth"]) + + # This seems flaky. + # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") + self.assertEqual(nested_simplify(outputs["predicted_depth"].max().item()), 29.304) + self.assertEqual(nested_simplify(outputs["predicted_depth"].min().item()), 2.662) + + @require_torch + def test_small_model_pt(self): + # This is highly irregular to have no small tests. + self.skipTest("There is not hf-internal-testing tiny model for either GLPN nor DPT") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_document_question_answering.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_document_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..388be9247b395d24b9183aaa642948403e2cbca0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_document_question_answering.py @@ -0,0 +1,369 @@ +# Copyright 2022 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 unittest + +from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available +from transformers.pipelines import pipeline +from transformers.pipelines.document_question_answering import apply_tesseract +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_detectron2, + require_pytesseract, + require_tf, + require_torch, + require_vision, + slow, +) + +from .test_pipelines_common import ANY + + +if is_vision_available(): + from PIL import Image + + from transformers.image_utils import load_image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + def load_image(_): + return None + + +# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, +# so we can expect it to be available. +INVOICE_URL = ( + "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png" +) + + +@is_pipeline_test +@require_torch +@require_vision +class DocumentQuestionAnsweringPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING + + @require_pytesseract + @require_vision + def get_test_pipeline(self, model, tokenizer, processor): + dqa_pipeline = pipeline( + "document-question-answering", model=model, tokenizer=tokenizer, image_processor=processor + ) + + image = INVOICE_URL + word_boxes = list(zip(*apply_tesseract(load_image(image), None, ""))) + question = "What is the placebo?" + examples = [ + { + "image": load_image(image), + "question": question, + }, + { + "image": image, + "question": question, + }, + { + "image": image, + "question": question, + "word_boxes": word_boxes, + }, + ] + return dqa_pipeline, examples + + def run_pipeline_test(self, dqa_pipeline, examples): + outputs = dqa_pipeline(examples, top_k=2) + self.assertEqual( + outputs, + [ + [ + {"score": ANY(float), "answer": ANY(str), "start": ANY(int), "end": ANY(int)}, + {"score": ANY(float), "answer": ANY(str), "start": ANY(int), "end": ANY(int)}, + ] + ] + * 3, + ) + + @require_torch + @require_detectron2 + @require_pytesseract + def test_small_model_pt(self): + dqa_pipeline = pipeline("document-question-answering", model="hf-internal-testing/tiny-random-layoutlmv2") + image = INVOICE_URL + question = "How many cats are there?" + + expected_output = [ + {"score": 0.0001, "answer": "oy 2312/2019", "start": 38, "end": 39}, + {"score": 0.0001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, + ] + outputs = dqa_pipeline(image=image, question=question, top_k=2) + self.assertEqual(nested_simplify(outputs, decimals=4), expected_output) + + outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) + self.assertEqual(nested_simplify(outputs, decimals=4), expected_output) + + # This image does not detect ANY text in it, meaning layoutlmv2 should fail. + # Empty answer probably + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + outputs = dqa_pipeline(image=image, question=question, top_k=2) + self.assertEqual(outputs, []) + + # We can optionnally pass directly the words and bounding boxes + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + words = [] + boxes = [] + outputs = dqa_pipeline(image=image, question=question, words=words, boxes=boxes, top_k=2) + self.assertEqual(outputs, []) + + # TODO: Enable this once hf-internal-testing/tiny-random-donut is implemented + # @require_torch + # def test_small_model_pt_donut(self): + # dqa_pipeline = pipeline("document-question-answering", model="hf-internal-testing/tiny-random-donut") + # # dqa_pipeline = pipeline("document-question-answering", model="../tiny-random-donut") + # image = "https://templates.invoicehome.com/invoice-template-us-neat-750px.png" + # question = "How many cats are there?" + # + # outputs = dqa_pipeline(image=image, question=question, top_k=2) + # self.assertEqual( + # nested_simplify(outputs, decimals=4), [{"score": 0.8799, "answer": "2"}, {"score": 0.296, "answer": "1"}] + # ) + + @slow + @require_torch + @require_detectron2 + @require_pytesseract + def test_large_model_pt(self): + dqa_pipeline = pipeline( + "document-question-answering", + model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa", + revision="9977165", + ) + image = INVOICE_URL + question = "What is the invoice number?" + + outputs = dqa_pipeline(image=image, question=question, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9944, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.0009, "answer": "us-001", "start": 16, "end": 16}, + ], + ) + + outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9944, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.0009, "answer": "us-001", "start": 16, "end": 16}, + ], + ) + + outputs = dqa_pipeline( + [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.9944, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.0009, "answer": "us-001", "start": 16, "end": 16}, + ], + ] + * 2, + ) + + @slow + @require_torch + @require_detectron2 + @require_pytesseract + def test_large_model_pt_chunk(self): + dqa_pipeline = pipeline( + "document-question-answering", + model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa", + revision="9977165", + max_seq_len=50, + ) + image = INVOICE_URL + question = "What is the invoice number?" + + outputs = dqa_pipeline(image=image, question=question, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9974, "answer": "1110212019", "start": 23, "end": 23}, + {"score": 0.9948, "answer": "us-001", "start": 16, "end": 16}, + ], + ) + + outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9974, "answer": "1110212019", "start": 23, "end": 23}, + {"score": 0.9948, "answer": "us-001", "start": 16, "end": 16}, + ], + ) + + outputs = dqa_pipeline( + [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.9974, "answer": "1110212019", "start": 23, "end": 23}, + {"score": 0.9948, "answer": "us-001", "start": 16, "end": 16}, + ] + ] + * 2, + ) + + @slow + @require_torch + @require_pytesseract + @require_vision + def test_large_model_pt_layoutlm(self): + tokenizer = AutoTokenizer.from_pretrained( + "impira/layoutlm-document-qa", revision="3dc6de3", add_prefix_space=True + ) + dqa_pipeline = pipeline( + "document-question-answering", + model="impira/layoutlm-document-qa", + tokenizer=tokenizer, + revision="3dc6de3", + ) + image = INVOICE_URL + question = "What is the invoice number?" + + outputs = dqa_pipeline(image=image, question=question, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.4251, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.0819, "answer": "1110212019", "start": 23, "end": 23}, + ], + ) + + outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.4251, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.0819, "answer": "1110212019", "start": 23, "end": 23}, + ], + ) + + outputs = dqa_pipeline( + [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.4251, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.0819, "answer": "1110212019", "start": 23, "end": 23}, + ] + ] + * 2, + ) + + word_boxes = list(zip(*apply_tesseract(load_image(image), None, ""))) + + # This model should also work if `image` is set to None + outputs = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.4251, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.0819, "answer": "1110212019", "start": 23, "end": 23}, + ], + ) + + @slow + @require_torch + @require_pytesseract + @require_vision + def test_large_model_pt_layoutlm_chunk(self): + tokenizer = AutoTokenizer.from_pretrained( + "impira/layoutlm-document-qa", revision="3dc6de3", add_prefix_space=True + ) + dqa_pipeline = pipeline( + "document-question-answering", + model="impira/layoutlm-document-qa", + tokenizer=tokenizer, + revision="3dc6de3", + max_seq_len=50, + ) + image = INVOICE_URL + question = "What is the invoice number?" + + outputs = dqa_pipeline(image=image, question=question, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9999, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.9998, "answer": "us-001", "start": 16, "end": 16}, + ], + ) + + outputs = dqa_pipeline( + [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.9999, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.9998, "answer": "us-001", "start": 16, "end": 16}, + ] + ] + * 2, + ) + + word_boxes = list(zip(*apply_tesseract(load_image(image), None, ""))) + + # This model should also work if `image` is set to None + outputs = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9999, "answer": "us-001", "start": 16, "end": 16}, + {"score": 0.9998, "answer": "us-001", "start": 16, "end": 16}, + ], + ) + + @slow + @require_torch + def test_large_model_pt_donut(self): + dqa_pipeline = pipeline( + "document-question-answering", + model="naver-clova-ix/donut-base-finetuned-docvqa", + tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa"), + feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa", + ) + + image = INVOICE_URL + question = "What is the invoice number?" + outputs = dqa_pipeline(image=image, question=question, top_k=2) + self.assertEqual(nested_simplify(outputs, decimals=4), [{"answer": "us-001"}]) + + @require_tf + @unittest.skip("Document question answering not implemented in TF") + def test_small_model_tf(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_feature_extraction.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..87c5a151175c707f4522f2e68127eaed5b735d53 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_feature_extraction.py @@ -0,0 +1,215 @@ +# 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 unittest + +import numpy as np + +from transformers import ( + FEATURE_EXTRACTOR_MAPPING, + IMAGE_PROCESSOR_MAPPING, + MODEL_MAPPING, + TF_MODEL_MAPPING, + FeatureExtractionPipeline, + LxmertConfig, + is_tf_available, + is_torch_available, + pipeline, +) +from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch + + +if is_torch_available(): + import torch + +if is_tf_available(): + import tensorflow as tf + + +@is_pipeline_test +class FeatureExtractionPipelineTests(unittest.TestCase): + model_mapping = MODEL_MAPPING + tf_model_mapping = TF_MODEL_MAPPING + + @require_torch + def test_small_model_pt(self): + feature_extractor = pipeline( + task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert", framework="pt" + ) + outputs = feature_extractor("This is a test") + self.assertEqual( + nested_simplify(outputs), + [[[2.287, 1.234, 0.042, 1.53, 1.306, 0.879, -0.526, -1.71, -1.276, 0.756, -0.775, -1.048, -0.25, -0.595, -0.137, -0.598, 2.022, -0.812, 0.284, -0.488, -0.391, -0.403, -0.525, -0.061, -0.228, 1.086, 0.378, -0.14, 0.599, -0.087, -2.259, -0.098], [1.676, 0.232, -1.508, -0.145, 1.798, -1.388, 1.331, -0.37, -0.939, 0.043, 0.06, -0.414, -1.408, 0.24, 0.622, -0.55, -0.569, 1.873, -0.706, 1.924, -0.254, 1.927, -0.423, 0.152, -0.952, 0.509, -0.496, -0.968, 0.093, -1.049, -0.65, 0.312], [0.207, -0.775, -1.822, 0.321, -0.71, -0.201, 0.3, 1.146, -0.233, -0.753, -0.305, 1.309, -1.47, -0.21, 1.802, -1.555, -1.175, 1.323, -0.303, 0.722, -0.076, 0.103, -1.406, 1.931, 0.091, 0.237, 1.172, 1.607, 0.253, -0.9, -1.068, 0.438], [0.615, 1.077, 0.171, -0.175, 1.3, 0.901, -0.653, -0.138, 0.341, -0.654, -0.184, -0.441, -0.424, 0.356, -0.075, 0.26, -1.023, 0.814, 0.524, -0.904, -0.204, -0.623, 1.234, -1.03, 2.594, 0.56, 1.831, -0.199, -1.508, -0.492, -1.687, -2.165], [0.129, 0.008, -1.279, -0.412, -0.004, 1.663, 0.196, 0.104, 0.123, 0.119, 0.635, 1.757, 2.334, -0.799, -1.626, -1.26, 0.595, -0.316, -1.399, 0.232, 0.264, 1.386, -1.171, -0.256, -0.256, -1.944, 1.168, -0.368, -0.714, -0.51, 0.454, 1.148], [-0.32, 0.29, -1.309, -0.177, 0.453, 0.636, -0.024, 0.509, 0.931, -1.754, -1.575, 0.786, 0.046, -1.165, -1.416, 1.373, 1.293, -0.285, -1.541, -1.186, -0.106, -0.994, 2.001, 0.972, -0.02, 1.654, -0.236, 0.643, 1.02, 0.572, -0.914, -0.154], [0.7, -0.937, 0.441, 0.25, 0.78, -0.022, 0.282, -0.095, 1.558, -0.336, 1.706, 0.884, 1.28, 0.198, -0.796, 1.218, -1.769, 1.197, -0.342, -0.177, -0.645, 1.364, 0.008, -0.597, -0.484, -2.772, -0.696, -0.632, -0.34, -1.527, -0.562, 0.862], [2.504, 0.831, -1.271, -0.033, 0.298, -0.735, 1.339, 1.74, 0.233, -1.424, -0.819, -0.761, 0.291, 0.853, -0.092, -0.885, 0.164, 1.025, 0.907, 0.749, -1.515, -0.545, -1.365, 0.271, 0.034, -2.005, 0.031, 0.244, 0.621, 0.176, 0.336, -1.196], [-0.711, 0.591, -1.001, -0.946, 0.784, -1.66, 1.545, 0.799, -0.857, 1.148, 0.213, -0.285, 0.464, -0.139, 0.79, -1.663, -1.121, 0.575, -0.178, -0.508, 1.565, -0.242, -0.346, 1.024, -1.135, -0.158, -2.101, 0.275, 2.009, -0.425, 0.716, 0.981], [0.912, -1.186, -0.846, -0.421, -1.315, -0.827, 0.309, 0.533, 1.029, -2.343, 1.513, -1.238, 1.487, -0.849, 0.896, -0.927, -0.459, 0.159, 0.177, 0.873, 0.935, 1.433, -0.485, 0.737, 1.327, -0.338, 1.608, -0.47, -0.445, -1.118, -0.213, -0.446], [-0.434, -1.362, -1.098, -1.068, 1.507, 0.003, 0.413, -0.395, 0.897, -0.237, 1.405, -0.344, 1.693, 0.677, 0.097, -0.257, -0.602, 1.026, -1.229, 0.855, -0.713, 1.014, 0.443, 0.238, 0.425, -2.184, 1.933, -1.157, -1.132, -0.597, -0.785, 0.967], [0.58, -0.971, 0.789, -0.468, -0.576, 1.779, 1.747, 1.715, -1.939, 0.125, 0.656, -0.042, -1.024, -1.767, 0.107, -0.408, -0.866, -1.774, 1.248, 0.939, -0.033, 1.523, 1.168, -0.744, 0.209, -0.168, -0.316, 0.207, -0.432, 0.047, -0.646, -0.664], [-0.185, -0.613, -1.695, 1.602, -0.32, -0.277, 0.967, 0.728, -0.965, -0.234, 1.069, -0.63, -1.631, 0.711, 0.426, 1.298, -0.191, -0.467, -0.771, 0.971, -0.118, -1.577, -2.064, -0.055, -0.59, 0.642, -0.997, 1.251, 0.538, 1.367, 0.106, 1.704]]]) # fmt: skip + + @require_tf + def test_small_model_tf(self): + feature_extractor = pipeline( + task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert", framework="tf" + ) + outputs = feature_extractor("This is a test") + self.assertEqual( + nested_simplify(outputs), + [[[2.287, 1.234, 0.042, 1.53, 1.306, 0.879, -0.526, -1.71, -1.276, 0.756, -0.775, -1.048, -0.25, -0.595, -0.137, -0.598, 2.022, -0.812, 0.284, -0.488, -0.391, -0.403, -0.525, -0.061, -0.228, 1.086, 0.378, -0.14, 0.599, -0.087, -2.259, -0.098], [1.676, 0.232, -1.508, -0.145, 1.798, -1.388, 1.331, -0.37, -0.939, 0.043, 0.06, -0.414, -1.408, 0.24, 0.622, -0.55, -0.569, 1.873, -0.706, 1.924, -0.254, 1.927, -0.423, 0.152, -0.952, 0.509, -0.496, -0.968, 0.093, -1.049, -0.65, 0.312], [0.207, -0.775, -1.822, 0.321, -0.71, -0.201, 0.3, 1.146, -0.233, -0.753, -0.305, 1.309, -1.47, -0.21, 1.802, -1.555, -1.175, 1.323, -0.303, 0.722, -0.076, 0.103, -1.406, 1.931, 0.091, 0.237, 1.172, 1.607, 0.253, -0.9, -1.068, 0.438], [0.615, 1.077, 0.171, -0.175, 1.3, 0.901, -0.653, -0.138, 0.341, -0.654, -0.184, -0.441, -0.424, 0.356, -0.075, 0.26, -1.023, 0.814, 0.524, -0.904, -0.204, -0.623, 1.234, -1.03, 2.594, 0.56, 1.831, -0.199, -1.508, -0.492, -1.687, -2.165], [0.129, 0.008, -1.279, -0.412, -0.004, 1.663, 0.196, 0.104, 0.123, 0.119, 0.635, 1.757, 2.334, -0.799, -1.626, -1.26, 0.595, -0.316, -1.399, 0.232, 0.264, 1.386, -1.171, -0.256, -0.256, -1.944, 1.168, -0.368, -0.714, -0.51, 0.454, 1.148], [-0.32, 0.29, -1.309, -0.177, 0.453, 0.636, -0.024, 0.509, 0.931, -1.754, -1.575, 0.786, 0.046, -1.165, -1.416, 1.373, 1.293, -0.285, -1.541, -1.186, -0.106, -0.994, 2.001, 0.972, -0.02, 1.654, -0.236, 0.643, 1.02, 0.572, -0.914, -0.154], [0.7, -0.937, 0.441, 0.25, 0.78, -0.022, 0.282, -0.095, 1.558, -0.336, 1.706, 0.884, 1.28, 0.198, -0.796, 1.218, -1.769, 1.197, -0.342, -0.177, -0.645, 1.364, 0.008, -0.597, -0.484, -2.772, -0.696, -0.632, -0.34, -1.527, -0.562, 0.862], [2.504, 0.831, -1.271, -0.033, 0.298, -0.735, 1.339, 1.74, 0.233, -1.424, -0.819, -0.761, 0.291, 0.853, -0.092, -0.885, 0.164, 1.025, 0.907, 0.749, -1.515, -0.545, -1.365, 0.271, 0.034, -2.005, 0.031, 0.244, 0.621, 0.176, 0.336, -1.196], [-0.711, 0.591, -1.001, -0.946, 0.784, -1.66, 1.545, 0.799, -0.857, 1.148, 0.213, -0.285, 0.464, -0.139, 0.79, -1.663, -1.121, 0.575, -0.178, -0.508, 1.565, -0.242, -0.346, 1.024, -1.135, -0.158, -2.101, 0.275, 2.009, -0.425, 0.716, 0.981], [0.912, -1.186, -0.846, -0.421, -1.315, -0.827, 0.309, 0.533, 1.029, -2.343, 1.513, -1.238, 1.487, -0.849, 0.896, -0.927, -0.459, 0.159, 0.177, 0.873, 0.935, 1.433, -0.485, 0.737, 1.327, -0.338, 1.608, -0.47, -0.445, -1.118, -0.213, -0.446], [-0.434, -1.362, -1.098, -1.068, 1.507, 0.003, 0.413, -0.395, 0.897, -0.237, 1.405, -0.344, 1.693, 0.677, 0.097, -0.257, -0.602, 1.026, -1.229, 0.855, -0.713, 1.014, 0.443, 0.238, 0.425, -2.184, 1.933, -1.157, -1.132, -0.597, -0.785, 0.967], [0.58, -0.971, 0.789, -0.468, -0.576, 1.779, 1.747, 1.715, -1.939, 0.125, 0.656, -0.042, -1.024, -1.767, 0.107, -0.408, -0.866, -1.774, 1.248, 0.939, -0.033, 1.523, 1.168, -0.744, 0.209, -0.168, -0.316, 0.207, -0.432, 0.047, -0.646, -0.664], [-0.185, -0.613, -1.695, 1.602, -0.32, -0.277, 0.967, 0.728, -0.965, -0.234, 1.069, -0.63, -1.631, 0.711, 0.426, 1.298, -0.191, -0.467, -0.771, 0.971, -0.118, -1.577, -2.064, -0.055, -0.59, 0.642, -0.997, 1.251, 0.538, 1.367, 0.106, 1.704]]]) # fmt: skip + + @require_torch + def test_tokenization_small_model_pt(self): + feature_extractor = pipeline( + task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert", framework="pt" + ) + # test with empty parameters + outputs = feature_extractor("This is a test") + self.assertEqual( + nested_simplify(outputs), + [[[2.287, 1.234, 0.042, 1.53, 1.306, 0.879, -0.526, -1.71, -1.276, 0.756, -0.775, -1.048, -0.25, -0.595, -0.137, -0.598, 2.022, -0.812, 0.284, -0.488, -0.391, -0.403, -0.525, -0.061, -0.228, 1.086, 0.378, -0.14, 0.599, -0.087, -2.259, -0.098], [1.676, 0.232, -1.508, -0.145, 1.798, -1.388, 1.331, -0.37, -0.939, 0.043, 0.06, -0.414, -1.408, 0.24, 0.622, -0.55, -0.569, 1.873, -0.706, 1.924, -0.254, 1.927, -0.423, 0.152, -0.952, 0.509, -0.496, -0.968, 0.093, -1.049, -0.65, 0.312], [0.207, -0.775, -1.822, 0.321, -0.71, -0.201, 0.3, 1.146, -0.233, -0.753, -0.305, 1.309, -1.47, -0.21, 1.802, -1.555, -1.175, 1.323, -0.303, 0.722, -0.076, 0.103, -1.406, 1.931, 0.091, 0.237, 1.172, 1.607, 0.253, -0.9, -1.068, 0.438], [0.615, 1.077, 0.171, -0.175, 1.3, 0.901, -0.653, -0.138, 0.341, -0.654, -0.184, -0.441, -0.424, 0.356, -0.075, 0.26, -1.023, 0.814, 0.524, -0.904, -0.204, -0.623, 1.234, -1.03, 2.594, 0.56, 1.831, -0.199, -1.508, -0.492, -1.687, -2.165], [0.129, 0.008, -1.279, -0.412, -0.004, 1.663, 0.196, 0.104, 0.123, 0.119, 0.635, 1.757, 2.334, -0.799, -1.626, -1.26, 0.595, -0.316, -1.399, 0.232, 0.264, 1.386, -1.171, -0.256, -0.256, -1.944, 1.168, -0.368, -0.714, -0.51, 0.454, 1.148], [-0.32, 0.29, -1.309, -0.177, 0.453, 0.636, -0.024, 0.509, 0.931, -1.754, -1.575, 0.786, 0.046, -1.165, -1.416, 1.373, 1.293, -0.285, -1.541, -1.186, -0.106, -0.994, 2.001, 0.972, -0.02, 1.654, -0.236, 0.643, 1.02, 0.572, -0.914, -0.154], [0.7, -0.937, 0.441, 0.25, 0.78, -0.022, 0.282, -0.095, 1.558, -0.336, 1.706, 0.884, 1.28, 0.198, -0.796, 1.218, -1.769, 1.197, -0.342, -0.177, -0.645, 1.364, 0.008, -0.597, -0.484, -2.772, -0.696, -0.632, -0.34, -1.527, -0.562, 0.862], [2.504, 0.831, -1.271, -0.033, 0.298, -0.735, 1.339, 1.74, 0.233, -1.424, -0.819, -0.761, 0.291, 0.853, -0.092, -0.885, 0.164, 1.025, 0.907, 0.749, -1.515, -0.545, -1.365, 0.271, 0.034, -2.005, 0.031, 0.244, 0.621, 0.176, 0.336, -1.196], [-0.711, 0.591, -1.001, -0.946, 0.784, -1.66, 1.545, 0.799, -0.857, 1.148, 0.213, -0.285, 0.464, -0.139, 0.79, -1.663, -1.121, 0.575, -0.178, -0.508, 1.565, -0.242, -0.346, 1.024, -1.135, -0.158, -2.101, 0.275, 2.009, -0.425, 0.716, 0.981], [0.912, -1.186, -0.846, -0.421, -1.315, -0.827, 0.309, 0.533, 1.029, -2.343, 1.513, -1.238, 1.487, -0.849, 0.896, -0.927, -0.459, 0.159, 0.177, 0.873, 0.935, 1.433, -0.485, 0.737, 1.327, -0.338, 1.608, -0.47, -0.445, -1.118, -0.213, -0.446], [-0.434, -1.362, -1.098, -1.068, 1.507, 0.003, 0.413, -0.395, 0.897, -0.237, 1.405, -0.344, 1.693, 0.677, 0.097, -0.257, -0.602, 1.026, -1.229, 0.855, -0.713, 1.014, 0.443, 0.238, 0.425, -2.184, 1.933, -1.157, -1.132, -0.597, -0.785, 0.967], [0.58, -0.971, 0.789, -0.468, -0.576, 1.779, 1.747, 1.715, -1.939, 0.125, 0.656, -0.042, -1.024, -1.767, 0.107, -0.408, -0.866, -1.774, 1.248, 0.939, -0.033, 1.523, 1.168, -0.744, 0.209, -0.168, -0.316, 0.207, -0.432, 0.047, -0.646, -0.664], [-0.185, -0.613, -1.695, 1.602, -0.32, -0.277, 0.967, 0.728, -0.965, -0.234, 1.069, -0.63, -1.631, 0.711, 0.426, 1.298, -0.191, -0.467, -0.771, 0.971, -0.118, -1.577, -2.064, -0.055, -0.59, 0.642, -0.997, 1.251, 0.538, 1.367, 0.106, 1.704]]]) # fmt: skip + + # test with various tokenizer parameters + tokenize_kwargs = {"max_length": 3} + outputs = feature_extractor("This is a test", tokenize_kwargs=tokenize_kwargs) + self.assertEqual(np.squeeze(outputs).shape, (3, 32)) + + tokenize_kwargs = {"truncation": True, "padding": True, "max_length": 4} + outputs = feature_extractor( + ["This is a test", "This", "This is", "This is a", "This is a test test test test"], + tokenize_kwargs=tokenize_kwargs, + ) + self.assertEqual(np.squeeze(outputs).shape, (5, 4, 32)) + + tokenize_kwargs = {"padding": True, "max_length": 4} + outputs = feature_extractor( + ["This is a test", "This", "This is", "This is a", "This is a test test test test"], + truncation=True, + tokenize_kwargs=tokenize_kwargs, + ) + self.assertEqual(np.squeeze(outputs).shape, (5, 4, 32)) + + # raise value error if truncation parameter given for two places + tokenize_kwargs = {"truncation": True} + with self.assertRaises(ValueError): + _ = feature_extractor( + ["This is a test", "This", "This is", "This is a", "This is a test test test test"], + truncation=True, + tokenize_kwargs=tokenize_kwargs, + ) + + @require_tf + def test_tokenization_small_model_tf(self): + feature_extractor = pipeline( + task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert", framework="tf" + ) + # test with empty parameters + outputs = feature_extractor("This is a test") + self.assertEqual( + nested_simplify(outputs), + [[[2.287, 1.234, 0.042, 1.53, 1.306, 0.879, -0.526, -1.71, -1.276, 0.756, -0.775, -1.048, -0.25, -0.595, -0.137, -0.598, 2.022, -0.812, 0.284, -0.488, -0.391, -0.403, -0.525, -0.061, -0.228, 1.086, 0.378, -0.14, 0.599, -0.087, -2.259, -0.098], [1.676, 0.232, -1.508, -0.145, 1.798, -1.388, 1.331, -0.37, -0.939, 0.043, 0.06, -0.414, -1.408, 0.24, 0.622, -0.55, -0.569, 1.873, -0.706, 1.924, -0.254, 1.927, -0.423, 0.152, -0.952, 0.509, -0.496, -0.968, 0.093, -1.049, -0.65, 0.312], [0.207, -0.775, -1.822, 0.321, -0.71, -0.201, 0.3, 1.146, -0.233, -0.753, -0.305, 1.309, -1.47, -0.21, 1.802, -1.555, -1.175, 1.323, -0.303, 0.722, -0.076, 0.103, -1.406, 1.931, 0.091, 0.237, 1.172, 1.607, 0.253, -0.9, -1.068, 0.438], [0.615, 1.077, 0.171, -0.175, 1.3, 0.901, -0.653, -0.138, 0.341, -0.654, -0.184, -0.441, -0.424, 0.356, -0.075, 0.26, -1.023, 0.814, 0.524, -0.904, -0.204, -0.623, 1.234, -1.03, 2.594, 0.56, 1.831, -0.199, -1.508, -0.492, -1.687, -2.165], [0.129, 0.008, -1.279, -0.412, -0.004, 1.663, 0.196, 0.104, 0.123, 0.119, 0.635, 1.757, 2.334, -0.799, -1.626, -1.26, 0.595, -0.316, -1.399, 0.232, 0.264, 1.386, -1.171, -0.256, -0.256, -1.944, 1.168, -0.368, -0.714, -0.51, 0.454, 1.148], [-0.32, 0.29, -1.309, -0.177, 0.453, 0.636, -0.024, 0.509, 0.931, -1.754, -1.575, 0.786, 0.046, -1.165, -1.416, 1.373, 1.293, -0.285, -1.541, -1.186, -0.106, -0.994, 2.001, 0.972, -0.02, 1.654, -0.236, 0.643, 1.02, 0.572, -0.914, -0.154], [0.7, -0.937, 0.441, 0.25, 0.78, -0.022, 0.282, -0.095, 1.558, -0.336, 1.706, 0.884, 1.28, 0.198, -0.796, 1.218, -1.769, 1.197, -0.342, -0.177, -0.645, 1.364, 0.008, -0.597, -0.484, -2.772, -0.696, -0.632, -0.34, -1.527, -0.562, 0.862], [2.504, 0.831, -1.271, -0.033, 0.298, -0.735, 1.339, 1.74, 0.233, -1.424, -0.819, -0.761, 0.291, 0.853, -0.092, -0.885, 0.164, 1.025, 0.907, 0.749, -1.515, -0.545, -1.365, 0.271, 0.034, -2.005, 0.031, 0.244, 0.621, 0.176, 0.336, -1.196], [-0.711, 0.591, -1.001, -0.946, 0.784, -1.66, 1.545, 0.799, -0.857, 1.148, 0.213, -0.285, 0.464, -0.139, 0.79, -1.663, -1.121, 0.575, -0.178, -0.508, 1.565, -0.242, -0.346, 1.024, -1.135, -0.158, -2.101, 0.275, 2.009, -0.425, 0.716, 0.981], [0.912, -1.186, -0.846, -0.421, -1.315, -0.827, 0.309, 0.533, 1.029, -2.343, 1.513, -1.238, 1.487, -0.849, 0.896, -0.927, -0.459, 0.159, 0.177, 0.873, 0.935, 1.433, -0.485, 0.737, 1.327, -0.338, 1.608, -0.47, -0.445, -1.118, -0.213, -0.446], [-0.434, -1.362, -1.098, -1.068, 1.507, 0.003, 0.413, -0.395, 0.897, -0.237, 1.405, -0.344, 1.693, 0.677, 0.097, -0.257, -0.602, 1.026, -1.229, 0.855, -0.713, 1.014, 0.443, 0.238, 0.425, -2.184, 1.933, -1.157, -1.132, -0.597, -0.785, 0.967], [0.58, -0.971, 0.789, -0.468, -0.576, 1.779, 1.747, 1.715, -1.939, 0.125, 0.656, -0.042, -1.024, -1.767, 0.107, -0.408, -0.866, -1.774, 1.248, 0.939, -0.033, 1.523, 1.168, -0.744, 0.209, -0.168, -0.316, 0.207, -0.432, 0.047, -0.646, -0.664], [-0.185, -0.613, -1.695, 1.602, -0.32, -0.277, 0.967, 0.728, -0.965, -0.234, 1.069, -0.63, -1.631, 0.711, 0.426, 1.298, -0.191, -0.467, -0.771, 0.971, -0.118, -1.577, -2.064, -0.055, -0.59, 0.642, -0.997, 1.251, 0.538, 1.367, 0.106, 1.704]]]) # fmt: skip + + # test with various tokenizer parameters + tokenize_kwargs = {"max_length": 3} + outputs = feature_extractor("This is a test", tokenize_kwargs=tokenize_kwargs) + self.assertEqual(np.squeeze(outputs).shape, (3, 32)) + + tokenize_kwargs = {"truncation": True, "padding": True, "max_length": 4} + outputs = feature_extractor( + ["This is a test", "This", "This is", "This is a", "This is a test test test test"], + tokenize_kwargs=tokenize_kwargs, + ) + self.assertEqual(np.squeeze(outputs).shape, (5, 4, 32)) + + tokenize_kwargs = {"padding": True, "max_length": 4} + outputs = feature_extractor( + ["This is a test", "This", "This is", "This is a", "This is a test test test test"], + truncation=True, + tokenize_kwargs=tokenize_kwargs, + ) + self.assertEqual(np.squeeze(outputs).shape, (5, 4, 32)) + + # raise value error if truncation parameter given for two places + tokenize_kwargs = {"truncation": True} + with self.assertRaises(ValueError): + _ = feature_extractor( + ["This is a test", "This", "This is", "This is a", "This is a test test test test"], + truncation=True, + tokenize_kwargs=tokenize_kwargs, + ) + + @require_torch + def test_return_tensors_pt(self): + feature_extractor = pipeline( + task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert", framework="pt" + ) + outputs = feature_extractor("This is a test", return_tensors=True) + self.assertTrue(torch.is_tensor(outputs)) + + @require_tf + def test_return_tensors_tf(self): + feature_extractor = pipeline( + task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert", framework="tf" + ) + outputs = feature_extractor("This is a test", return_tensors=True) + self.assertTrue(tf.is_tensor(outputs)) + + def get_shape(self, input_, shape=None): + if shape is None: + shape = [] + if isinstance(input_, list): + subshapes = [self.get_shape(in_, shape) for in_ in input_] + if all(s == 0 for s in subshapes): + shape.append(len(input_)) + else: + subshape = subshapes[0] + shape = [len(input_), *subshape] + elif isinstance(input_, float): + return 0 + else: + raise ValueError("We expect lists of floats, nothing else") + return shape + + def get_test_pipeline(self, model, tokenizer, processor): + if tokenizer is None: + self.skipTest("No tokenizer") + return + elif ( + type(model.config) in FEATURE_EXTRACTOR_MAPPING + or isinstance(model.config, LxmertConfig) + or type(model.config) in IMAGE_PROCESSOR_MAPPING + ): + self.skipTest("This is a bimodal model, we need to find a more consistent way to switch on those models.") + return + elif model.config.is_encoder_decoder: + self.skipTest( + """encoder_decoder models are trickier for this pipeline. + Do we want encoder + decoder inputs to get some featues? + Do we want encoder only features ? + For now ignore those. + """ + ) + + return + feature_extractor = FeatureExtractionPipeline(model=model, tokenizer=tokenizer, feature_extractor=processor) + return feature_extractor, ["This is a test", "This is another test"] + + def run_pipeline_test(self, feature_extractor, examples): + outputs = feature_extractor("This is a test") + + shape = self.get_shape(outputs) + self.assertEqual(shape[0], 1) + + # If we send too small input + # there's a bug within FunnelModel (output with shape [1, 4, 2, 1] doesn't match the broadcast shape [1, 4, 2, 2]) + outputs = feature_extractor(["This is a test", "Another longer test"]) + shape = self.get_shape(outputs) + self.assertEqual(shape[0], 2) + + outputs = feature_extractor("This is a test" * 100, truncation=True) + shape = self.get_shape(outputs) + self.assertEqual(shape[0], 1) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_fill_mask.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_fill_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..571b320d617fa1edcb1428ced1c3fd7526be71c5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_fill_mask.py @@ -0,0 +1,454 @@ +# 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 gc +import unittest + +from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline +from transformers.pipelines import PipelineException +from transformers.testing_utils import ( + backend_empty_cache, + is_pipeline_test, + is_torch_available, + nested_simplify, + require_tf, + require_torch, + require_torch_accelerator, + slow, + torch_device, +) + +from .test_pipelines_common import ANY + + +@is_pipeline_test +class FillMaskPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_MASKED_LM_MAPPING + tf_model_mapping = TF_MODEL_FOR_MASKED_LM_MAPPING + + def tearDown(self): + super().tearDown() + # clean-up as much as possible GPU memory occupied by PyTorch + gc.collect() + if is_torch_available(): + backend_empty_cache(torch_device) + + @require_tf + def test_small_model_tf(self): + unmasker = pipeline(task="fill-mask", model="sshleifer/tiny-distilroberta-base", top_k=2, framework="tf") + outputs = unmasker("My name is ") + self.assertEqual( + nested_simplify(outputs, decimals=6), + [ + {"sequence": "My name is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped"}, + {"sequence": "My name is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser"}, + ], + ) + + outputs = unmasker("The largest city in France is ") + self.assertEqual( + nested_simplify(outputs, decimals=6), + [ + { + "sequence": "The largest city in France is grouped", + "score": 2.1e-05, + "token": 38015, + "token_str": " grouped", + }, + { + "sequence": "The largest city in France is accuser", + "score": 2.1e-05, + "token": 25506, + "token_str": " accuser", + }, + ], + ) + + outputs = unmasker("My name is ", targets=[" Patrick", " Clara", " Teven"], top_k=3) + self.assertEqual( + nested_simplify(outputs, decimals=6), + [ + {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, + {"sequence": "My name is Patrick", "score": 2e-05, "token": 3499, "token_str": " Patrick"}, + {"sequence": "My name is Te", "score": 1.9e-05, "token": 2941, "token_str": " Te"}, + ], + ) + + @require_torch + def test_small_model_pt(self): + unmasker = pipeline(task="fill-mask", model="sshleifer/tiny-distilroberta-base", top_k=2, framework="pt") + + outputs = unmasker("My name is ") + self.assertEqual( + nested_simplify(outputs, decimals=6), + [ + {"sequence": "My name is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul"}, + {"sequence": "My name isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, + ], + ) + + outputs = unmasker("The largest city in France is ") + self.assertEqual( + nested_simplify(outputs, decimals=6), + [ + { + "sequence": "The largest city in France is Maul", + "score": 2.2e-05, + "token": 35676, + "token_str": " Maul", + }, + {"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, + ], + ) + + outputs = unmasker("My name is ", targets=[" Patrick", " Clara", " Teven"], top_k=3) + self.assertEqual( + nested_simplify(outputs, decimals=6), + [ + {"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3499, "token_str": " Patrick"}, + {"sequence": "My name is Te", "score": 2e-05, "token": 2941, "token_str": " Te"}, + {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, + ], + ) + + outputs = unmasker("My name is ", top_k=2) + + self.assertEqual( + nested_simplify(outputs, decimals=6), + [ + [ + { + "score": 2.2e-05, + "token": 35676, + "token_str": " Maul", + "sequence": "My name is Maul", + }, + {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "My name isELS"}, + ], + [ + { + "score": 2.2e-05, + "token": 35676, + "token_str": " Maul", + "sequence": "My name is Maul", + }, + {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "My name isELS"}, + ], + ], + ) + + @require_torch_accelerator + def test_fp16_casting(self): + pipe = pipeline( + "fill-mask", + model="hf-internal-testing/tiny-random-distilbert", + device=torch_device, + framework="pt", + ) + + # convert model to fp16 + pipe.model.half() + + response = pipe("Paris is the [MASK] of France.") + # We actually don't care about the result, we just want to make sure + # it works, meaning the float16 tensor got casted back to float32 + # for postprocessing. + self.assertIsInstance(response, list) + + @slow + @require_torch + def test_large_model_pt(self): + unmasker = pipeline(task="fill-mask", model="distilroberta-base", top_k=2, framework="pt") + self.run_large_test(unmasker) + + @slow + @require_tf + def test_large_model_tf(self): + unmasker = pipeline(task="fill-mask", model="distilroberta-base", top_k=2, framework="tf") + self.run_large_test(unmasker) + + def run_large_test(self, unmasker): + outputs = unmasker("My name is ") + self.assertEqual( + nested_simplify(outputs), + [ + {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"}, + {"sequence": "My name is Chris", "score": 0.007, "token": 1573, "token_str": " Chris"}, + ], + ) + outputs = unmasker("The largest city in France is ") + self.assertEqual( + nested_simplify(outputs), + [ + { + "sequence": "The largest city in France is Paris", + "score": 0.251, + "token": 2201, + "token_str": " Paris", + }, + { + "sequence": "The largest city in France is Lyon", + "score": 0.214, + "token": 12790, + "token_str": " Lyon", + }, + ], + ) + + outputs = unmasker("My name is ", targets=[" Patrick", " Clara", " Teven"], top_k=3) + self.assertEqual( + nested_simplify(outputs), + [ + {"sequence": "My name is Patrick", "score": 0.005, "token": 3499, "token_str": " Patrick"}, + {"sequence": "My name is Clara", "score": 0.000, "token": 13606, "token_str": " Clara"}, + {"sequence": "My name is Te", "score": 0.000, "token": 2941, "token_str": " Te"}, + ], + ) + + dummy_str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," * 100 + outputs = unmasker( + "My name is " + dummy_str, + tokenizer_kwargs={"truncation": True}, + ) + simplified = nested_simplify(outputs, decimals=4) + self.assertEqual( + [{"sequence": x["sequence"][:100]} for x in simplified], + [ + {"sequence": f"My name is,{dummy_str}"[:100]}, + {"sequence": f"My name is:,{dummy_str}"[:100]}, + ], + ) + self.assertEqual( + [{k: x[k] for k in x if k != "sequence"} for x in simplified], + [ + {"score": 0.2819, "token": 6, "token_str": ","}, + {"score": 0.0954, "token": 46686, "token_str": ":,"}, + ], + ) + + @require_torch + def test_model_no_pad_pt(self): + unmasker = pipeline(task="fill-mask", model="sshleifer/tiny-distilroberta-base", framework="pt") + unmasker.tokenizer.pad_token_id = None + unmasker.tokenizer.pad_token = None + self.run_pipeline_test(unmasker, []) + + @require_tf + def test_model_no_pad_tf(self): + unmasker = pipeline(task="fill-mask", model="sshleifer/tiny-distilroberta-base", framework="tf") + unmasker.tokenizer.pad_token_id = None + unmasker.tokenizer.pad_token = None + self.run_pipeline_test(unmasker, []) + + def get_test_pipeline(self, model, tokenizer, processor): + if tokenizer is None or tokenizer.mask_token_id is None: + self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)") + + fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer) + examples = [ + f"This is another {tokenizer.mask_token} test", + ] + return fill_masker, examples + + def run_pipeline_test(self, fill_masker, examples): + tokenizer = fill_masker.tokenizer + model = fill_masker.model + + outputs = fill_masker( + f"This is a {tokenizer.mask_token}", + ) + self.assertEqual( + outputs, + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + ) + + outputs = fill_masker([f"This is a {tokenizer.mask_token}"]) + self.assertEqual( + outputs, + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + ) + + outputs = fill_masker([f"This is a {tokenizer.mask_token}", f"Another {tokenizer.mask_token} great test."]) + self.assertEqual( + outputs, + [ + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + ], + ) + + with self.assertRaises(ValueError): + fill_masker([None]) + # No mask_token is not supported + with self.assertRaises(PipelineException): + fill_masker("This is") + + self.run_test_top_k(model, tokenizer) + self.run_test_targets(model, tokenizer) + self.run_test_top_k_targets(model, tokenizer) + self.fill_mask_with_duplicate_targets_and_top_k(model, tokenizer) + self.fill_mask_with_multiple_masks(model, tokenizer) + + def run_test_targets(self, model, tokenizer): + vocab = tokenizer.get_vocab() + targets = sorted(vocab.keys())[:2] + # Pipeline argument + fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer, targets=targets) + outputs = fill_masker(f"This is a {tokenizer.mask_token}") + self.assertEqual( + outputs, + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + ) + target_ids = {vocab[el] for el in targets} + self.assertEqual({el["token"] for el in outputs}, target_ids) + processed_targets = [tokenizer.decode([x]) for x in target_ids] + self.assertEqual({el["token_str"] for el in outputs}, set(processed_targets)) + + # Call argument + fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer) + outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets=targets) + self.assertEqual( + outputs, + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + ) + target_ids = {vocab[el] for el in targets} + self.assertEqual({el["token"] for el in outputs}, target_ids) + processed_targets = [tokenizer.decode([x]) for x in target_ids] + self.assertEqual({el["token_str"] for el in outputs}, set(processed_targets)) + + # Score equivalence + outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets=targets) + tokens = [top_mask["token_str"] for top_mask in outputs] + scores = [top_mask["score"] for top_mask in outputs] + + # For some BPE tokenizers, `` is removed during decoding, so `token_str` won't be the same as in `targets`. + if set(tokens) == set(targets): + unmasked_targets = fill_masker(f"This is a {tokenizer.mask_token}", targets=tokens) + target_scores = [top_mask["score"] for top_mask in unmasked_targets] + self.assertEqual(nested_simplify(scores), nested_simplify(target_scores)) + + # Raises with invalid + with self.assertRaises(ValueError): + outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets=[]) + # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised + if "" not in tokenizer.get_vocab(): + with self.assertRaises(ValueError): + outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets=[""]) + with self.assertRaises(ValueError): + outputs = fill_masker(f"This is a {tokenizer.mask_token}", targets="") + + def run_test_top_k(self, model, tokenizer): + fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer, top_k=2) + outputs = fill_masker(f"This is a {tokenizer.mask_token}") + self.assertEqual( + outputs, + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + ) + + fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer) + outputs2 = fill_masker(f"This is a {tokenizer.mask_token}", top_k=2) + self.assertEqual( + outputs2, + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + ) + self.assertEqual(nested_simplify(outputs), nested_simplify(outputs2)) + + def run_test_top_k_targets(self, model, tokenizer): + vocab = tokenizer.get_vocab() + fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer) + + # top_k=2, ntargets=3 + targets = sorted(vocab.keys())[:3] + outputs = fill_masker(f"This is a {tokenizer.mask_token}", top_k=2, targets=targets) + + # If we use the most probably targets, and filter differently, we should still + # have the same results + targets2 = [el["token_str"] for el in sorted(outputs, key=lambda x: x["score"], reverse=True)] + # For some BPE tokenizers, `` is removed during decoding, so `token_str` won't be the same as in `targets`. + if set(targets2).issubset(targets): + outputs2 = fill_masker(f"This is a {tokenizer.mask_token}", top_k=3, targets=targets2) + # They should yield exactly the same result + self.assertEqual(nested_simplify(outputs), nested_simplify(outputs2)) + + def fill_mask_with_duplicate_targets_and_top_k(self, model, tokenizer): + fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer) + vocab = tokenizer.get_vocab() + # String duplicates + id duplicates + targets = sorted(vocab.keys())[:3] + targets = [targets[0], targets[1], targets[0], targets[2], targets[1]] + outputs = fill_masker(f"My name is {tokenizer.mask_token}", targets=targets, top_k=10) + + # The target list contains duplicates, so we can't output more + # than them + self.assertEqual(len(outputs), 3) + + def fill_mask_with_multiple_masks(self, model, tokenizer): + fill_masker = FillMaskPipeline(model=model, tokenizer=tokenizer) + + outputs = fill_masker( + f"This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}", top_k=2 + ) + self.assertEqual( + outputs, + [ + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + [ + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + {"sequence": ANY(str), "score": ANY(float), "token": ANY(int), "token_str": ANY(str)}, + ], + ], + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_classification.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..7af16371a0208311e3e0a43d9bac6950b8e7b12f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_classification.py @@ -0,0 +1,221 @@ +# Copyright 2021 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 unittest + +from transformers import ( + MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, + PreTrainedTokenizerBase, + is_vision_available, +) +from transformers.pipelines import ImageClassificationPipeline, pipeline +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_torch, + require_torch_or_tf, + require_vision, + slow, +) + +from .test_pipelines_common import ANY + + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +@is_pipeline_test +@require_torch_or_tf +@require_vision +class ImageClassificationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING + tf_model_mapping = TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + image_classifier = ImageClassificationPipeline(model=model, image_processor=processor, top_k=2) + examples = [ + Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), + "http://images.cocodataset.org/val2017/000000039769.jpg", + ] + return image_classifier, examples + + def run_pipeline_test(self, image_classifier, examples): + outputs = image_classifier("./tests/fixtures/tests_samples/COCO/000000039769.png") + + self.assertEqual( + outputs, + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + ) + + import datasets + + dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test") + + # Accepts URL + PIL.Image + lists + outputs = image_classifier( + [ + Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), + "http://images.cocodataset.org/val2017/000000039769.jpg", + # RGBA + dataset[0]["file"], + # LA + dataset[1]["file"], + # L + dataset[2]["file"], + ] + ) + self.assertEqual( + outputs, + [ + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + ], + ) + + @require_torch + def test_small_model_pt(self): + small_model = "hf-internal-testing/tiny-random-vit" + image_classifier = pipeline("image-classification", model=small_model) + + outputs = image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg") + self.assertEqual( + nested_simplify(outputs, decimals=4), + [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}], + ) + + outputs = image_classifier( + [ + "http://images.cocodataset.org/val2017/000000039769.jpg", + "http://images.cocodataset.org/val2017/000000039769.jpg", + ], + top_k=2, + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}], + [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}], + ], + ) + + @require_tf + def test_small_model_tf(self): + small_model = "hf-internal-testing/tiny-random-vit" + image_classifier = pipeline("image-classification", model=small_model, framework="tf") + + outputs = image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg") + self.assertEqual( + nested_simplify(outputs, decimals=4), + [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}], + ) + + outputs = image_classifier( + [ + "http://images.cocodataset.org/val2017/000000039769.jpg", + "http://images.cocodataset.org/val2017/000000039769.jpg", + ], + top_k=2, + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}], + [{"label": "LABEL_1", "score": 0.574}, {"label": "LABEL_0", "score": 0.426}], + ], + ) + + def test_custom_tokenizer(self): + tokenizer = PreTrainedTokenizerBase() + + # Assert that the pipeline can be initialized with a feature extractor that is not in any mapping + image_classifier = pipeline( + "image-classification", model="hf-internal-testing/tiny-random-vit", tokenizer=tokenizer + ) + + self.assertIs(image_classifier.tokenizer, tokenizer) + + @slow + @require_torch + def test_perceiver(self): + # Perceiver is not tested by `run_pipeline_test` properly. + # That is because the type of feature_extractor and model preprocessor need to be kept + # in sync, which is not the case in the current design + image_classifier = pipeline("image-classification", model="deepmind/vision-perceiver-conv") + outputs = image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg") + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.4385, "label": "tabby, tabby cat"}, + {"score": 0.321, "label": "tiger cat"}, + {"score": 0.0502, "label": "Egyptian cat"}, + {"score": 0.0137, "label": "crib, cot"}, + {"score": 0.007, "label": "radiator"}, + ], + ) + + image_classifier = pipeline("image-classification", model="deepmind/vision-perceiver-fourier") + outputs = image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg") + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.5658, "label": "tabby, tabby cat"}, + {"score": 0.1309, "label": "tiger cat"}, + {"score": 0.0722, "label": "Egyptian cat"}, + {"score": 0.0707, "label": "remote control, remote"}, + {"score": 0.0082, "label": "computer keyboard, keypad"}, + ], + ) + + image_classifier = pipeline("image-classification", model="deepmind/vision-perceiver-learned") + outputs = image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg") + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.3022, "label": "tabby, tabby cat"}, + {"score": 0.2362, "label": "Egyptian cat"}, + {"score": 0.1856, "label": "tiger cat"}, + {"score": 0.0324, "label": "remote control, remote"}, + {"score": 0.0096, "label": "quilt, comforter, comfort, puff"}, + ], + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_segmentation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..9c5c8fdfd4a8dde2dc83e509e8f27d4e4f53634a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_segmentation.py @@ -0,0 +1,731 @@ +# Copyright 2021 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 tempfile +import unittest +from typing import Dict + +import datasets +import numpy as np +import requests +from datasets import load_dataset +from huggingface_hub.utils import insecure_hashlib + +from transformers import ( + MODEL_FOR_IMAGE_SEGMENTATION_MAPPING, + MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING, + MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING, + AutoImageProcessor, + AutoModelForImageSegmentation, + AutoModelForInstanceSegmentation, + DetrForSegmentation, + ImageSegmentationPipeline, + MaskFormerForInstanceSegmentation, + is_vision_available, + pipeline, +) +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_timm, + require_torch, + require_vision, + slow, +) + +from .test_pipelines_common import ANY + + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +def hashimage(image: Image) -> str: + m = insecure_hashlib.md5(image.tobytes()) + return m.hexdigest()[:10] + + +def mask_to_test_readable(mask: Image) -> Dict: + npimg = np.array(mask) + white_pixels = (npimg == 255).sum() + shape = npimg.shape + return {"hash": hashimage(mask), "white_pixels": white_pixels, "shape": shape} + + +def mask_to_test_readable_only_shape(mask: Image) -> Dict: + npimg = np.array(mask) + shape = npimg.shape + return {"shape": shape} + + +@is_pipeline_test +@require_vision +@require_timm +@require_torch +class ImageSegmentationPipelineTests(unittest.TestCase): + model_mapping = dict( + (list(MODEL_FOR_IMAGE_SEGMENTATION_MAPPING.items()) if MODEL_FOR_IMAGE_SEGMENTATION_MAPPING else []) + + (MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING.items() if MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING else []) + + (MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING.items() if MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING else []) + ) + + def get_test_pipeline(self, model, tokenizer, processor): + image_segmenter = ImageSegmentationPipeline(model=model, image_processor=processor) + return image_segmenter, [ + "./tests/fixtures/tests_samples/COCO/000000039769.png", + "./tests/fixtures/tests_samples/COCO/000000039769.png", + ] + + def run_pipeline_test(self, image_segmenter, examples): + outputs = image_segmenter( + "./tests/fixtures/tests_samples/COCO/000000039769.png", + threshold=0.0, + mask_threshold=0, + overlap_mask_area_threshold=0, + ) + self.assertIsInstance(outputs, list) + n = len(outputs) + if isinstance(image_segmenter.model, (MaskFormerForInstanceSegmentation, DetrForSegmentation)): + # Instance segmentation (maskformer, and detr) have a slot for null class + # and can output nothing even with a low threshold + self.assertGreaterEqual(n, 0) + else: + self.assertGreaterEqual(n, 1) + # XXX: PIL.Image implements __eq__ which bypasses ANY, so we inverse the comparison + # to make it work + self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n, outputs) + + dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test") + + # RGBA + outputs = image_segmenter(dataset[0]["file"], threshold=0.0, mask_threshold=0, overlap_mask_area_threshold=0) + m = len(outputs) + self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * m, outputs) + # LA + outputs = image_segmenter(dataset[1]["file"], threshold=0.0, mask_threshold=0, overlap_mask_area_threshold=0) + m = len(outputs) + self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * m, outputs) + # L + outputs = image_segmenter(dataset[2]["file"], threshold=0.0, mask_threshold=0, overlap_mask_area_threshold=0) + m = len(outputs) + self.assertEqual([{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * m, outputs) + + if isinstance(image_segmenter.model, DetrForSegmentation): + # We need to test batch_size with images with the same size. + # Detr doesn't normalize the size of the images, meaning we can have + # 800x800 or 800x1200, meaning we cannot batch simply. + # We simply bail on this + batch_size = 1 + else: + batch_size = 2 + + # 5 times the same image so the output shape is predictable + batch = [ + "./tests/fixtures/tests_samples/COCO/000000039769.png", + "./tests/fixtures/tests_samples/COCO/000000039769.png", + "./tests/fixtures/tests_samples/COCO/000000039769.png", + "./tests/fixtures/tests_samples/COCO/000000039769.png", + "./tests/fixtures/tests_samples/COCO/000000039769.png", + ] + outputs = image_segmenter( + batch, + threshold=0.0, + mask_threshold=0, + overlap_mask_area_threshold=0, + batch_size=batch_size, + ) + self.assertEqual(len(batch), len(outputs)) + self.assertEqual(len(outputs[0]), n) + self.assertEqual( + [ + [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n, + [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n, + [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n, + [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n, + [{"score": ANY(float, type(None)), "label": ANY(str), "mask": ANY(Image.Image)}] * n, + ], + outputs, + f"Expected [{n}, {n}, {n}, {n}, {n}], got {[len(item) for item in outputs]}", + ) + + @require_tf + @unittest.skip("Image segmentation not implemented in TF") + def test_small_model_tf(self): + pass + + @require_torch + def test_small_model_pt_no_panoptic(self): + model_id = "hf-internal-testing/tiny-random-mobilevit" + # The default task is `image-classification` we need to override + pipe = pipeline(task="image-segmentation", model=model_id) + + # This model does NOT support neither `instance` nor `panoptic` + # We should error out + with self.assertRaises(ValueError) as e: + pipe("http://images.cocodataset.org/val2017/000000039769.jpg", subtask="panoptic") + self.assertEqual( + str(e.exception), + "Subtask panoptic is not supported for model ", + ) + with self.assertRaises(ValueError) as e: + pipe("http://images.cocodataset.org/val2017/000000039769.jpg", subtask="instance") + self.assertEqual( + str(e.exception), + "Subtask instance is not supported for model ", + ) + + @require_torch + def test_small_model_pt(self): + model_id = "hf-internal-testing/tiny-detr-mobilenetsv3-panoptic" + + model = AutoModelForImageSegmentation.from_pretrained(model_id) + image_processor = AutoImageProcessor.from_pretrained(model_id) + image_segmenter = ImageSegmentationPipeline( + model=model, + image_processor=image_processor, + subtask="panoptic", + threshold=0.0, + mask_threshold=0.0, + overlap_mask_area_threshold=0.0, + ) + + outputs = image_segmenter( + "http://images.cocodataset.org/val2017/000000039769.jpg", + ) + + # Shortening by hashing + for o in outputs: + o["mask"] = mask_to_test_readable(o["mask"]) + + # This is extremely brittle, and those values are made specific for the CI. + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": 0.004, + "label": "LABEL_215", + "mask": {"hash": "a01498ca7c", "shape": (480, 640), "white_pixels": 307200}, + }, + ], + ) + + outputs = image_segmenter( + [ + "http://images.cocodataset.org/val2017/000000039769.jpg", + "http://images.cocodataset.org/val2017/000000039769.jpg", + ], + ) + for output in outputs: + for o in output: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + { + "score": 0.004, + "label": "LABEL_215", + "mask": {"hash": "a01498ca7c", "shape": (480, 640), "white_pixels": 307200}, + }, + ], + [ + { + "score": 0.004, + "label": "LABEL_215", + "mask": {"hash": "a01498ca7c", "shape": (480, 640), "white_pixels": 307200}, + }, + ], + ], + ) + + output = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", subtask="instance") + for o in output: + o["mask"] = mask_to_test_readable(o["mask"]) + self.assertEqual( + nested_simplify(output, decimals=4), + [ + { + "score": 0.004, + "label": "LABEL_215", + "mask": {"hash": "a01498ca7c", "shape": (480, 640), "white_pixels": 307200}, + }, + ], + ) + + # This must be surprising to the reader. + # The `panoptic` returns only LABEL_215, and this returns 3 labels. + # + output = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", subtask="semantic") + + output_masks = [o["mask"] for o in output] + + # page links (to visualize) + expected_masks = [ + "https://huggingface.co/datasets/hf-internal-testing/mask-for-image-segmentation-tests/blob/main/mask_0.png", + "https://huggingface.co/datasets/hf-internal-testing/mask-for-image-segmentation-tests/blob/main/mask_1.png", + "https://huggingface.co/datasets/hf-internal-testing/mask-for-image-segmentation-tests/blob/main/mask_2.png", + ] + # actual links to get files + expected_masks = [x.replace("/blob/", "/resolve/") for x in expected_masks] + expected_masks = [Image.open(requests.get(image, stream=True).raw) for image in expected_masks] + + # Convert masks to numpy array + output_masks = [np.array(x) for x in output_masks] + expected_masks = [np.array(x) for x in expected_masks] + + self.assertEqual(output_masks[0].shape, expected_masks[0].shape) + self.assertEqual(output_masks[1].shape, expected_masks[1].shape) + self.assertEqual(output_masks[2].shape, expected_masks[2].shape) + + # With un-trained tiny random models, the output `logits` tensor is very likely to contain many values + # close to each other, which cause `argmax` to give quite different results when running the test on 2 + # environments. We use a lower threshold `0.9` here to avoid flakiness. + self.assertGreaterEqual(np.mean(output_masks[0] == expected_masks[0]), 0.9) + self.assertGreaterEqual(np.mean(output_masks[1] == expected_masks[1]), 0.9) + self.assertGreaterEqual(np.mean(output_masks[2] == expected_masks[2]), 0.9) + + for o in output: + o["mask"] = mask_to_test_readable_only_shape(o["mask"]) + self.maxDiff = None + self.assertEqual( + nested_simplify(output, decimals=4), + [ + { + "label": "LABEL_88", + "mask": {"shape": (480, 640)}, + "score": None, + }, + { + "label": "LABEL_101", + "mask": {"shape": (480, 640)}, + "score": None, + }, + { + "label": "LABEL_215", + "mask": {"shape": (480, 640)}, + "score": None, + }, + ], + ) + + @require_torch + def test_small_model_pt_semantic(self): + model_id = "hf-internal-testing/tiny-random-beit-pipeline" + image_segmenter = pipeline(model=model_id) + outputs = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg") + for o in outputs: + # shortening by hashing + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": None, + "label": "LABEL_0", + "mask": {"hash": "42d0907228", "shape": (480, 640), "white_pixels": 10714}, + }, + { + "score": None, + "label": "LABEL_1", + "mask": {"hash": "46b8cc3976", "shape": (480, 640), "white_pixels": 296486}, + }, + ], + ) + + @require_torch + @slow + def test_integration_torch_image_segmentation(self): + model_id = "facebook/detr-resnet-50-panoptic" + image_segmenter = pipeline( + "image-segmentation", + model=model_id, + threshold=0.0, + overlap_mask_area_threshold=0.0, + ) + + outputs = image_segmenter( + "http://images.cocodataset.org/val2017/000000039769.jpg", + ) + + # Shortening by hashing + for o in outputs: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": 0.9094, + "label": "blanket", + "mask": {"hash": "dcff19a97a", "shape": (480, 640), "white_pixels": 16617}, + }, + { + "score": 0.9941, + "label": "cat", + "mask": {"hash": "9c0af87bd0", "shape": (480, 640), "white_pixels": 59185}, + }, + { + "score": 0.9987, + "label": "remote", + "mask": {"hash": "c7870600d6", "shape": (480, 640), "white_pixels": 4182}, + }, + { + "score": 0.9995, + "label": "remote", + "mask": {"hash": "ef899a25fd", "shape": (480, 640), "white_pixels": 2275}, + }, + { + "score": 0.9722, + "label": "couch", + "mask": {"hash": "37b8446ac5", "shape": (480, 640), "white_pixels": 172380}, + }, + { + "score": 0.9994, + "label": "cat", + "mask": {"hash": "6a09d3655e", "shape": (480, 640), "white_pixels": 52561}, + }, + ], + ) + + outputs = image_segmenter( + [ + "http://images.cocodataset.org/val2017/000000039769.jpg", + "http://images.cocodataset.org/val2017/000000039769.jpg", + ], + ) + + # Shortening by hashing + for output in outputs: + for o in output: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + { + "score": 0.9094, + "label": "blanket", + "mask": {"hash": "dcff19a97a", "shape": (480, 640), "white_pixels": 16617}, + }, + { + "score": 0.9941, + "label": "cat", + "mask": {"hash": "9c0af87bd0", "shape": (480, 640), "white_pixels": 59185}, + }, + { + "score": 0.9987, + "label": "remote", + "mask": {"hash": "c7870600d6", "shape": (480, 640), "white_pixels": 4182}, + }, + { + "score": 0.9995, + "label": "remote", + "mask": {"hash": "ef899a25fd", "shape": (480, 640), "white_pixels": 2275}, + }, + { + "score": 0.9722, + "label": "couch", + "mask": {"hash": "37b8446ac5", "shape": (480, 640), "white_pixels": 172380}, + }, + { + "score": 0.9994, + "label": "cat", + "mask": {"hash": "6a09d3655e", "shape": (480, 640), "white_pixels": 52561}, + }, + ], + [ + { + "score": 0.9094, + "label": "blanket", + "mask": {"hash": "dcff19a97a", "shape": (480, 640), "white_pixels": 16617}, + }, + { + "score": 0.9941, + "label": "cat", + "mask": {"hash": "9c0af87bd0", "shape": (480, 640), "white_pixels": 59185}, + }, + { + "score": 0.9987, + "label": "remote", + "mask": {"hash": "c7870600d6", "shape": (480, 640), "white_pixels": 4182}, + }, + { + "score": 0.9995, + "label": "remote", + "mask": {"hash": "ef899a25fd", "shape": (480, 640), "white_pixels": 2275}, + }, + { + "score": 0.9722, + "label": "couch", + "mask": {"hash": "37b8446ac5", "shape": (480, 640), "white_pixels": 172380}, + }, + { + "score": 0.9994, + "label": "cat", + "mask": {"hash": "6a09d3655e", "shape": (480, 640), "white_pixels": 52561}, + }, + ], + ], + ) + + @require_torch + @slow + def test_threshold(self): + model_id = "facebook/detr-resnet-50-panoptic" + image_segmenter = pipeline("image-segmentation", model=model_id) + + outputs = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", threshold=0.999) + # Shortening by hashing + for o in outputs: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": 0.9995, + "label": "remote", + "mask": {"hash": "d02404f578", "shape": (480, 640), "white_pixels": 2789}, + }, + { + "score": 0.9994, + "label": "cat", + "mask": {"hash": "eaa115b40c", "shape": (480, 640), "white_pixels": 304411}, + }, + ], + ) + + outputs = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", threshold=0.5) + + for o in outputs: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": 0.9941, + "label": "cat", + "mask": {"hash": "9c0af87bd0", "shape": (480, 640), "white_pixels": 59185}, + }, + { + "score": 0.9987, + "label": "remote", + "mask": {"hash": "c7870600d6", "shape": (480, 640), "white_pixels": 4182}, + }, + { + "score": 0.9995, + "label": "remote", + "mask": {"hash": "ef899a25fd", "shape": (480, 640), "white_pixels": 2275}, + }, + { + "score": 0.9722, + "label": "couch", + "mask": {"hash": "37b8446ac5", "shape": (480, 640), "white_pixels": 172380}, + }, + { + "score": 0.9994, + "label": "cat", + "mask": {"hash": "6a09d3655e", "shape": (480, 640), "white_pixels": 52561}, + }, + ], + ) + + @require_torch + @slow + def test_maskformer(self): + threshold = 0.8 + model_id = "facebook/maskformer-swin-base-ade" + + model = AutoModelForInstanceSegmentation.from_pretrained(model_id) + image_processor = AutoImageProcessor.from_pretrained(model_id) + + image_segmenter = pipeline("image-segmentation", model=model, image_processor=image_processor) + + image = load_dataset("hf-internal-testing/fixtures_ade20k", split="test") + file = image[0]["file"] + outputs = image_segmenter(file, threshold=threshold) + + # Shortening by hashing + for o in outputs: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": 0.9974, + "label": "wall", + "mask": {"hash": "a547b7c062", "shape": (512, 683), "white_pixels": 14252}, + }, + { + "score": 0.949, + "label": "house", + "mask": {"hash": "0da9b7b38f", "shape": (512, 683), "white_pixels": 132177}, + }, + { + "score": 0.9995, + "label": "grass", + "mask": {"hash": "1d07ea0a26", "shape": (512, 683), "white_pixels": 53444}, + }, + { + "score": 0.9976, + "label": "tree", + "mask": {"hash": "6cdc97c7da", "shape": (512, 683), "white_pixels": 7944}, + }, + { + "score": 0.8239, + "label": "plant", + "mask": {"hash": "1ab4ce378f", "shape": (512, 683), "white_pixels": 4136}, + }, + { + "score": 0.9942, + "label": "road, route", + "mask": {"hash": "39c5d17be5", "shape": (512, 683), "white_pixels": 1941}, + }, + { + "score": 1.0, + "label": "sky", + "mask": {"hash": "a3756324a6", "shape": (512, 683), "white_pixels": 135802}, + }, + ], + ) + + @require_torch + @slow + def test_oneformer(self): + image_segmenter = pipeline(model="shi-labs/oneformer_ade20k_swin_tiny") + + image = load_dataset("hf-internal-testing/fixtures_ade20k", split="test") + file = image[0]["file"] + outputs = image_segmenter(file, threshold=0.99) + # Shortening by hashing + for o in outputs: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": 0.9981, + "label": "grass", + "mask": {"hash": "3a92904d4c", "white_pixels": 118131, "shape": (512, 683)}, + }, + { + "score": 0.9992, + "label": "sky", + "mask": {"hash": "fa2300cc9a", "white_pixels": 231565, "shape": (512, 683)}, + }, + ], + ) + + # Different task + outputs = image_segmenter(file, threshold=0.99, subtask="instance") + # Shortening by hashing + for o in outputs: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": 0.9991, + "label": "sky", + "mask": {"hash": "8b1ffad016", "white_pixels": 230566, "shape": (512, 683)}, + }, + { + "score": 0.9981, + "label": "grass", + "mask": {"hash": "9bbdf83d3d", "white_pixels": 119130, "shape": (512, 683)}, + }, + ], + ) + + # Different task + outputs = image_segmenter(file, subtask="semantic") + # Shortening by hashing + for o in outputs: + o["mask"] = mask_to_test_readable(o["mask"]) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + { + "score": None, + "label": "wall", + "mask": {"hash": "897fb20b7f", "white_pixels": 14506, "shape": (512, 683)}, + }, + { + "score": None, + "label": "building", + "mask": {"hash": "f2a68c63e4", "white_pixels": 125019, "shape": (512, 683)}, + }, + { + "score": None, + "label": "sky", + "mask": {"hash": "e0ca3a548e", "white_pixels": 135330, "shape": (512, 683)}, + }, + { + "score": None, + "label": "tree", + "mask": {"hash": "7c9544bcac", "white_pixels": 16263, "shape": (512, 683)}, + }, + { + "score": None, + "label": "road, route", + "mask": {"hash": "2c7704e491", "white_pixels": 2143, "shape": (512, 683)}, + }, + { + "score": None, + "label": "grass", + "mask": {"hash": "bf6c2867e0", "white_pixels": 53040, "shape": (512, 683)}, + }, + { + "score": None, + "label": "plant", + "mask": {"hash": "93c4b7199e", "white_pixels": 3335, "shape": (512, 683)}, + }, + { + "score": None, + "label": "house", + "mask": {"hash": "93ec419ad5", "white_pixels": 60, "shape": (512, 683)}, + }, + ], + ) + + def test_save_load(self): + model_id = "hf-internal-testing/tiny-detr-mobilenetsv3-panoptic" + + model = AutoModelForImageSegmentation.from_pretrained(model_id) + image_processor = AutoImageProcessor.from_pretrained(model_id) + image_segmenter = pipeline( + task="image-segmentation", + model=model, + image_processor=image_processor, + ) + with tempfile.TemporaryDirectory() as tmpdirname: + image_segmenter.save_pretrained(tmpdirname) + pipeline(task="image-segmentation", model=tmpdirname) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_to_image.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_to_image.py new file mode 100644 index 0000000000000000000000000000000000000000..e9110bb692954e6fa108d2186a479c77023e7e25 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_to_image.py @@ -0,0 +1,85 @@ +# Copyright 2023 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 unittest + +from transformers import ( + MODEL_FOR_IMAGE_TO_IMAGE_MAPPING, + AutoImageProcessor, + AutoModelForImageToImage, + ImageToImagePipeline, + is_vision_available, + pipeline, +) +from transformers.testing_utils import ( + is_pipeline_test, + require_torch, + require_vision, + slow, +) + + +if is_vision_available(): + from PIL import Image + +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +@is_pipeline_test +@require_torch +@require_vision +class ImageToImagePipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_IMAGE_TO_IMAGE_MAPPING + examples = [ + Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), + "http://images.cocodataset.org/val2017/000000039769.jpg", + ] + + @require_torch + @require_vision + @slow + def test_pipeline(self): + model_id = "caidas/swin2SR-classical-sr-x2-64" + upscaler = pipeline("image-to-image", model=model_id) + upscaled_list = upscaler(self.examples) + + self.assertEqual(len(upscaled_list), len(self.examples)) + for output in upscaled_list: + self.assertIsInstance(output, Image.Image) + + self.assertEqual(upscaled_list[0].size, (1296, 976)) + self.assertEqual(upscaled_list[1].size, (1296, 976)) + + @require_torch + @require_vision + @slow + def test_pipeline_model_processor(self): + model_id = "caidas/swin2SR-classical-sr-x2-64" + model = AutoModelForImageToImage.from_pretrained(model_id) + image_processor = AutoImageProcessor.from_pretrained(model_id) + + upscaler = ImageToImagePipeline(model=model, image_processor=image_processor) + upscaled_list = upscaler(self.examples) + + self.assertEqual(len(upscaled_list), len(self.examples)) + for output in upscaled_list: + self.assertIsInstance(output, Image.Image) + + self.assertEqual(upscaled_list[0].size, (1296, 976)) + self.assertEqual(upscaled_list[1].size, (1296, 976)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_to_text.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..4f5b5780277bfc61b7c25afee21f5f437b2e72e0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_image_to_text.py @@ -0,0 +1,275 @@ +# Copyright 2022 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 unittest + +import requests + +from transformers import MODEL_FOR_VISION_2_SEQ_MAPPING, TF_MODEL_FOR_VISION_2_SEQ_MAPPING, is_vision_available +from transformers.pipelines import pipeline +from transformers.testing_utils import ( + is_pipeline_test, + is_torch_available, + require_tf, + require_torch, + require_vision, + slow, +) + +from .test_pipelines_common import ANY + + +if is_torch_available(): + from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 +else: + is_torch_greater_or_equal_than_1_11 = False + + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +@is_pipeline_test +@require_vision +class ImageToTextPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING + tf_model_mapping = TF_MODEL_FOR_VISION_2_SEQ_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + pipe = pipeline("image-to-text", model=model, tokenizer=tokenizer, image_processor=processor) + examples = [ + Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), + "./tests/fixtures/tests_samples/COCO/000000039769.png", + ] + return pipe, examples + + def run_pipeline_test(self, pipe, examples): + outputs = pipe(examples) + self.assertEqual( + outputs, + [ + [{"generated_text": ANY(str)}], + [{"generated_text": ANY(str)}], + ], + ) + + @require_tf + def test_small_model_tf(self): + pipe = pipeline("image-to-text", model="hf-internal-testing/tiny-random-vit-gpt2", framework="tf") + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + + outputs = pipe(image) + self.assertEqual( + outputs, + [ + { + "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" + }, + ], + ) + + outputs = pipe([image, image]) + self.assertEqual( + outputs, + [ + [ + { + "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" + } + ], + [ + { + "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" + } + ], + ], + ) + + outputs = pipe(image, max_new_tokens=1) + self.assertEqual( + outputs, + [{"generated_text": "growth"}], + ) + + @require_torch + def test_small_model_pt(self): + pipe = pipeline("image-to-text", model="hf-internal-testing/tiny-random-vit-gpt2") + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + + outputs = pipe(image) + self.assertEqual( + outputs, + [ + { + "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" + }, + ], + ) + + outputs = pipe([image, image]) + self.assertEqual( + outputs, + [ + [ + { + "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" + } + ], + [ + { + "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" + } + ], + ], + ) + + @require_torch + def test_small_model_pt_conditional(self): + pipe = pipeline("image-to-text", model="hf-internal-testing/tiny-random-BlipForConditionalGeneration") + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + prompt = "a photo of" + + outputs = pipe(image, prompt=prompt) + self.assertTrue(outputs[0]["generated_text"].startswith(prompt)) + + @slow + @require_torch + def test_large_model_pt(self): + pipe = pipeline("image-to-text", model="ydshieh/vit-gpt2-coco-en") + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + + outputs = pipe(image) + self.assertEqual(outputs, [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}]) + + outputs = pipe([image, image]) + self.assertEqual( + outputs, + [ + [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}], + [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}], + ], + ) + + @slow + @require_torch + def test_generation_pt_blip(self): + pipe = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base") + url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png" + image = Image.open(requests.get(url, stream=True).raw) + + outputs = pipe(image) + self.assertEqual(outputs, [{"generated_text": "a pink pokemon pokemon with a blue shirt and a blue shirt"}]) + + @slow + @require_torch + def test_generation_pt_git(self): + pipe = pipeline("image-to-text", model="microsoft/git-base-coco") + url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png" + image = Image.open(requests.get(url, stream=True).raw) + + outputs = pipe(image) + self.assertEqual(outputs, [{"generated_text": "a cartoon of a purple character."}]) + + @slow + @require_torch + def test_conditional_generation_pt_blip(self): + pipe = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base") + url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg" + image = Image.open(requests.get(url, stream=True).raw) + + prompt = "a photography of" + + outputs = pipe(image, prompt=prompt) + self.assertEqual(outputs, [{"generated_text": "a photography of a volcano"}]) + + with self.assertRaises(ValueError): + outputs = pipe([image, image], prompt=[prompt, prompt]) + + @slow + @require_torch + def test_conditional_generation_pt_git(self): + pipe = pipeline("image-to-text", model="microsoft/git-base-coco") + url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg" + image = Image.open(requests.get(url, stream=True).raw) + + prompt = "a photo of a" + + outputs = pipe(image, prompt=prompt) + self.assertEqual(outputs, [{"generated_text": "a photo of a tent with a tent and a tent in the background."}]) + + with self.assertRaises(ValueError): + outputs = pipe([image, image], prompt=[prompt, prompt]) + + @unittest.skipIf( + not is_torch_greater_or_equal_than_1_11, reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`." + ) + @slow + @require_torch + def test_conditional_generation_pt_pix2struct(self): + pipe = pipeline("image-to-text", model="google/pix2struct-ai2d-base") + url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg" + image = Image.open(requests.get(url, stream=True).raw) + + prompt = "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud" + + outputs = pipe(image, prompt=prompt) + self.assertEqual(outputs, [{"generated_text": "ash cloud"}]) + + with self.assertRaises(ValueError): + outputs = pipe([image, image], prompt=[prompt, prompt]) + + @slow + @require_tf + def test_large_model_tf(self): + pipe = pipeline("image-to-text", model="ydshieh/vit-gpt2-coco-en", framework="tf") + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + + outputs = pipe(image) + self.assertEqual(outputs, [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}]) + + outputs = pipe([image, image]) + self.assertEqual( + outputs, + [ + [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}], + [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}], + ], + ) + + @slow + @require_torch + def test_conditional_generation_llava(self): + pipe = pipeline("image-to-text", model="llava-hf/bakLlava-v1-hf") + url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg" + image = Image.open(requests.get(url, stream=True).raw) + + prompt = ( + "\nUSER: What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud?\nASSISTANT:" + ) + + outputs = pipe(image, prompt=prompt, generate_kwargs={"max_new_tokens": 200}) + self.assertEqual( + outputs, + [ + { + "generated_text": " \nUSER: What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud?\nASSISTANT: Lava" + } + ], + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_mask_generation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_mask_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a44a5354830f2bc2da0d6d22e9441bfe0b54fc --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_mask_generation.py @@ -0,0 +1,160 @@ +# Copyright 2023 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 unittest +from typing import Dict + +import numpy as np +from huggingface_hub.utils import insecure_hashlib + +from transformers import ( + MODEL_FOR_MASK_GENERATION_MAPPING, + TF_MODEL_FOR_MASK_GENERATION_MAPPING, + is_vision_available, + pipeline, +) +from transformers.pipelines import MaskGenerationPipeline +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_torch, + require_vision, + slow, +) + + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +def hashimage(image: Image) -> str: + m = insecure_hashlib.md5(image.tobytes()) + return m.hexdigest()[:10] + + +def mask_to_test_readable(mask: Image) -> Dict: + npimg = np.array(mask) + shape = npimg.shape + return {"hash": hashimage(mask), "shape": shape} + + +@is_pipeline_test +@require_vision +@require_torch +class MaskGenerationPipelineTests(unittest.TestCase): + model_mapping = dict( + (list(MODEL_FOR_MASK_GENERATION_MAPPING.items()) if MODEL_FOR_MASK_GENERATION_MAPPING else []) + ) + tf_model_mapping = dict( + (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items()) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) + ) + + def get_test_pipeline(self, model, tokenizer, processor): + image_segmenter = MaskGenerationPipeline(model=model, image_processor=processor) + return image_segmenter, [ + "./tests/fixtures/tests_samples/COCO/000000039769.png", + "./tests/fixtures/tests_samples/COCO/000000039769.png", + ] + + # TODO: Implement me @Arthur + def run_pipeline_test(self, mask_generator, examples): + pass + + @require_tf + @unittest.skip("Image segmentation not implemented in TF") + def test_small_model_tf(self): + pass + + @slow + @require_torch + def test_small_model_pt(self): + image_segmenter = pipeline("mask-generation", model="facebook/sam-vit-huge") + + outputs = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg", points_per_batch=256) + + # Shortening by hashing + new_outupt = [] + for i, o in enumerate(outputs["masks"]): + new_outupt += [{"mask": mask_to_test_readable(o), "scores": outputs["scores"][i]}] + + # fmt: off + self.assertEqual( + nested_simplify(new_outupt, decimals=4), + [ + {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0444}, + {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.021}, + {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0167}, + {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0132}, + {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0053}, + {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9967}, + {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.993}, + {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9909}, + {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9879}, + {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9834}, + {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9716}, + {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9612}, + {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9599}, + {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9552}, + {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9532}, + {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9516}, + {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9499}, + {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9483}, + {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9464}, + {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.943}, + {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.943}, + {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9408}, + {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9335}, + {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9326}, + {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9262}, + {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8999}, + {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8986}, + {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8984}, + {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8873}, + {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8871} + ], + ) + # fmt: on + + @require_torch + @slow + def test_threshold(self): + model_id = "facebook/sam-vit-huge" + image_segmenter = pipeline("mask-generation", model=model_id) + + outputs = image_segmenter( + "http://images.cocodataset.org/val2017/000000039769.jpg", pred_iou_thresh=1, points_per_batch=256 + ) + + # Shortening by hashing + new_outupt = [] + for i, o in enumerate(outputs["masks"]): + new_outupt += [{"mask": mask_to_test_readable(o), "scores": outputs["scores"][i]}] + + self.assertEqual( + nested_simplify(new_outupt, decimals=4), + [ + {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.0444}, + {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.0210}, + {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.0167}, + {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.0132}, + {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.0053}, + ], + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_object_detection.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_object_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..4196db36d765c809e91d744cb5de557790006e3e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_object_detection.py @@ -0,0 +1,275 @@ +# Copyright 2021 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 unittest + +from transformers import ( + MODEL_FOR_OBJECT_DETECTION_MAPPING, + AutoFeatureExtractor, + AutoModelForObjectDetection, + ObjectDetectionPipeline, + is_vision_available, + pipeline, +) +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_pytesseract, + require_tf, + require_timm, + require_torch, + require_vision, + slow, +) + +from .test_pipelines_common import ANY + + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +@is_pipeline_test +@require_vision +@require_timm +@require_torch +class ObjectDetectionPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + object_detector = ObjectDetectionPipeline(model=model, image_processor=processor) + return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] + + def run_pipeline_test(self, object_detector, examples): + outputs = object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png", threshold=0.0) + + self.assertGreater(len(outputs), 0) + for detected_object in outputs: + self.assertEqual( + detected_object, + { + "score": ANY(float), + "label": ANY(str), + "box": {"xmin": ANY(int), "ymin": ANY(int), "xmax": ANY(int), "ymax": ANY(int)}, + }, + ) + + import datasets + + dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test") + + batch = [ + Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), + "http://images.cocodataset.org/val2017/000000039769.jpg", + # RGBA + dataset[0]["file"], + # LA + dataset[1]["file"], + # L + dataset[2]["file"], + ] + batch_outputs = object_detector(batch, threshold=0.0) + + self.assertEqual(len(batch), len(batch_outputs)) + for outputs in batch_outputs: + self.assertGreater(len(outputs), 0) + for detected_object in outputs: + self.assertEqual( + detected_object, + { + "score": ANY(float), + "label": ANY(str), + "box": {"xmin": ANY(int), "ymin": ANY(int), "xmax": ANY(int), "ymax": ANY(int)}, + }, + ) + + @require_tf + @unittest.skip("Object detection not implemented in TF") + def test_small_model_tf(self): + pass + + @require_torch + def test_small_model_pt(self): + model_id = "hf-internal-testing/tiny-detr-mobilenetsv3" + + model = AutoModelForObjectDetection.from_pretrained(model_id) + feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + object_detector = ObjectDetectionPipeline(model=model, feature_extractor=feature_extractor) + + outputs = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg", threshold=0.0) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, + {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, + ], + ) + + outputs = object_detector( + [ + "http://images.cocodataset.org/val2017/000000039769.jpg", + "http://images.cocodataset.org/val2017/000000039769.jpg", + ], + threshold=0.0, + ) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, + {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, + ], + [ + {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, + {"score": 0.3376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}}, + ], + ], + ) + + @require_torch + @slow + def test_large_model_pt(self): + model_id = "facebook/detr-resnet-50" + + model = AutoModelForObjectDetection.from_pretrained(model_id) + feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + object_detector = ObjectDetectionPipeline(model=model, feature_extractor=feature_extractor) + + outputs = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg") + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, + {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, + {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, + {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, + {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, + ], + ) + + outputs = object_detector( + [ + "http://images.cocodataset.org/val2017/000000039769.jpg", + "http://images.cocodataset.org/val2017/000000039769.jpg", + ] + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, + {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, + {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, + {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, + {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, + ], + [ + {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, + {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, + {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, + {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, + {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, + ], + ], + ) + + @require_torch + @slow + def test_integration_torch_object_detection(self): + model_id = "facebook/detr-resnet-50" + + object_detector = pipeline("object-detection", model=model_id) + + outputs = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg") + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, + {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, + {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, + {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, + {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, + ], + ) + + outputs = object_detector( + [ + "http://images.cocodataset.org/val2017/000000039769.jpg", + "http://images.cocodataset.org/val2017/000000039769.jpg", + ] + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, + {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, + {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, + {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, + {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, + ], + [ + {"score": 0.9982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}}, + {"score": 0.9960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}}, + {"score": 0.9955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}}, + {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, + {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, + ], + ], + ) + + @require_torch + @slow + def test_threshold(self): + threshold = 0.9985 + model_id = "facebook/detr-resnet-50" + + object_detector = pipeline("object-detection", model=model_id) + + outputs = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg", threshold=threshold) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}}, + {"score": 0.9987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}}, + ], + ) + + @require_torch + @require_pytesseract + @slow + def test_layoutlm(self): + model_id = "Narsil/layoutlmv3-finetuned-funsd" + threshold = 0.9993 + + object_detector = pipeline("object-detection", model=model_id, threshold=threshold) + + outputs = object_detector( + "https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png" + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.9993, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}}, + {"score": 0.9993, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}}, + ], + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_question_answering.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..f7683aec15c32d4f52d400007995f3e57141af4f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_question_answering.py @@ -0,0 +1,501 @@ +# 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 unittest + +from transformers import ( + MODEL_FOR_QUESTION_ANSWERING_MAPPING, + TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, + LxmertConfig, + QuestionAnsweringPipeline, +) +from transformers.data.processors.squad import SquadExample +from transformers.pipelines import QuestionAnsweringArgumentHandler, pipeline +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_torch, + require_torch_or_tf, + slow, +) + +from .test_pipelines_common import ANY + + +# These 2 model types require different inputs than those of the usual text models. +_TO_SKIP = {"LayoutLMv2Config", "LayoutLMv3Config"} + + +@is_pipeline_test +class QAPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_QUESTION_ANSWERING_MAPPING + tf_model_mapping = TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING + + if model_mapping is not None: + model_mapping = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} + if tf_model_mapping is not None: + tf_model_mapping = { + config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP + } + + def get_test_pipeline(self, model, tokenizer, processor): + if isinstance(model.config, LxmertConfig): + # This is an bimodal model, we need to find a more consistent way + # to switch on those models. + return None, None + question_answerer = QuestionAnsweringPipeline(model, tokenizer) + + examples = [ + {"question": "Where was HuggingFace founded ?", "context": "HuggingFace was founded in Paris."}, + {"question": "In what field is HuggingFace ?", "context": "HuggingFace is an AI startup."}, + ] + return question_answerer, examples + + def run_pipeline_test(self, question_answerer, _): + outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris." + ) + self.assertEqual(outputs, {"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)}) + outputs = question_answerer( + question="Where was HuggingFace founded ?", + context="HuggingFace was founded in Paris.", + handle_impossible_answer=True, + ) + self.assertEqual(outputs, {"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)}) + + outputs = question_answerer( + question=["In what field is HuggingFace working ?", "In what field is HuggingFace working ?"], + context="HuggingFace was founded in Paris.", + ) + self.assertEqual( + outputs, + [ + {"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)}, + {"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)}, + ], + ) + + outputs = question_answerer( + question=["What field is HuggingFace working ?", "In what field is HuggingFace ?"], + context=[ + "HuggingFace is a startup based in New-York", + "HuggingFace is a startup founded in Paris", + ], + ) + self.assertEqual( + outputs, + [ + {"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)}, + {"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)}, + ], + ) + + with self.assertRaises(ValueError): + question_answerer(question="", context="HuggingFace was founded in Paris.") + with self.assertRaises(ValueError): + question_answerer(question=None, context="HuggingFace was founded in Paris.") + with self.assertRaises(ValueError): + question_answerer(question="In what field is HuggingFace working ?", context="") + with self.assertRaises(ValueError): + question_answerer(question="In what field is HuggingFace working ?", context=None) + + outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris.", top_k=20 + ) + self.assertEqual( + outputs, [{"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)} for i in range(20)] + ) + + # Very long context require multiple features + outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris." * 20 + ) + self.assertEqual(outputs, {"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)}) + + # Using batch is OK + if question_answerer.tokenizer.pad_token_id is None: + question_answerer.tokenizer.pad_token_id = question_answerer.model.config.eos_token_id + new_outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris." * 20, batch_size=2 + ) + self.assertEqual(new_outputs, {"answer": ANY(str), "start": ANY(int), "end": ANY(int), "score": ANY(float)}) + self.assertEqual(nested_simplify(outputs), nested_simplify(new_outputs)) + + @require_torch + def test_small_model_pt(self): + question_answerer = pipeline( + "question-answering", model="sshleifer/tiny-distilbert-base-cased-distilled-squad" + ) + + outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris." + ) + + self.assertEqual(nested_simplify(outputs), {"score": 0.01, "start": 0, "end": 11, "answer": "HuggingFace"}) + + @require_torch + def test_small_model_pt_iterator(self): + # https://github.com/huggingface/transformers/issues/18510 + pipe = pipeline(model="sshleifer/tiny-distilbert-base-cased-distilled-squad", batch_size=16, framework="pt") + + def data(): + for i in range(10): + yield {"question": "Where was HuggingFace founded ?", "context": "HuggingFace was founded in Paris."} + + for outputs in pipe(data()): + self.assertEqual(nested_simplify(outputs), {"score": 0.01, "start": 0, "end": 11, "answer": "HuggingFace"}) + + @require_torch + def test_small_model_pt_softmax_trick(self): + question_answerer = pipeline( + "question-answering", model="sshleifer/tiny-distilbert-base-cased-distilled-squad" + ) + + real_postprocess = question_answerer.postprocess + + # Tweak start and stop to make sure we encounter the softmax logits + # bug. + def ensure_large_logits_postprocess( + model_outputs, + top_k=1, + handle_impossible_answer=False, + max_answer_len=15, + ): + for output in model_outputs: + output["start"] = output["start"] * 1e6 + output["end"] = output["end"] * 1e6 + return real_postprocess( + model_outputs, + top_k=top_k, + handle_impossible_answer=handle_impossible_answer, + max_answer_len=max_answer_len, + ) + + question_answerer.postprocess = ensure_large_logits_postprocess + + outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris." + ) + + self.assertEqual(nested_simplify(outputs), {"score": 0.028, "start": 0, "end": 11, "answer": "HuggingFace"}) + + @slow + @require_torch + def test_small_model_japanese(self): + question_answerer = pipeline( + "question-answering", + model="KoichiYasuoka/deberta-base-japanese-aozora-ud-head", + ) + output = question_answerer(question="国語", context="全学年にわたって小学校の国語の教科書に挿し絵が用いられている") # fmt: skip + + # Wrong answer, the whole text is identified as one "word" since the tokenizer does not include + # a pretokenizer + self.assertEqual(nested_simplify(output),{"score": 1.0, "start": 0, "end": 30, "answer": "全学年にわたって小学校の国語の教科書に挿し絵が用いられている"}) # fmt: skip + + # Disable word alignment + output = question_answerer(question="国語", context="全学年にわたって小学校の国語の教科書に挿し絵が用いられている", align_to_words=False) # fmt: skip + self.assertEqual( + nested_simplify(output), + {"score": 1.0, "start": 15, "end": 18, "answer": "教科書"}, + ) + + @slow + @require_torch + def test_small_model_long_context_cls_slow(self): + question_answerer = pipeline( + "question-answering", + model="deepset/roberta-base-squad2", + handle_impossible_answer=True, + max_seq_length=512, + ) + outputs = question_answerer( + question="What country is Paris the capital of?", + context="""London is the capital and largest city of England and the United Kingdom. It stands on the River Thames in south-east England at the head of a 50-mile (80 km) estuary down to the North Sea, and has been a major settlement for two millennia. The City of London, its ancient core and financial centre, was founded by the Romans as Londinium and retains boundaries close to its medieval ones. Since the 19th century, \"London\" has also referred to the metropolis around this core, historically split between the counties of Middlesex, Essex, Surrey, Kent, and Hertfordshire, which largely comprises Greater London, governed by the Greater London Authority. The City of Westminster, to the west of the City of London, has for centuries held the national government and parliament. As one of the world's global cities, London exerts strong influence on its arts, commerce, education, entertainment, fashion, finance, health care, media, tourism, and communications, and has sometimes been called the capital of the world. Its GDP (€801.66 billion in 2017) makes it the biggest urban economy in Europe, and it is one of the major financial centres in the world. In 2019 it had the second-highest number of ultra high-net-worth individuals in Europe after Paris and the second-highest number of billionaires in Europe after Moscow. As of 2021, London has the most millionaires of any city. With Europe's largest concentration of higher education institutions, it includes Imperial College London in natural and applied sciences, the London School of Economics in social sciences, and the comprehensive University College London. The city is home to the most 5-star hotels of any city in the world. In 2012, London became the first city to host three Summer Olympic Games. London is the capital and largest city of England and the United Kingdom. It stands on the River Thames in south-east England at the head of a 50-mile (80 km) estuary down to the North Sea, and has been a major settlement for two millennia. The City of London, its ancient core and financial centre, was founded by the Romans as Londinium and retains boundaries close to its medieval ones. Since the 19th century, \"London\" has also referred to the metropolis around this core, historically split between the counties of Middlesex, Essex, Surrey, Kent, and Hertfordshire, which largely comprises Greater London, governed by the Greater London Authority. The City of Westminster, to the west of the City of London, has for centuries held the national government and parliament. As one of the world's global cities, London exerts strong influence on its arts, commerce, education, entertainment, fashion, finance, health care, media, tourism, and communications, and has sometimes been called the capital of the world. Its GDP (€801.66 billion in 2017) makes it the biggest urban economy in Europe, and it is one of the major financial centres in the world. In 2019 it had the second-highest number of ultra high-net-worth individuals in Europe after Paris and the second-highest number of billionaires in Europe after Moscow. As of 2021, London has the most millionaires of any city. With Europe's largest concentration of higher education institutions, it includes Imperial College London in natural and applied sciences, the London School of Economics in social sciences, and the comprehensive University College London. The city is home to the most 5-star hotels of any city in the world. In 2012, London became the first city to host three Summer Olympic Games.""", + ) + self.assertEqual(nested_simplify(outputs), {"score": 0.988, "start": 0, "end": 0, "answer": ""}) + + @require_tf + def test_small_model_tf(self): + question_answerer = pipeline( + "question-answering", model="sshleifer/tiny-distilbert-base-cased-distilled-squad", framework="tf" + ) + outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris." + ) + + self.assertEqual(nested_simplify(outputs), {"score": 0.011, "start": 0, "end": 11, "answer": "HuggingFace"}) + + @slow + @require_torch + def test_large_model_pt(self): + question_answerer = pipeline( + "question-answering", + ) + outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris." + ) + + self.assertEqual(nested_simplify(outputs), {"score": 0.979, "start": 27, "end": 32, "answer": "Paris"}) + + @slow + @require_torch + def test_large_model_issue(self): + qa_pipeline = pipeline( + "question-answering", + model="mrm8488/bert-multi-cased-finetuned-xquadv1", + ) + outputs = qa_pipeline( + { + "context": ( + "Yes Bank founder Rana Kapoor has approached the Bombay High Court, challenging a special court's" + " order from August this year that had remanded him in police custody for a week in a multi-crore" + " loan fraud case. Kapoor, who is currently lodged in Taloja Jail, is an accused in the loan fraud" + " case and some related matters being probed by the CBI and Enforcement Directorate. A single" + " bench presided over by Justice S K Shinde on Tuesday posted the plea for further hearing on" + " October 14. In his plea filed through advocate Vijay Agarwal, Kapoor claimed that the special" + " court's order permitting the CBI's request for police custody on August 14 was illegal and in" + " breach of the due process of law. Therefore, his police custody and subsequent judicial custody" + " in the case were all illegal. Kapoor has urged the High Court to quash and set aside the special" + " court's order dated August 14. As per his plea, in August this year, the CBI had moved two" + " applications before the special court, one seeking permission to arrest Kapoor, who was already" + " in judicial custody at the time in another case, and the other, seeking his police custody." + " While the special court refused to grant permission to the CBI to arrest Kapoor, it granted the" + " central agency's plea for his custody. Kapoor, however, said in his plea that before filing an" + " application for his arrest, the CBI had not followed the process of issuing him a notice under" + " Section 41 of the CrPC for appearance before it. He further said that the CBI had not taken" + " prior sanction as mandated under section 17 A of the Prevention of Corruption Act for" + " prosecuting him. The special court, however, had said in its order at the time that as Kapoor" + " was already in judicial custody in another case and was not a free man the procedure mandated" + " under Section 41 of the CrPC need not have been adhered to as far as issuing a prior notice of" + " appearance was concerned. ADVERTISING It had also said that case records showed that the" + " investigating officer had taken an approval from a managing director of Yes Bank before" + " beginning the proceedings against Kapoor and such a permission was a valid sanction. However," + " Kapoor in his plea said that the above order was bad in law and sought that it be quashed and" + " set aside. The law mandated that if initial action was not in consonance with legal procedures," + " then all subsequent actions must be held as illegal, he said, urging the High Court to declare" + " the CBI remand and custody and all subsequent proceedings including the further custody as" + " illegal and void ab-initio. In a separate plea before the High Court, Kapoor's daughter Rakhee" + " Kapoor-Tandon has sought exemption from in-person appearance before a special PMLA court. Rakhee" + " has stated that she is a resident of the United Kingdom and is unable to travel to India owing" + " to restrictions imposed due to the COVID-19 pandemic. According to the CBI, in the present case," + " Kapoor had obtained a gratification or pecuniary advantage of ₹ 307 crore, and thereby caused" + " Yes Bank a loss of ₹ 1,800 crore by extending credit facilities to Avantha Group, when it was" + " not eligible for the same" + ), + "question": "Is this person invovled in fraud?", + } + ) + self.assertEqual( + nested_simplify(outputs), + {"answer": "an accused in the loan fraud case", "end": 294, "score": 0.001, "start": 261}, + ) + + @slow + @require_torch + def test_large_model_course(self): + question_answerer = pipeline("question-answering") + long_context = """ +🤗 Transformers: State of the Art NLP + +🤗 Transformers provides thousands of pretrained models to perform tasks on texts such as classification, information extraction, +question answering, summarization, translation, text generation and more in over 100 languages. +Its aim is to make cutting-edge NLP easier to use for everyone. + +🤗 Transformers provides APIs to quickly download and use those pretrained models on a given text, fine-tune them on your own datasets and +then share them with the community on our model hub. At the same time, each python module defining an architecture is fully standalone and +can be modified to enable quick research experiments. + +Why should I use transformers? + +1. Easy-to-use state-of-the-art models: + - High performance on NLU and NLG tasks. + - Low barrier to entry for educators and practitioners. + - Few user-facing abstractions with just three classes to learn. + - A unified API for using all our pretrained models. + - Lower compute costs, smaller carbon footprint: + +2. Researchers can share trained models instead of always retraining. + - Practitioners can reduce compute time and production costs. + - Dozens of architectures with over 10,000 pretrained models, some in more than 100 languages. + +3. Choose the right framework for every part of a model's lifetime: + - Train state-of-the-art models in 3 lines of code. + - Move a single model between TF2.0/PyTorch frameworks at will. + - Seamlessly pick the right framework for training, evaluation and production. + +4. Easily customize a model or an example to your needs: + - We provide examples for each architecture to reproduce the results published by its original authors. + - Model internals are exposed as consistently as possible. + - Model files can be used independently of the library for quick experiments. + +🤗 Transformers is backed by the three most popular deep learning libraries — Jax, PyTorch and TensorFlow — with a seamless integration +between them. It's straightforward to train your models with one before loading them for inference with the other. +""" + question = "Which deep learning libraries back 🤗 Transformers?" + outputs = question_answerer(question=question, context=long_context) + + self.assertEqual( + nested_simplify(outputs), + {"answer": "Jax, PyTorch and TensorFlow", "end": 1919, "score": 0.971, "start": 1892}, + ) + + @slow + @require_tf + def test_large_model_tf(self): + question_answerer = pipeline("question-answering", framework="tf") + outputs = question_answerer( + question="Where was HuggingFace founded ?", context="HuggingFace was founded in Paris." + ) + + self.assertEqual(nested_simplify(outputs), {"score": 0.979, "start": 27, "end": 32, "answer": "Paris"}) + + +@require_torch_or_tf +class QuestionAnsweringArgumentHandlerTests(unittest.TestCase): + def test_argument_handler(self): + qa = QuestionAnsweringArgumentHandler() + + Q = "Where was HuggingFace founded ?" + C = "HuggingFace was founded in Paris" + + normalized = qa(Q, C) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 1) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa(question=Q, context=C) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 1) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa(question=Q, context=C) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 1) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa(question=[Q, Q], context=C) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 2) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa({"question": Q, "context": C}) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 1) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa([{"question": Q, "context": C}]) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 1) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa([{"question": Q, "context": C}, {"question": Q, "context": C}]) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 2) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa(X={"question": Q, "context": C}) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 1) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa(X=[{"question": Q, "context": C}]) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 1) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + normalized = qa(data={"question": Q, "context": C}) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 1) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + def test_argument_handler_error_handling(self): + qa = QuestionAnsweringArgumentHandler() + + Q = "Where was HuggingFace founded ?" + C = "HuggingFace was founded in Paris" + + with self.assertRaises(KeyError): + qa({"context": C}) + with self.assertRaises(KeyError): + qa({"question": Q}) + with self.assertRaises(KeyError): + qa([{"context": C}]) + with self.assertRaises(ValueError): + qa(None, C) + with self.assertRaises(ValueError): + qa("", C) + with self.assertRaises(ValueError): + qa(Q, None) + with self.assertRaises(ValueError): + qa(Q, "") + + with self.assertRaises(ValueError): + qa(question=None, context=C) + with self.assertRaises(ValueError): + qa(question="", context=C) + with self.assertRaises(ValueError): + qa(question=Q, context=None) + with self.assertRaises(ValueError): + qa(question=Q, context="") + + with self.assertRaises(ValueError): + qa({"question": None, "context": C}) + with self.assertRaises(ValueError): + qa({"question": "", "context": C}) + with self.assertRaises(ValueError): + qa({"question": Q, "context": None}) + with self.assertRaises(ValueError): + qa({"question": Q, "context": ""}) + + with self.assertRaises(ValueError): + qa([{"question": Q, "context": C}, {"question": None, "context": C}]) + with self.assertRaises(ValueError): + qa([{"question": Q, "context": C}, {"question": "", "context": C}]) + + with self.assertRaises(ValueError): + qa([{"question": Q, "context": C}, {"question": Q, "context": None}]) + with self.assertRaises(ValueError): + qa([{"question": Q, "context": C}, {"question": Q, "context": ""}]) + + with self.assertRaises(ValueError): + qa(question={"This": "Is weird"}, context="This is a context") + + with self.assertRaises(ValueError): + qa(question=[Q, Q], context=[C, C, C]) + + with self.assertRaises(ValueError): + qa(question=[Q, Q, Q], context=[C, C]) + + def test_argument_handler_old_format(self): + qa = QuestionAnsweringArgumentHandler() + + Q = "Where was HuggingFace founded ?" + C = "HuggingFace was founded in Paris" + # Backward compatibility for this + normalized = qa(question=[Q, Q], context=[C, C]) + self.assertEqual(type(normalized), list) + self.assertEqual(len(normalized), 2) + self.assertEqual({type(el) for el in normalized}, {SquadExample}) + + def test_argument_handler_error_handling_odd(self): + qa = QuestionAnsweringArgumentHandler() + with self.assertRaises(ValueError): + qa(None) + + with self.assertRaises(ValueError): + qa(Y=None) + + with self.assertRaises(ValueError): + qa(1) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_summarization.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_summarization.py new file mode 100644 index 0000000000000000000000000000000000000000..7b75842081c530600d63ef8949bcd83204865745 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_summarization.py @@ -0,0 +1,152 @@ +# 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 unittest + +from transformers import ( + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + SummarizationPipeline, + TFPreTrainedModel, + pipeline, +) +from transformers.testing_utils import get_gpu_count, is_pipeline_test, require_tf, require_torch, slow, torch_device +from transformers.tokenization_utils import TruncationStrategy + +from .test_pipelines_common import ANY + + +@is_pipeline_test +class SummarizationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + tf_model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + summarizer = SummarizationPipeline(model=model, tokenizer=tokenizer) + return summarizer, ["(CNN)The Palestinian Authority officially became", "Some other text"] + + def run_pipeline_test(self, summarizer, _): + model = summarizer.model + + outputs = summarizer("(CNN)The Palestinian Authority officially became") + self.assertEqual(outputs, [{"summary_text": ANY(str)}]) + + outputs = summarizer( + "(CNN)The Palestinian Authority officially became ", + num_beams=2, + min_length=2, + max_length=5, + ) + self.assertEqual(outputs, [{"summary_text": ANY(str)}]) + + # Some models (Switch Transformers, LED, T5, LongT5, etc) can handle long sequences. + model_can_handle_longer_seq = [ + "SwitchTransformersConfig", + "T5Config", + "LongT5Config", + "LEDConfig", + "PegasusXConfig", + "FSMTConfig", + "M2M100Config", + "ProphetNetConfig", # positional embeddings up to a fixed maximum size (otherwise clamping the values) + ] + if model.config.__class__.__name__ not in model_can_handle_longer_seq: + # Too long and exception is expected. + # For TF models, if the weights are initialized in GPU context, we won't get expected index error from + # the embedding layer. + if not ( + isinstance(model, TFPreTrainedModel) + and get_gpu_count() > 0 + and len(summarizer.model.trainable_weights) > 0 + ): + with self.assertRaises(Exception): + outputs = summarizer("This " * 1000) + outputs = summarizer("This " * 1000, truncation=TruncationStrategy.ONLY_FIRST) + + @require_torch + def test_small_model_pt(self): + summarizer = pipeline(task="summarization", model="sshleifer/tiny-mbart", framework="pt") + outputs = summarizer("This is a small test") + self.assertEqual( + outputs, + [ + { + "summary_text": "เข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไป" + } + ], + ) + + @require_tf + def test_small_model_tf(self): + summarizer = pipeline(task="summarization", model="sshleifer/tiny-mbart", framework="tf") + outputs = summarizer("This is a small test") + self.assertEqual( + outputs, + [ + { + "summary_text": "เข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไปเข้าไป" + } + ], + ) + + @require_torch + @slow + def test_integration_torch_summarization(self): + summarizer = pipeline(task="summarization", device=torch_device) + cnn_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." + ) + expected_cnn_summary = ( + " The Palestinian Authority becomes the 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 court . Rights group Human Rights Watch welcomes the move," + " says governments seeking to penalize Palestine should end pressure ." + ) + result = summarizer(cnn_article) + self.assertEqual(result[0]["summary_text"], expected_cnn_summary) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_table_question_answering.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_table_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..a30763fc096d7e4225a98bc5dc70a231ef8e5e67 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_table_question_answering.py @@ -0,0 +1,672 @@ +# 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 unittest + +from transformers import ( + MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING, + AutoModelForTableQuestionAnswering, + AutoTokenizer, + TableQuestionAnsweringPipeline, + TFAutoModelForTableQuestionAnswering, + is_torch_available, + pipeline, +) +from transformers.testing_utils import ( + is_pipeline_test, + require_pandas, + require_tensorflow_probability, + require_tf, + require_torch, + slow, +) + + +if is_torch_available(): + from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_12 +else: + is_torch_greater_or_equal_than_1_12 = False + + +@is_pipeline_test +class TQAPipelineTests(unittest.TestCase): + # Putting it there for consistency, but TQA do not have fast tokenizer + # which are needed to generate automatic tests + model_mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING + + @require_tensorflow_probability + @require_pandas + @require_tf + @require_torch + def test_small_model_tf(self): + model_id = "lysandre/tiny-tapas-random-wtq" + model = TFAutoModelForTableQuestionAnswering.from_pretrained(model_id, from_pt=True) + tokenizer = AutoTokenizer.from_pretrained(model_id) + self.assertIsInstance(model.config.aggregation_labels, dict) + self.assertIsInstance(model.config.no_aggregation_label_index, int) + + table_querier = TableQuestionAnsweringPipeline(model=model, tokenizer=tokenizer) + outputs = table_querier( + table={ + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + query="how many movies has george clooney played in?", + ) + self.assertEqual( + outputs, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + ) + outputs = table_querier( + table={ + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + query=["how many movies has george clooney played in?", "how old is he?", "what's his date of birth?"], + ) + self.assertEqual( + outputs, + [ + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + ], + ) + outputs = table_querier( + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + query=[ + "What repository has the largest number of stars?", + "Given that the numbers of stars defines if a repository is active, what repository is the most" + " active?", + "What is the number of repositories?", + "What is the average number of stars?", + "What is the total amount of stars?", + ], + ) + self.assertEqual( + outputs, + [ + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + ], + ) + + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table=None) + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table="") + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table={}) + with self.assertRaises(ValueError): + table_querier( + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + } + ) + with self.assertRaises(ValueError): + table_querier( + query="", + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + ) + with self.assertRaises(ValueError): + table_querier( + query=None, + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + ) + + @unittest.skipIf(not is_torch_greater_or_equal_than_1_12, reason="Tapas is only available in torch v1.12+") + @require_torch + def test_small_model_pt(self): + model_id = "lysandre/tiny-tapas-random-wtq" + model = AutoModelForTableQuestionAnswering.from_pretrained(model_id) + tokenizer = AutoTokenizer.from_pretrained(model_id) + self.assertIsInstance(model.config.aggregation_labels, dict) + self.assertIsInstance(model.config.no_aggregation_label_index, int) + + table_querier = TableQuestionAnsweringPipeline(model=model, tokenizer=tokenizer) + outputs = table_querier( + table={ + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + query="how many movies has george clooney played in?", + ) + self.assertEqual( + outputs, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + ) + outputs = table_querier( + table={ + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + query=["how many movies has george clooney played in?", "how old is he?", "what's his date of birth?"], + ) + self.assertEqual( + outputs, + [ + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + ], + ) + outputs = table_querier( + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + query=[ + "What repository has the largest number of stars?", + "Given that the numbers of stars defines if a repository is active, what repository is the most" + " active?", + "What is the number of repositories?", + "What is the average number of stars?", + "What is the total amount of stars?", + ], + ) + self.assertEqual( + outputs, + [ + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + {"answer": "AVERAGE > ", "coordinates": [], "cells": [], "aggregator": "AVERAGE"}, + ], + ) + + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table=None) + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table="") + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table={}) + with self.assertRaises(ValueError): + table_querier( + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + } + ) + with self.assertRaises(ValueError): + table_querier( + query="", + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + ) + with self.assertRaises(ValueError): + table_querier( + query=None, + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + ) + + @unittest.skipIf(not is_torch_greater_or_equal_than_1_12, reason="Tapas is only available in torch v1.12+") + @require_torch + def test_slow_tokenizer_sqa_pt(self): + model_id = "lysandre/tiny-tapas-random-sqa" + model = AutoModelForTableQuestionAnswering.from_pretrained(model_id) + tokenizer = AutoTokenizer.from_pretrained(model_id) + table_querier = TableQuestionAnsweringPipeline(model=model, tokenizer=tokenizer) + + inputs = { + "table": { + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + "query": ["how many movies has george clooney played in?", "how old is he?", "what's his date of birth?"], + } + sequential_outputs = table_querier(**inputs, sequential=True) + batch_outputs = table_querier(**inputs, sequential=False) + + self.assertEqual(len(sequential_outputs), 3) + self.assertEqual(len(batch_outputs), 3) + self.assertEqual(sequential_outputs[0], batch_outputs[0]) + self.assertNotEqual(sequential_outputs[1], batch_outputs[1]) + # self.assertNotEqual(sequential_outputs[2], batch_outputs[2]) + + table_querier = TableQuestionAnsweringPipeline(model=model, tokenizer=tokenizer) + outputs = table_querier( + table={ + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + query="how many movies has george clooney played in?", + ) + self.assertEqual( + outputs, + {"answer": "7 february 1967", "coordinates": [(0, 3)], "cells": ["7 february 1967"]}, + ) + outputs = table_querier( + table={ + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + query=["how many movies has george clooney played in?", "how old is he?", "what's his date of birth?"], + ) + self.assertEqual( + outputs, + [ + {"answer": "7 february 1967", "coordinates": [(0, 3)], "cells": ["7 february 1967"]}, + {"answer": "7 february 1967", "coordinates": [(0, 3)], "cells": ["7 february 1967"]}, + {"answer": "7 february 1967", "coordinates": [(0, 3)], "cells": ["7 february 1967"]}, + ], + ) + outputs = table_querier( + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + query=[ + "What repository has the largest number of stars?", + "Given that the numbers of stars defines if a repository is active, what repository is the most" + " active?", + "What is the number of repositories?", + "What is the average number of stars?", + "What is the total amount of stars?", + ], + ) + self.assertEqual( + outputs, + [ + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + ], + ) + + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table=None) + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table="") + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table={}) + with self.assertRaises(ValueError): + table_querier( + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + } + ) + with self.assertRaises(ValueError): + table_querier( + query="", + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + ) + with self.assertRaises(ValueError): + table_querier( + query=None, + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + ) + + @require_tf + @require_tensorflow_probability + @require_pandas + @require_torch + def test_slow_tokenizer_sqa_tf(self): + model_id = "lysandre/tiny-tapas-random-sqa" + model = TFAutoModelForTableQuestionAnswering.from_pretrained(model_id, from_pt=True) + tokenizer = AutoTokenizer.from_pretrained(model_id) + table_querier = TableQuestionAnsweringPipeline(model=model, tokenizer=tokenizer) + + inputs = { + "table": { + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + "query": ["how many movies has george clooney played in?", "how old is he?", "what's his date of birth?"], + } + sequential_outputs = table_querier(**inputs, sequential=True) + batch_outputs = table_querier(**inputs, sequential=False) + + self.assertEqual(len(sequential_outputs), 3) + self.assertEqual(len(batch_outputs), 3) + self.assertEqual(sequential_outputs[0], batch_outputs[0]) + self.assertNotEqual(sequential_outputs[1], batch_outputs[1]) + # self.assertNotEqual(sequential_outputs[2], batch_outputs[2]) + + table_querier = TableQuestionAnsweringPipeline(model=model, tokenizer=tokenizer) + outputs = table_querier( + table={ + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + query="how many movies has george clooney played in?", + ) + self.assertEqual( + outputs, + {"answer": "7 february 1967", "coordinates": [(0, 3)], "cells": ["7 february 1967"]}, + ) + outputs = table_querier( + table={ + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + }, + query=["how many movies has george clooney played in?", "how old is he?", "what's his date of birth?"], + ) + self.assertEqual( + outputs, + [ + {"answer": "7 february 1967", "coordinates": [(0, 3)], "cells": ["7 february 1967"]}, + {"answer": "7 february 1967", "coordinates": [(0, 3)], "cells": ["7 february 1967"]}, + {"answer": "7 february 1967", "coordinates": [(0, 3)], "cells": ["7 february 1967"]}, + ], + ) + outputs = table_querier( + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + query=[ + "What repository has the largest number of stars?", + "Given that the numbers of stars defines if a repository is active, what repository is the most" + " active?", + "What is the number of repositories?", + "What is the average number of stars?", + "What is the total amount of stars?", + ], + ) + self.assertEqual( + outputs, + [ + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + {"answer": "Python, Python", "coordinates": [(0, 3), (1, 3)], "cells": ["Python", "Python"]}, + ], + ) + + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table=None) + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table="") + with self.assertRaises(ValueError): + table_querier(query="What does it do with empty context ?", table={}) + with self.assertRaises(ValueError): + table_querier( + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + } + ) + with self.assertRaises(ValueError): + table_querier( + query="", + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + ) + with self.assertRaises(ValueError): + table_querier( + query=None, + table={ + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + }, + ) + + @unittest.skipIf(not is_torch_greater_or_equal_than_1_12, reason="Tapas is only available in torch v1.12+") + @slow + @require_torch + def test_integration_wtq_pt(self): + table_querier = pipeline("table-question-answering") + + data = { + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + } + queries = [ + "What repository has the largest number of stars?", + "Given that the numbers of stars defines if a repository is active, what repository is the most active?", + "What is the number of repositories?", + "What is the average number of stars?", + "What is the total amount of stars?", + ] + + results = table_querier(data, queries) + + expected_results = [ + {"answer": "Transformers", "coordinates": [(0, 0)], "cells": ["Transformers"], "aggregator": "NONE"}, + {"answer": "Transformers", "coordinates": [(0, 0)], "cells": ["Transformers"], "aggregator": "NONE"}, + { + "answer": "COUNT > Transformers, Datasets, Tokenizers", + "coordinates": [(0, 0), (1, 0), (2, 0)], + "cells": ["Transformers", "Datasets", "Tokenizers"], + "aggregator": "COUNT", + }, + { + "answer": "AVERAGE > 36542, 4512, 3934", + "coordinates": [(0, 1), (1, 1), (2, 1)], + "cells": ["36542", "4512", "3934"], + "aggregator": "AVERAGE", + }, + { + "answer": "SUM > 36542, 4512, 3934", + "coordinates": [(0, 1), (1, 1), (2, 1)], + "cells": ["36542", "4512", "3934"], + "aggregator": "SUM", + }, + ] + self.assertListEqual(results, expected_results) + + @slow + @require_tensorflow_probability + @require_pandas + def test_integration_wtq_tf(self): + model_id = "google/tapas-base-finetuned-wtq" + model = TFAutoModelForTableQuestionAnswering.from_pretrained(model_id) + tokenizer = AutoTokenizer.from_pretrained(model_id) + table_querier = pipeline("table-question-answering", model=model, tokenizer=tokenizer) + + data = { + "Repository": ["Transformers", "Datasets", "Tokenizers"], + "Stars": ["36542", "4512", "3934"], + "Contributors": ["651", "77", "34"], + "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + } + queries = [ + "What repository has the largest number of stars?", + "Given that the numbers of stars defines if a repository is active, what repository is the most active?", + "What is the number of repositories?", + "What is the average number of stars?", + "What is the total amount of stars?", + ] + + results = table_querier(data, queries) + + expected_results = [ + {"answer": "Transformers", "coordinates": [(0, 0)], "cells": ["Transformers"], "aggregator": "NONE"}, + {"answer": "Transformers", "coordinates": [(0, 0)], "cells": ["Transformers"], "aggregator": "NONE"}, + { + "answer": "COUNT > Transformers, Datasets, Tokenizers", + "coordinates": [(0, 0), (1, 0), (2, 0)], + "cells": ["Transformers", "Datasets", "Tokenizers"], + "aggregator": "COUNT", + }, + { + "answer": "AVERAGE > 36542, 4512, 3934", + "coordinates": [(0, 1), (1, 1), (2, 1)], + "cells": ["36542", "4512", "3934"], + "aggregator": "AVERAGE", + }, + { + "answer": "SUM > 36542, 4512, 3934", + "coordinates": [(0, 1), (1, 1), (2, 1)], + "cells": ["36542", "4512", "3934"], + "aggregator": "SUM", + }, + ] + self.assertListEqual(results, expected_results) + + @unittest.skipIf(not is_torch_greater_or_equal_than_1_12, reason="Tapas is only available in torch v1.12+") + @slow + @require_torch + def test_integration_sqa_pt(self): + table_querier = pipeline( + "table-question-answering", + model="google/tapas-base-finetuned-sqa", + tokenizer="google/tapas-base-finetuned-sqa", + ) + data = { + "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], + "Age": ["56", "45", "59"], + "Number of movies": ["87", "53", "69"], + "Date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + } + queries = ["How many movies has George Clooney played in?", "How old is he?", "What's his date of birth?"] + results = table_querier(data, queries, sequential=True) + + expected_results = [ + {"answer": "69", "coordinates": [(2, 2)], "cells": ["69"]}, + {"answer": "59", "coordinates": [(2, 1)], "cells": ["59"]}, + {"answer": "28 november 1967", "coordinates": [(2, 3)], "cells": ["28 november 1967"]}, + ] + self.assertListEqual(results, expected_results) + + @slow + @require_tensorflow_probability + @require_pandas + def test_integration_sqa_tf(self): + model_id = "google/tapas-base-finetuned-sqa" + model = TFAutoModelForTableQuestionAnswering.from_pretrained(model_id) + tokenizer = AutoTokenizer.from_pretrained(model_id) + table_querier = pipeline( + "table-question-answering", + model=model, + tokenizer=tokenizer, + ) + data = { + "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], + "Age": ["56", "45", "59"], + "Number of movies": ["87", "53", "69"], + "Date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + } + queries = ["How many movies has George Clooney played in?", "How old is he?", "What's his date of birth?"] + results = table_querier(data, queries, sequential=True) + + expected_results = [ + {"answer": "69", "coordinates": [(2, 2)], "cells": ["69"]}, + {"answer": "59", "coordinates": [(2, 1)], "cells": ["59"]}, + {"answer": "28 november 1967", "coordinates": [(2, 3)], "cells": ["28 november 1967"]}, + ] + self.assertListEqual(results, expected_results) + + @slow + @require_torch + def test_large_model_pt_tapex(self): + model_id = "microsoft/tapex-large-finetuned-wtq" + table_querier = pipeline( + "table-question-answering", + model=model_id, + ) + data = { + "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], + "Age": ["56", "45", "59"], + "Number of movies": ["87", "53", "69"], + "Date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + } + queries = [ + "How many movies has George Clooney played in?", + "How old is Mr Clooney ?", + "What's the date of birth of Leonardo ?", + ] + results = table_querier(data, queries, sequential=True) + + expected_results = [ + {"answer": " 69"}, + {"answer": " 59"}, + {"answer": " 10 june 1996"}, + ] + self.assertListEqual(results, expected_results) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text2text_generation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text2text_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..eccae9850b3b5932b1486f1c125024d750efa7c7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text2text_generation.py @@ -0,0 +1,127 @@ +# 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 unittest + +from transformers import ( + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + Text2TextGenerationPipeline, + pipeline, +) +from transformers.testing_utils import is_pipeline_test, require_tf, require_torch +from transformers.utils import is_torch_available + +from .test_pipelines_common import ANY + + +if is_torch_available(): + import torch + + +@is_pipeline_test +class Text2TextGenerationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + tf_model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + generator = Text2TextGenerationPipeline(model=model, tokenizer=tokenizer) + return generator, ["Something to write", "Something else"] + + def run_pipeline_test(self, generator, _): + outputs = generator("Something there") + self.assertEqual(outputs, [{"generated_text": ANY(str)}]) + # These are encoder decoder, they don't just append to incoming string + self.assertFalse(outputs[0]["generated_text"].startswith("Something there")) + + outputs = generator(["This is great !", "Something else"], num_return_sequences=2, do_sample=True) + self.assertEqual( + outputs, + [ + [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], + [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], + ], + ) + + outputs = generator( + ["This is great !", "Something else"], num_return_sequences=2, batch_size=2, do_sample=True + ) + self.assertEqual( + outputs, + [ + [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], + [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], + ], + ) + + with self.assertRaises(ValueError): + generator(4) + + @require_torch + def test_small_model_pt(self): + generator = pipeline("text2text-generation", model="patrickvonplaten/t5-tiny-random", framework="pt") + # do_sample=False necessary for reproducibility + outputs = generator("Something there", do_sample=False) + self.assertEqual(outputs, [{"generated_text": ""}]) + + num_return_sequences = 3 + outputs = generator( + "Something there", + num_return_sequences=num_return_sequences, + num_beams=num_return_sequences, + ) + target_outputs = [ + {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"}, + {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"}, + {"generated_text": ""}, + ] + self.assertEqual(outputs, target_outputs) + + outputs = generator("This is a test", do_sample=True, num_return_sequences=2, return_tensors=True) + self.assertEqual( + outputs, + [ + {"generated_token_ids": ANY(torch.Tensor)}, + {"generated_token_ids": ANY(torch.Tensor)}, + ], + ) + generator.tokenizer.pad_token_id = generator.model.config.eos_token_id + generator.tokenizer.pad_token = "" + outputs = generator( + ["This is a test", "This is a second test"], + do_sample=True, + num_return_sequences=2, + batch_size=2, + return_tensors=True, + ) + self.assertEqual( + outputs, + [ + [ + {"generated_token_ids": ANY(torch.Tensor)}, + {"generated_token_ids": ANY(torch.Tensor)}, + ], + [ + {"generated_token_ids": ANY(torch.Tensor)}, + {"generated_token_ids": ANY(torch.Tensor)}, + ], + ], + ) + + @require_tf + def test_small_model_tf(self): + generator = pipeline("text2text-generation", model="patrickvonplaten/t5-tiny-random", framework="tf") + # do_sample=False necessary for reproducibility + outputs = generator("Something there", do_sample=False) + self.assertEqual(outputs, [{"generated_text": ""}]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_classification.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..7a33a41c06503dbc46bb132d7fae383635041ed8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_classification.py @@ -0,0 +1,196 @@ +# 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 unittest + +from transformers import ( + MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + TextClassificationPipeline, + pipeline, +) +from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow, torch_device + +from .test_pipelines_common import ANY + + +# These 2 model types require different inputs than those of the usual text models. +_TO_SKIP = {"LayoutLMv2Config", "LayoutLMv3Config"} + + +@is_pipeline_test +class TextClassificationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING + tf_model_mapping = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING + + if model_mapping is not None: + model_mapping = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} + if tf_model_mapping is not None: + tf_model_mapping = { + config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP + } + + @require_torch + def test_small_model_pt(self): + text_classifier = pipeline( + task="text-classification", model="hf-internal-testing/tiny-random-distilbert", framework="pt" + ) + + outputs = text_classifier("This is great !") + self.assertEqual(nested_simplify(outputs), [{"label": "LABEL_0", "score": 0.504}]) + + outputs = text_classifier("This is great !", top_k=2) + self.assertEqual( + nested_simplify(outputs), [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}] + ) + + outputs = text_classifier(["This is great !", "This is bad"], top_k=2) + self.assertEqual( + nested_simplify(outputs), + [ + [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], + [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], + ], + ) + + outputs = text_classifier("This is great !", top_k=1) + self.assertEqual(nested_simplify(outputs), [{"label": "LABEL_0", "score": 0.504}]) + + # Legacy behavior + outputs = text_classifier("This is great !", return_all_scores=False) + self.assertEqual(nested_simplify(outputs), [{"label": "LABEL_0", "score": 0.504}]) + + outputs = text_classifier("This is great !", return_all_scores=True) + self.assertEqual( + nested_simplify(outputs), [[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]] + ) + + outputs = text_classifier(["This is great !", "Something else"], return_all_scores=True) + self.assertEqual( + nested_simplify(outputs), + [ + [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], + [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], + ], + ) + + outputs = text_classifier(["This is great !", "Something else"], return_all_scores=False) + self.assertEqual( + nested_simplify(outputs), + [ + {"label": "LABEL_0", "score": 0.504}, + {"label": "LABEL_0", "score": 0.504}, + ], + ) + + @require_torch + def test_accepts_torch_device(self): + text_classifier = pipeline( + task="text-classification", + model="hf-internal-testing/tiny-random-distilbert", + framework="pt", + device=torch_device, + ) + + outputs = text_classifier("This is great !") + self.assertEqual(nested_simplify(outputs), [{"label": "LABEL_0", "score": 0.504}]) + + @require_tf + def test_small_model_tf(self): + text_classifier = pipeline( + task="text-classification", model="hf-internal-testing/tiny-random-distilbert", framework="tf" + ) + + outputs = text_classifier("This is great !") + self.assertEqual(nested_simplify(outputs), [{"label": "LABEL_0", "score": 0.504}]) + + @slow + @require_torch + def test_pt_bert(self): + text_classifier = pipeline("text-classification") + + outputs = text_classifier("This is great !") + self.assertEqual(nested_simplify(outputs), [{"label": "POSITIVE", "score": 1.0}]) + outputs = text_classifier("This is bad !") + self.assertEqual(nested_simplify(outputs), [{"label": "NEGATIVE", "score": 1.0}]) + outputs = text_classifier("Birds are a type of animal") + self.assertEqual(nested_simplify(outputs), [{"label": "POSITIVE", "score": 0.988}]) + + @slow + @require_tf + def test_tf_bert(self): + text_classifier = pipeline("text-classification", framework="tf") + + outputs = text_classifier("This is great !") + self.assertEqual(nested_simplify(outputs), [{"label": "POSITIVE", "score": 1.0}]) + outputs = text_classifier("This is bad !") + self.assertEqual(nested_simplify(outputs), [{"label": "NEGATIVE", "score": 1.0}]) + outputs = text_classifier("Birds are a type of animal") + self.assertEqual(nested_simplify(outputs), [{"label": "POSITIVE", "score": 0.988}]) + + def get_test_pipeline(self, model, tokenizer, processor): + text_classifier = TextClassificationPipeline(model=model, tokenizer=tokenizer) + return text_classifier, ["HuggingFace is in", "This is another test"] + + def run_pipeline_test(self, text_classifier, _): + model = text_classifier.model + # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 + valid_inputs = "HuggingFace is in" + outputs = text_classifier(valid_inputs) + + self.assertEqual(nested_simplify(outputs), [{"label": ANY(str), "score": ANY(float)}]) + self.assertTrue(outputs[0]["label"] in model.config.id2label.values()) + + valid_inputs = ["HuggingFace is in ", "Paris is in France"] + outputs = text_classifier(valid_inputs) + self.assertEqual( + nested_simplify(outputs), + [{"label": ANY(str), "score": ANY(float)}, {"label": ANY(str), "score": ANY(float)}], + ) + self.assertTrue(outputs[0]["label"] in model.config.id2label.values()) + self.assertTrue(outputs[1]["label"] in model.config.id2label.values()) + + # Forcing to get all results with `top_k=None` + # This is NOT the legacy format + outputs = text_classifier(valid_inputs, top_k=None) + N = len(model.config.id2label.values()) + self.assertEqual( + nested_simplify(outputs), + [[{"label": ANY(str), "score": ANY(float)}] * N, [{"label": ANY(str), "score": ANY(float)}] * N], + ) + + valid_inputs = {"text": "HuggingFace is in ", "text_pair": "Paris is in France"} + outputs = text_classifier(valid_inputs) + self.assertEqual( + nested_simplify(outputs), + {"label": ANY(str), "score": ANY(float)}, + ) + self.assertTrue(outputs["label"] in model.config.id2label.values()) + + # This might be used a text pair, but tokenizer + pipe interaction + # makes it hard to understand that it's not using the pair properly + # https://github.com/huggingface/transformers/issues/17305 + # We disabled this usage instead as it was outputting wrong outputs. + invalid_input = [["HuggingFace is in ", "Paris is in France"]] + with self.assertRaises(ValueError): + text_classifier(invalid_input) + + # This used to be valid for doing text pairs + # We're keeping it working because of backward compatibility + outputs = text_classifier([[["HuggingFace is in ", "Paris is in France"]]]) + self.assertEqual( + nested_simplify(outputs), + [{"label": ANY(str), "score": ANY(float)}], + ) + self.assertTrue(outputs[0]["label"] in model.config.id2label.values()) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_generation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..dc77204f3e13d1c2a5e55fd17118e0502591b46f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_generation.py @@ -0,0 +1,370 @@ +# 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 unittest + +from transformers import ( + MODEL_FOR_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_CAUSAL_LM_MAPPING, + TextGenerationPipeline, + logging, + pipeline, +) +from transformers.testing_utils import ( + CaptureLogger, + is_pipeline_test, + require_accelerate, + require_tf, + require_torch, + require_torch_accelerator, + require_torch_gpu, + require_torch_or_tf, + torch_device, +) + +from .test_pipelines_common import ANY + + +@is_pipeline_test +@require_torch_or_tf +class TextGenerationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING + tf_model_mapping = TF_MODEL_FOR_CAUSAL_LM_MAPPING + + @require_torch + def test_small_model_pt(self): + text_generator = pipeline(task="text-generation", model="sshleifer/tiny-ctrl", framework="pt") + # Using `do_sample=False` to force deterministic output + outputs = text_generator("This is a test", do_sample=False) + self.assertEqual( + outputs, + [ + { + "generated_text": ( + "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." + " oscope. FiliFili@@" + ) + } + ], + ) + + outputs = text_generator(["This is a test", "This is a second test"]) + self.assertEqual( + outputs, + [ + [ + { + "generated_text": ( + "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." + " oscope. FiliFili@@" + ) + } + ], + [ + { + "generated_text": ( + "This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy" + " oscope. oscope. FiliFili@@" + ) + } + ], + ], + ) + + outputs = text_generator("This is a test", do_sample=True, num_return_sequences=2, return_tensors=True) + self.assertEqual( + outputs, + [ + {"generated_token_ids": ANY(list)}, + {"generated_token_ids": ANY(list)}, + ], + ) + text_generator.tokenizer.pad_token_id = text_generator.model.config.eos_token_id + text_generator.tokenizer.pad_token = "" + outputs = text_generator( + ["This is a test", "This is a second test"], + do_sample=True, + num_return_sequences=2, + batch_size=2, + return_tensors=True, + ) + self.assertEqual( + outputs, + [ + [ + {"generated_token_ids": ANY(list)}, + {"generated_token_ids": ANY(list)}, + ], + [ + {"generated_token_ids": ANY(list)}, + {"generated_token_ids": ANY(list)}, + ], + ], + ) + + @require_tf + def test_small_model_tf(self): + text_generator = pipeline(task="text-generation", model="sshleifer/tiny-ctrl", framework="tf") + + # Using `do_sample=False` to force deterministic output + outputs = text_generator("This is a test", do_sample=False) + self.assertEqual( + outputs, + [ + { + "generated_text": ( + "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" + " please," + ) + } + ], + ) + + outputs = text_generator(["This is a test", "This is a second test"], do_sample=False) + self.assertEqual( + outputs, + [ + [ + { + "generated_text": ( + "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" + " please," + ) + } + ], + [ + { + "generated_text": ( + "This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes" + " Cannes 閲閲Cannes Cannes Cannes 攵 please," + ) + } + ], + ], + ) + + def get_test_pipeline(self, model, tokenizer, processor): + text_generator = TextGenerationPipeline(model=model, tokenizer=tokenizer) + return text_generator, ["This is a test", "Another test"] + + def test_stop_sequence_stopping_criteria(self): + prompt = """Hello I believe in""" + text_generator = pipeline("text-generation", model="hf-internal-testing/tiny-random-gpt2") + output = text_generator(prompt) + self.assertEqual( + output, + [{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}], + ) + + output = text_generator(prompt, stop_sequence=" fe") + self.assertEqual(output, [{"generated_text": "Hello I believe in fe"}]) + + def run_pipeline_test(self, text_generator, _): + model = text_generator.model + tokenizer = text_generator.tokenizer + + outputs = text_generator("This is a test") + self.assertEqual(outputs, [{"generated_text": ANY(str)}]) + self.assertTrue(outputs[0]["generated_text"].startswith("This is a test")) + + outputs = text_generator("This is a test", return_full_text=False) + self.assertEqual(outputs, [{"generated_text": ANY(str)}]) + self.assertNotIn("This is a test", outputs[0]["generated_text"]) + + text_generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer, return_full_text=False) + outputs = text_generator("This is a test") + self.assertEqual(outputs, [{"generated_text": ANY(str)}]) + self.assertNotIn("This is a test", outputs[0]["generated_text"]) + + outputs = text_generator("This is a test", return_full_text=True) + self.assertEqual(outputs, [{"generated_text": ANY(str)}]) + self.assertTrue(outputs[0]["generated_text"].startswith("This is a test")) + + outputs = text_generator(["This is great !", "Something else"], num_return_sequences=2, do_sample=True) + self.assertEqual( + outputs, + [ + [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], + [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], + ], + ) + + if text_generator.tokenizer.pad_token is not None: + outputs = text_generator( + ["This is great !", "Something else"], num_return_sequences=2, batch_size=2, do_sample=True + ) + self.assertEqual( + outputs, + [ + [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], + [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], + ], + ) + + with self.assertRaises(ValueError): + outputs = text_generator("test", return_full_text=True, return_text=True) + with self.assertRaises(ValueError): + outputs = text_generator("test", return_full_text=True, return_tensors=True) + with self.assertRaises(ValueError): + outputs = text_generator("test", return_text=True, return_tensors=True) + + # Empty prompt is slighly special + # it requires BOS token to exist. + # Special case for Pegasus which will always append EOS so will + # work even without BOS. + if ( + text_generator.tokenizer.bos_token_id is not None + or "Pegasus" in tokenizer.__class__.__name__ + or "Git" in model.__class__.__name__ + ): + outputs = text_generator("") + self.assertEqual(outputs, [{"generated_text": ANY(str)}]) + else: + with self.assertRaises((ValueError, AssertionError)): + outputs = text_generator("") + + if text_generator.framework == "tf": + # TF generation does not support max_new_tokens, and it's impossible + # to control long generation with only max_length without + # fancy calculation, dismissing tests for now. + return + # We don't care about infinite range models. + # They already work. + # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. + EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS = [ + "RwkvForCausalLM", + "XGLMForCausalLM", + "GPTNeoXForCausalLM", + "FuyuForCausalLM", + ] + if ( + tokenizer.model_max_length < 10000 + and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS + ): + # Handling of large generations + with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError)): + text_generator("This is a test" * 500, max_new_tokens=20) + + outputs = text_generator("This is a test" * 500, handle_long_generation="hole", max_new_tokens=20) + # Hole strategy cannot work + with self.assertRaises(ValueError): + text_generator( + "This is a test" * 500, + handle_long_generation="hole", + max_new_tokens=tokenizer.model_max_length + 10, + ) + + @require_torch + @require_accelerate + @require_torch_gpu + def test_small_model_pt_bloom_accelerate(self): + import torch + + # Classic `model_kwargs` + pipe = pipeline( + model="hf-internal-testing/tiny-random-bloom", + model_kwargs={"device_map": "auto", "torch_dtype": torch.bfloat16}, + ) + self.assertEqual(pipe.model.device, torch.device(0)) + self.assertEqual(pipe.model.lm_head.weight.dtype, torch.bfloat16) + out = pipe("This is a test") + self.assertEqual( + out, + [ + { + "generated_text": ( + "This is a test test test test test test test test test test test test test test test test" + " test" + ) + } + ], + ) + + # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) + pipe = pipeline(model="hf-internal-testing/tiny-random-bloom", device_map="auto", torch_dtype=torch.bfloat16) + self.assertEqual(pipe.model.device, torch.device(0)) + self.assertEqual(pipe.model.lm_head.weight.dtype, torch.bfloat16) + out = pipe("This is a test") + self.assertEqual( + out, + [ + { + "generated_text": ( + "This is a test test test test test test test test test test test test test test test test" + " test" + ) + } + ], + ) + + # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 + pipe = pipeline(model="hf-internal-testing/tiny-random-bloom", device_map="auto") + self.assertEqual(pipe.model.device, torch.device(0)) + self.assertEqual(pipe.model.lm_head.weight.dtype, torch.float32) + out = pipe("This is a test") + self.assertEqual( + out, + [ + { + "generated_text": ( + "This is a test test test test test test test test test test test test test test test test" + " test" + ) + } + ], + ) + + @require_torch + @require_torch_accelerator + def test_small_model_fp16(self): + import torch + + pipe = pipeline( + model="hf-internal-testing/tiny-random-bloom", + device=torch_device, + torch_dtype=torch.float16, + ) + pipe("This is a test") + + @require_torch + @require_accelerate + @require_torch_accelerator + def test_pipeline_accelerate_top_p(self): + import torch + + pipe = pipeline(model="hf-internal-testing/tiny-random-bloom", device_map="auto", torch_dtype=torch.float16) + pipe("This is a test", do_sample=True, top_p=0.5) + + def test_pipeline_length_setting_warning(self): + prompt = """Hello world""" + text_generator = pipeline("text-generation", model="hf-internal-testing/tiny-random-gpt2") + if text_generator.model.framework == "tf": + logger = logging.get_logger("transformers.generation.tf_utils") + else: + logger = logging.get_logger("transformers.generation.utils") + logger_msg = "Both `max_new_tokens`" # The beggining of the message to be checked in this test + + # Both are set by the user -> log warning + with CaptureLogger(logger) as cl: + _ = text_generator(prompt, max_length=10, max_new_tokens=1) + self.assertIn(logger_msg, cl.out) + + # The user only sets one -> no warning + with CaptureLogger(logger) as cl: + _ = text_generator(prompt, max_new_tokens=1) + self.assertNotIn(logger_msg, cl.out) + + with CaptureLogger(logger) as cl: + _ = text_generator(prompt, max_length=10) + self.assertNotIn(logger_msg, cl.out) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_to_audio.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_to_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f1eccae5089cfd8b1f257a494b0c23042acba5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_text_to_audio.py @@ -0,0 +1,245 @@ +# Copyright 2023 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 unittest + +import numpy as np + +from transformers import ( + MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING, + AutoProcessor, + TextToAudioPipeline, + pipeline, +) +from transformers.testing_utils import ( + is_pipeline_test, + require_torch, + require_torch_accelerator, + require_torch_or_tf, + slow, + torch_device, +) +from transformers.trainer_utils import set_seed + +from .test_pipelines_common import ANY + + +@is_pipeline_test +@require_torch_or_tf +class TextToAudioPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING + # for now only test text_to_waveform and not text_to_spectrogram + + @slow + @require_torch + def test_small_musicgen_pt(self): + music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt") + + forward_params = { + "do_sample": False, + "max_new_tokens": 250, + } + + outputs = music_generator("This is a test", forward_params=forward_params) + self.assertEqual({"audio": ANY(np.ndarray), "sampling_rate": 32000}, outputs) + + # test two examples side-by-side + outputs = music_generator(["This is a test", "This is a second test"], forward_params=forward_params) + audio = [output["audio"] for output in outputs] + self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) + + # test batching + outputs = music_generator( + ["This is a test", "This is a second test"], forward_params=forward_params, batch_size=2 + ) + audio = [output["audio"] for output in outputs] + self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) + + @slow + @require_torch + def test_small_bark_pt(self): + speech_generator = pipeline(task="text-to-audio", model="suno/bark-small", framework="pt") + + forward_params = { + # Using `do_sample=False` to force deterministic output + "do_sample": False, + "semantic_max_new_tokens": 100, + } + + outputs = speech_generator("This is a test", forward_params=forward_params) + self.assertEqual( + {"audio": ANY(np.ndarray), "sampling_rate": 24000}, + outputs, + ) + + # test two examples side-by-side + outputs = speech_generator( + ["This is a test", "This is a second test"], + forward_params=forward_params, + ) + audio = [output["audio"] for output in outputs] + self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) + + # test other generation strategy + forward_params = { + "do_sample": True, + "semantic_max_new_tokens": 100, + "semantic_num_return_sequences": 2, + } + + outputs = speech_generator("This is a test", forward_params=forward_params) + audio = outputs["audio"] + self.assertEqual(ANY(np.ndarray), audio) + + # test using a speaker embedding + processor = AutoProcessor.from_pretrained("suno/bark-small") + temp_inp = processor("hey, how are you?", voice_preset="v2/en_speaker_5") + history_prompt = temp_inp["history_prompt"] + forward_params["history_prompt"] = history_prompt + + outputs = speech_generator( + ["This is a test", "This is a second test"], + forward_params=forward_params, + batch_size=2, + ) + audio = [output["audio"] for output in outputs] + self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) + + @slow + @require_torch_accelerator + def test_conversion_additional_tensor(self): + speech_generator = pipeline(task="text-to-audio", model="suno/bark-small", framework="pt", device=torch_device) + processor = AutoProcessor.from_pretrained("suno/bark-small") + + forward_params = { + "do_sample": True, + "semantic_max_new_tokens": 100, + } + + # atm, must do to stay coherent with BarkProcessor + preprocess_params = { + "max_length": 256, + "add_special_tokens": False, + "return_attention_mask": True, + "return_token_type_ids": False, + "padding": "max_length", + } + outputs = speech_generator( + "This is a test", + forward_params=forward_params, + preprocess_params=preprocess_params, + ) + + temp_inp = processor("hey, how are you?", voice_preset="v2/en_speaker_5") + history_prompt = temp_inp["history_prompt"] + forward_params["history_prompt"] = history_prompt + + # history_prompt is a torch.Tensor passed as a forward_param + # if generation is successful, it means that it was passed to the right device + outputs = speech_generator( + "This is a test", forward_params=forward_params, preprocess_params=preprocess_params + ) + self.assertEqual( + {"audio": ANY(np.ndarray), "sampling_rate": 24000}, + outputs, + ) + + @slow + @require_torch + def test_vits_model_pt(self): + speech_generator = pipeline(task="text-to-audio", model="facebook/mms-tts-eng", framework="pt") + + outputs = speech_generator("This is a test") + self.assertEqual(outputs["sampling_rate"], 16000) + + audio = outputs["audio"] + self.assertEqual(ANY(np.ndarray), audio) + + # test two examples side-by-side + outputs = speech_generator(["This is a test", "This is a second test"]) + audio = [output["audio"] for output in outputs] + self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) + + # test batching + outputs = speech_generator(["This is a test", "This is a second test"], batch_size=2) + self.assertEqual(ANY(np.ndarray), outputs[0]["audio"]) + + @slow + @require_torch + def test_forward_model_kwargs(self): + # use vits - a forward model + speech_generator = pipeline(task="text-to-audio", model="kakao-enterprise/vits-vctk", framework="pt") + + # for reproducibility + set_seed(555) + outputs = speech_generator("This is a test", forward_params={"speaker_id": 5}) + audio = outputs["audio"] + + with self.assertRaises(TypeError): + # assert error if generate parameter + outputs = speech_generator("This is a test", forward_params={"speaker_id": 5, "do_sample": True}) + + forward_params = {"speaker_id": 5} + generate_kwargs = {"do_sample": True} + + with self.assertRaises(ValueError): + # assert error if generate_kwargs with forward-only models + outputs = speech_generator( + "This is a test", forward_params=forward_params, generate_kwargs=generate_kwargs + ) + self.assertTrue(np.abs(outputs["audio"] - audio).max() < 1e-5) + + @slow + @require_torch + def test_generative_model_kwargs(self): + # use musicgen - a generative model + music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt") + + forward_params = { + "do_sample": True, + "max_new_tokens": 250, + } + + # for reproducibility + set_seed(555) + outputs = music_generator("This is a test", forward_params=forward_params) + audio = outputs["audio"] + self.assertEqual(ANY(np.ndarray), audio) + + # make sure generate kwargs get priority over forward params + forward_params = { + "do_sample": False, + "max_new_tokens": 250, + } + generate_kwargs = {"do_sample": True} + + # for reproducibility + set_seed(555) + outputs = music_generator("This is a test", forward_params=forward_params, generate_kwargs=generate_kwargs) + self.assertListEqual(outputs["audio"].tolist(), audio.tolist()) + + def get_test_pipeline(self, model, tokenizer, processor): + speech_generator = TextToAudioPipeline(model=model, tokenizer=tokenizer) + return speech_generator, ["This is a test", "Another test"] + + def run_pipeline_test(self, speech_generator, _): + outputs = speech_generator("This is a test") + self.assertEqual(ANY(np.ndarray), outputs["audio"]) + + forward_params = ( + {"num_return_sequences": 2, "do_sample": True} if speech_generator.model.can_generate() else {} + ) + outputs = speech_generator(["This is great !", "Something else"], forward_params=forward_params) + audio = [output["audio"] for output in outputs] + self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_token_classification.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_token_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..b139fbfd2f79822dc0cf87948bcca2529c5c238b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_token_classification.py @@ -0,0 +1,949 @@ +# 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 unittest + +import numpy as np + +from transformers import ( + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + AutoModelForTokenClassification, + AutoTokenizer, + TokenClassificationPipeline, + pipeline, +) +from transformers.pipelines import AggregationStrategy, TokenClassificationArgumentHandler +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_torch, + require_torch_accelerator, + slow, + torch_device, +) + +from .test_pipelines_common import ANY + + +VALID_INPUTS = ["A simple string", ["list of strings", "A simple string that is quite a bit longer"]] + +# These 2 model types require different inputs than those of the usual text models. +_TO_SKIP = {"LayoutLMv2Config", "LayoutLMv3Config"} + + +@is_pipeline_test +class TokenClassificationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING + tf_model_mapping = TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING + + if model_mapping is not None: + model_mapping = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} + if tf_model_mapping is not None: + tf_model_mapping = { + config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP + } + + def get_test_pipeline(self, model, tokenizer, processor): + token_classifier = TokenClassificationPipeline(model=model, tokenizer=tokenizer) + return token_classifier, ["A simple string", "A simple string that is quite a bit longer"] + + def run_pipeline_test(self, token_classifier, _): + model = token_classifier.model + tokenizer = token_classifier.tokenizer + if not tokenizer.is_fast: + return # Slow tokenizers do not return offsets mappings, so this test will fail + + outputs = token_classifier("A simple string") + self.assertIsInstance(outputs, list) + n = len(outputs) + self.assertEqual( + nested_simplify(outputs), + [ + { + "entity": ANY(str), + "score": ANY(float), + "start": ANY(int), + "end": ANY(int), + "index": ANY(int), + "word": ANY(str), + } + for i in range(n) + ], + ) + outputs = token_classifier(["list of strings", "A simple string that is quite a bit longer"]) + self.assertIsInstance(outputs, list) + self.assertEqual(len(outputs), 2) + n = len(outputs[0]) + m = len(outputs[1]) + + self.assertEqual( + nested_simplify(outputs), + [ + [ + { + "entity": ANY(str), + "score": ANY(float), + "start": ANY(int), + "end": ANY(int), + "index": ANY(int), + "word": ANY(str), + } + for i in range(n) + ], + [ + { + "entity": ANY(str), + "score": ANY(float), + "start": ANY(int), + "end": ANY(int), + "index": ANY(int), + "word": ANY(str), + } + for i in range(m) + ], + ], + ) + + self.run_aggregation_strategy(model, tokenizer) + + def run_aggregation_strategy(self, model, tokenizer): + token_classifier = TokenClassificationPipeline(model=model, tokenizer=tokenizer, aggregation_strategy="simple") + self.assertEqual(token_classifier._postprocess_params["aggregation_strategy"], AggregationStrategy.SIMPLE) + outputs = token_classifier("A simple string") + self.assertIsInstance(outputs, list) + n = len(outputs) + self.assertEqual( + nested_simplify(outputs), + [ + { + "entity_group": ANY(str), + "score": ANY(float), + "start": ANY(int), + "end": ANY(int), + "word": ANY(str), + } + for i in range(n) + ], + ) + + token_classifier = TokenClassificationPipeline(model=model, tokenizer=tokenizer, aggregation_strategy="first") + self.assertEqual(token_classifier._postprocess_params["aggregation_strategy"], AggregationStrategy.FIRST) + outputs = token_classifier("A simple string") + self.assertIsInstance(outputs, list) + n = len(outputs) + self.assertEqual( + nested_simplify(outputs), + [ + { + "entity_group": ANY(str), + "score": ANY(float), + "start": ANY(int), + "end": ANY(int), + "word": ANY(str), + } + for i in range(n) + ], + ) + + token_classifier = TokenClassificationPipeline(model=model, tokenizer=tokenizer, aggregation_strategy="max") + self.assertEqual(token_classifier._postprocess_params["aggregation_strategy"], AggregationStrategy.MAX) + outputs = token_classifier("A simple string") + self.assertIsInstance(outputs, list) + n = len(outputs) + self.assertEqual( + nested_simplify(outputs), + [ + { + "entity_group": ANY(str), + "score": ANY(float), + "start": ANY(int), + "end": ANY(int), + "word": ANY(str), + } + for i in range(n) + ], + ) + + token_classifier = TokenClassificationPipeline( + model=model, tokenizer=tokenizer, aggregation_strategy="average" + ) + self.assertEqual(token_classifier._postprocess_params["aggregation_strategy"], AggregationStrategy.AVERAGE) + outputs = token_classifier("A simple string") + self.assertIsInstance(outputs, list) + n = len(outputs) + self.assertEqual( + nested_simplify(outputs), + [ + { + "entity_group": ANY(str), + "score": ANY(float), + "start": ANY(int), + "end": ANY(int), + "word": ANY(str), + } + for i in range(n) + ], + ) + + with self.assertWarns(UserWarning): + token_classifier = pipeline(task="ner", model=model, tokenizer=tokenizer, grouped_entities=True) + self.assertEqual(token_classifier._postprocess_params["aggregation_strategy"], AggregationStrategy.SIMPLE) + with self.assertWarns(UserWarning): + token_classifier = pipeline( + task="ner", model=model, tokenizer=tokenizer, grouped_entities=True, ignore_subwords=True + ) + self.assertEqual(token_classifier._postprocess_params["aggregation_strategy"], AggregationStrategy.FIRST) + + @slow + @require_torch + def test_chunking(self): + NER_MODEL = "elastic/distilbert-base-uncased-finetuned-conll03-english" + model = AutoModelForTokenClassification.from_pretrained(NER_MODEL) + tokenizer = AutoTokenizer.from_pretrained(NER_MODEL, use_fast=True) + tokenizer.model_max_length = 10 + stride = 5 + sentence = ( + "Hugging Face, Inc. is a French company that develops tools for building applications using machine learning. " + "The company, based in New York City was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf." + ) + + token_classifier = TokenClassificationPipeline( + model=model, tokenizer=tokenizer, aggregation_strategy="simple", stride=stride + ) + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output), + [ + {"entity_group": "ORG", "score": 0.978, "word": "hugging face, inc.", "start": 0, "end": 18}, + {"entity_group": "MISC", "score": 0.999, "word": "french", "start": 24, "end": 30}, + {"entity_group": "LOC", "score": 0.997, "word": "new york city", "start": 131, "end": 144}, + {"entity_group": "MISC", "score": 0.999, "word": "french", "start": 168, "end": 174}, + {"entity_group": "PER", "score": 0.999, "word": "clement delangue", "start": 189, "end": 205}, + {"entity_group": "PER", "score": 0.999, "word": "julien chaumond", "start": 207, "end": 222}, + {"entity_group": "PER", "score": 0.999, "word": "thomas wolf", "start": 228, "end": 239}, + ], + ) + + token_classifier = TokenClassificationPipeline( + model=model, tokenizer=tokenizer, aggregation_strategy="first", stride=stride + ) + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output), + [ + {"entity_group": "ORG", "score": 0.978, "word": "hugging face, inc.", "start": 0, "end": 18}, + {"entity_group": "MISC", "score": 0.999, "word": "french", "start": 24, "end": 30}, + {"entity_group": "LOC", "score": 0.997, "word": "new york city", "start": 131, "end": 144}, + {"entity_group": "MISC", "score": 0.999, "word": "french", "start": 168, "end": 174}, + {"entity_group": "PER", "score": 0.999, "word": "clement delangue", "start": 189, "end": 205}, + {"entity_group": "PER", "score": 0.999, "word": "julien chaumond", "start": 207, "end": 222}, + {"entity_group": "PER", "score": 0.999, "word": "thomas wolf", "start": 228, "end": 239}, + ], + ) + + token_classifier = TokenClassificationPipeline( + model=model, tokenizer=tokenizer, aggregation_strategy="max", stride=stride + ) + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output), + [ + {"entity_group": "ORG", "score": 0.978, "word": "hugging face, inc.", "start": 0, "end": 18}, + {"entity_group": "MISC", "score": 0.999, "word": "french", "start": 24, "end": 30}, + {"entity_group": "LOC", "score": 0.997, "word": "new york city", "start": 131, "end": 144}, + {"entity_group": "MISC", "score": 0.999, "word": "french", "start": 168, "end": 174}, + {"entity_group": "PER", "score": 0.999, "word": "clement delangue", "start": 189, "end": 205}, + {"entity_group": "PER", "score": 0.999, "word": "julien chaumond", "start": 207, "end": 222}, + {"entity_group": "PER", "score": 0.999, "word": "thomas wolf", "start": 228, "end": 239}, + ], + ) + + token_classifier = TokenClassificationPipeline( + model=model, tokenizer=tokenizer, aggregation_strategy="average", stride=stride + ) + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output), + [ + {"entity_group": "ORG", "score": 0.978, "word": "hugging face, inc.", "start": 0, "end": 18}, + {"entity_group": "MISC", "score": 0.999, "word": "french", "start": 24, "end": 30}, + {"entity_group": "LOC", "score": 0.997, "word": "new york city", "start": 131, "end": 144}, + {"entity_group": "MISC", "score": 0.999, "word": "french", "start": 168, "end": 174}, + {"entity_group": "PER", "score": 0.999, "word": "clement delangue", "start": 189, "end": 205}, + {"entity_group": "PER", "score": 0.999, "word": "julien chaumond", "start": 207, "end": 222}, + {"entity_group": "PER", "score": 0.999, "word": "thomas wolf", "start": 228, "end": 239}, + ], + ) + + @require_torch + def test_chunking_fast(self): + # Note: We cannot run the test on "conflicts" on the chunking. + # The problem is that the model is random, and thus the results do heavily + # depend on the chunking, so we cannot expect "abcd" and "bcd" to find + # the same entities. We defer to slow tests for this. + pipe = pipeline(model="hf-internal-testing/tiny-bert-for-token-classification") + sentence = "The company, based in New York City was founded in 2016 by French entrepreneurs" + + results = pipe(sentence, aggregation_strategy="first") + # This is what this random model gives on the full sentence + self.assertEqual( + nested_simplify(results), + [ + # This is 2 actual tokens + {"end": 39, "entity_group": "MISC", "score": 0.115, "start": 31, "word": "city was"}, + {"end": 79, "entity_group": "MISC", "score": 0.115, "start": 66, "word": "entrepreneurs"}, + ], + ) + + # This will force the tokenizer to split after "city was". + pipe.tokenizer.model_max_length = 12 + self.assertEqual( + pipe.tokenizer.decode(pipe.tokenizer.encode(sentence, truncation=True)), + "[CLS] the company, based in new york city was [SEP]", + ) + + stride = 4 + results = pipe(sentence, aggregation_strategy="first", stride=stride) + self.assertEqual( + nested_simplify(results), + [ + {"end": 39, "entity_group": "MISC", "score": 0.115, "start": 31, "word": "city was"}, + # This is an extra entity found by this random model, but at least both original + # entities are there + {"end": 58, "entity_group": "MISC", "score": 0.115, "start": 56, "word": "by"}, + {"end": 79, "entity_group": "MISC", "score": 0.115, "start": 66, "word": "entrepreneurs"}, + ], + ) + + @require_torch + @slow + def test_spanish_bert(self): + # https://github.com/huggingface/transformers/pull/4987 + NER_MODEL = "mrm8488/bert-spanish-cased-finetuned-ner" + model = AutoModelForTokenClassification.from_pretrained(NER_MODEL) + tokenizer = AutoTokenizer.from_pretrained(NER_MODEL, use_fast=True) + sentence = """Consuelo Araújo Noguera, ministra de cultura del presidente Andrés Pastrana (1998.2002) fue asesinada por las Farc luego de haber permanecido secuestrada por algunos meses.""" + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer) + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output[:3]), + [ + {"entity": "B-PER", "score": 0.999, "word": "Cons", "start": 0, "end": 4, "index": 1}, + {"entity": "B-PER", "score": 0.803, "word": "##uelo", "start": 4, "end": 8, "index": 2}, + {"entity": "I-PER", "score": 0.999, "word": "Ara", "start": 9, "end": 12, "index": 3}, + ], + ) + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="simple") + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output[:3]), + [ + {"entity_group": "PER", "score": 0.999, "word": "Cons", "start": 0, "end": 4}, + {"entity_group": "PER", "score": 0.966, "word": "##uelo Araújo Noguera", "start": 4, "end": 23}, + {"entity_group": "PER", "score": 1.0, "word": "Andrés Pastrana", "start": 60, "end": 75}, + ], + ) + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="first") + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output[:3]), + [ + {"entity_group": "PER", "score": 0.999, "word": "Consuelo Araújo Noguera", "start": 0, "end": 23}, + {"entity_group": "PER", "score": 1.0, "word": "Andrés Pastrana", "start": 60, "end": 75}, + {"entity_group": "ORG", "score": 0.999, "word": "Farc", "start": 110, "end": 114}, + ], + ) + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="max") + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output[:3]), + [ + {"entity_group": "PER", "score": 0.999, "word": "Consuelo Araújo Noguera", "start": 0, "end": 23}, + {"entity_group": "PER", "score": 1.0, "word": "Andrés Pastrana", "start": 60, "end": 75}, + {"entity_group": "ORG", "score": 0.999, "word": "Farc", "start": 110, "end": 114}, + ], + ) + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="average") + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output[:3]), + [ + {"entity_group": "PER", "score": 0.966, "word": "Consuelo Araújo Noguera", "start": 0, "end": 23}, + {"entity_group": "PER", "score": 1.0, "word": "Andrés Pastrana", "start": 60, "end": 75}, + {"entity_group": "ORG", "score": 0.542, "word": "Farc", "start": 110, "end": 114}, + ], + ) + + @require_torch_accelerator + @slow + def test_accelerator(self): + sentence = "This is dummy sentence" + ner = pipeline( + "token-classification", + device=torch_device, + aggregation_strategy=AggregationStrategy.SIMPLE, + ) + + output = ner(sentence) + self.assertEqual(nested_simplify(output), []) + + @require_torch + @slow + def test_dbmdz_english(self): + # Other sentence + NER_MODEL = "dbmdz/bert-large-cased-finetuned-conll03-english" + model = AutoModelForTokenClassification.from_pretrained(NER_MODEL) + tokenizer = AutoTokenizer.from_pretrained(NER_MODEL, use_fast=True) + sentence = """Enzo works at the UN""" + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer) + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output), + [ + {"entity": "I-PER", "score": 0.998, "word": "En", "start": 0, "end": 2, "index": 1}, + {"entity": "I-PER", "score": 0.997, "word": "##zo", "start": 2, "end": 4, "index": 2}, + {"entity": "I-ORG", "score": 0.999, "word": "UN", "start": 18, "end": 20, "index": 6}, + ], + ) + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="simple") + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output), + [ + {"entity_group": "PER", "score": 0.997, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 18, "end": 20}, + ], + ) + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="first") + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output[:3]), + [ + {"entity_group": "PER", "score": 0.998, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 18, "end": 20}, + ], + ) + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="max") + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output[:3]), + [ + {"entity_group": "PER", "score": 0.998, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 18, "end": 20}, + ], + ) + + token_classifier = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="average") + output = token_classifier(sentence) + self.assertEqual( + nested_simplify(output), + [ + {"entity_group": "PER", "score": 0.997, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 18, "end": 20}, + ], + ) + + @require_torch + @slow + def test_aggregation_strategy_byte_level_tokenizer(self): + sentence = "Groenlinks praat over Schiphol." + ner = pipeline("ner", model="xlm-roberta-large-finetuned-conll02-dutch", aggregation_strategy="max") + self.assertEqual( + nested_simplify(ner(sentence)), + [ + {"end": 10, "entity_group": "ORG", "score": 0.994, "start": 0, "word": "Groenlinks"}, + {"entity_group": "LOC", "score": 1.0, "word": "Schiphol.", "start": 22, "end": 31}, + ], + ) + + @require_torch + def test_aggregation_strategy_no_b_i_prefix(self): + model_name = "sshleifer/tiny-dbmdz-bert-large-cased-finetuned-conll03-english" + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) + token_classifier = pipeline(task="ner", model=model_name, tokenizer=tokenizer, framework="pt") + # Just to understand scores indexes in this test + token_classifier.model.config.id2label = {0: "O", 1: "MISC", 2: "PER", 3: "ORG", 4: "LOC"} + example = [ + { + "scores": np.array([0, 0, 0, 0, 0.9968166351318359]), # fmt : skip + "index": 1, + "is_subword": False, + "word": "En", + "start": 0, + "end": 2, + }, + { + "scores": np.array([0, 0, 0, 0, 0.9957635998725891]), # fmt : skip + "index": 2, + "is_subword": True, + "word": "##zo", + "start": 2, + "end": 4, + }, + { + "scores": np.array([0, 0, 0, 0.9986497163772583, 0]), # fmt : skip + "index": 7, + "word": "UN", + "is_subword": False, + "start": 11, + "end": 13, + }, + ] + self.assertEqual( + nested_simplify(token_classifier.aggregate(example, AggregationStrategy.NONE)), + [ + {"end": 2, "entity": "LOC", "score": 0.997, "start": 0, "word": "En", "index": 1}, + {"end": 4, "entity": "LOC", "score": 0.996, "start": 2, "word": "##zo", "index": 2}, + {"end": 13, "entity": "ORG", "score": 0.999, "start": 11, "word": "UN", "index": 7}, + ], + ) + self.assertEqual( + nested_simplify(token_classifier.aggregate(example, AggregationStrategy.SIMPLE)), + [ + {"entity_group": "LOC", "score": 0.996, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 11, "end": 13}, + ], + ) + + @require_torch + def test_aggregation_strategy(self): + model_name = "sshleifer/tiny-dbmdz-bert-large-cased-finetuned-conll03-english" + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) + token_classifier = pipeline(task="ner", model=model_name, tokenizer=tokenizer, framework="pt") + # Just to understand scores indexes in this test + self.assertEqual( + token_classifier.model.config.id2label, + {0: "O", 1: "B-MISC", 2: "I-MISC", 3: "B-PER", 4: "I-PER", 5: "B-ORG", 6: "I-ORG", 7: "B-LOC", 8: "I-LOC"}, + ) + example = [ + { + "scores": np.array([0, 0, 0, 0, 0.9968166351318359, 0, 0, 0]), # fmt : skip + "index": 1, + "is_subword": False, + "word": "En", + "start": 0, + "end": 2, + }, + { + "scores": np.array([0, 0, 0, 0, 0.9957635998725891, 0, 0, 0]), # fmt : skip + "index": 2, + "is_subword": True, + "word": "##zo", + "start": 2, + "end": 4, + }, + { + "scores": np.array([0, 0, 0, 0, 0, 0.9986497163772583, 0, 0]), # fmt : skip + "index": 7, + "word": "UN", + "is_subword": False, + "start": 11, + "end": 13, + }, + ] + self.assertEqual( + nested_simplify(token_classifier.aggregate(example, AggregationStrategy.NONE)), + [ + {"end": 2, "entity": "I-PER", "score": 0.997, "start": 0, "word": "En", "index": 1}, + {"end": 4, "entity": "I-PER", "score": 0.996, "start": 2, "word": "##zo", "index": 2}, + {"end": 13, "entity": "B-ORG", "score": 0.999, "start": 11, "word": "UN", "index": 7}, + ], + ) + self.assertEqual( + nested_simplify(token_classifier.aggregate(example, AggregationStrategy.SIMPLE)), + [ + {"entity_group": "PER", "score": 0.996, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 11, "end": 13}, + ], + ) + self.assertEqual( + nested_simplify(token_classifier.aggregate(example, AggregationStrategy.FIRST)), + [ + {"entity_group": "PER", "score": 0.997, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 11, "end": 13}, + ], + ) + self.assertEqual( + nested_simplify(token_classifier.aggregate(example, AggregationStrategy.MAX)), + [ + {"entity_group": "PER", "score": 0.997, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 11, "end": 13}, + ], + ) + self.assertEqual( + nested_simplify(token_classifier.aggregate(example, AggregationStrategy.AVERAGE)), + [ + {"entity_group": "PER", "score": 0.996, "word": "Enzo", "start": 0, "end": 4}, + {"entity_group": "ORG", "score": 0.999, "word": "UN", "start": 11, "end": 13}, + ], + ) + + @require_torch + def test_aggregation_strategy_example2(self): + model_name = "sshleifer/tiny-dbmdz-bert-large-cased-finetuned-conll03-english" + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) + token_classifier = pipeline(task="ner", model=model_name, tokenizer=tokenizer, framework="pt") + # Just to understand scores indexes in this test + self.assertEqual( + token_classifier.model.config.id2label, + {0: "O", 1: "B-MISC", 2: "I-MISC", 3: "B-PER", 4: "I-PER", 5: "B-ORG", 6: "I-ORG", 7: "B-LOC", 8: "I-LOC"}, + ) + example = [ + { + # Necessary for AVERAGE + "scores": np.array([0, 0.55, 0, 0.45, 0, 0, 0, 0, 0, 0]), + "is_subword": False, + "index": 1, + "word": "Ra", + "start": 0, + "end": 2, + }, + { + "scores": np.array([0, 0, 0, 0.2, 0, 0, 0, 0.8, 0, 0]), + "is_subword": True, + "word": "##ma", + "start": 2, + "end": 4, + "index": 2, + }, + { + # 4th score will have the higher average + # 4th score is B-PER for this model + # It's does not correspond to any of the subtokens. + "scores": np.array([0, 0, 0, 0.4, 0, 0, 0.6, 0, 0, 0]), + "is_subword": True, + "word": "##zotti", + "start": 11, + "end": 13, + "index": 3, + }, + ] + self.assertEqual( + token_classifier.aggregate(example, AggregationStrategy.NONE), + [ + {"end": 2, "entity": "B-MISC", "score": 0.55, "start": 0, "word": "Ra", "index": 1}, + {"end": 4, "entity": "B-LOC", "score": 0.8, "start": 2, "word": "##ma", "index": 2}, + {"end": 13, "entity": "I-ORG", "score": 0.6, "start": 11, "word": "##zotti", "index": 3}, + ], + ) + + self.assertEqual( + token_classifier.aggregate(example, AggregationStrategy.FIRST), + [{"entity_group": "MISC", "score": 0.55, "word": "Ramazotti", "start": 0, "end": 13}], + ) + self.assertEqual( + token_classifier.aggregate(example, AggregationStrategy.MAX), + [{"entity_group": "LOC", "score": 0.8, "word": "Ramazotti", "start": 0, "end": 13}], + ) + self.assertEqual( + nested_simplify(token_classifier.aggregate(example, AggregationStrategy.AVERAGE)), + [{"entity_group": "PER", "score": 0.35, "word": "Ramazotti", "start": 0, "end": 13}], + ) + + @require_torch + @slow + def test_aggregation_strategy_offsets_with_leading_space(self): + sentence = "We're from New York" + model_name = "brandon25/deberta-base-finetuned-ner" + ner = pipeline("ner", model=model_name, ignore_labels=[], aggregation_strategy="max") + self.assertEqual( + nested_simplify(ner(sentence)), + [ + {"entity_group": "O", "score": 1.0, "word": " We're from", "start": 0, "end": 10}, + {"entity_group": "LOC", "score": 1.0, "word": " New York", "start": 10, "end": 19}, + ], + ) + + @require_torch + def test_gather_pre_entities(self): + model_name = "sshleifer/tiny-dbmdz-bert-large-cased-finetuned-conll03-english" + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) + token_classifier = pipeline(task="ner", model=model_name, tokenizer=tokenizer, framework="pt") + + sentence = "Hello there" + + tokens = tokenizer( + sentence, + return_attention_mask=False, + return_tensors="pt", + truncation=True, + return_special_tokens_mask=True, + return_offsets_mapping=True, + ) + offset_mapping = tokens.pop("offset_mapping").cpu().numpy()[0] + special_tokens_mask = tokens.pop("special_tokens_mask").cpu().numpy()[0] + input_ids = tokens["input_ids"].numpy()[0] + # First element in [CLS] + scores = np.array([[1, 0, 0], [0.1, 0.3, 0.6], [0.8, 0.1, 0.1]]) + + pre_entities = token_classifier.gather_pre_entities( + sentence, + input_ids, + scores, + offset_mapping, + special_tokens_mask, + aggregation_strategy=AggregationStrategy.NONE, + ) + self.assertEqual( + nested_simplify(pre_entities), + [ + {"word": "Hello", "scores": [0.1, 0.3, 0.6], "start": 0, "end": 5, "is_subword": False, "index": 1}, + { + "word": "there", + "scores": [0.8, 0.1, 0.1], + "index": 2, + "start": 6, + "end": 11, + "is_subword": False, + }, + ], + ) + + @require_torch + def test_word_heuristic_leading_space(self): + model_name = "hf-internal-testing/tiny-random-deberta-v2" + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) + token_classifier = pipeline(task="ner", model=model_name, tokenizer=tokenizer, framework="pt") + + sentence = "I play the theremin" + + tokens = tokenizer( + sentence, + return_attention_mask=False, + return_tensors="pt", + return_special_tokens_mask=True, + return_offsets_mapping=True, + ) + offset_mapping = tokens.pop("offset_mapping").cpu().numpy()[0] + special_tokens_mask = tokens.pop("special_tokens_mask").cpu().numpy()[0] + input_ids = tokens["input_ids"].numpy()[0] + scores = np.array([[1, 0] for _ in input_ids]) # values irrelevant for heuristic + + pre_entities = token_classifier.gather_pre_entities( + sentence, + input_ids, + scores, + offset_mapping, + special_tokens_mask, + aggregation_strategy=AggregationStrategy.FIRST, + ) + + # ensure expected tokenization and correct is_subword values + self.assertEqual( + [(entity["word"], entity["is_subword"]) for entity in pre_entities], + [("▁I", False), ("▁play", False), ("▁the", False), ("▁there", False), ("min", True)], + ) + + @require_tf + def test_tf_only(self): + model_name = "hf-internal-testing/tiny-random-bert-tf-only" # This model only has a TensorFlow version + # We test that if we don't specificy framework='tf', it gets detected automatically + token_classifier = pipeline(task="ner", model=model_name) + self.assertEqual(token_classifier.framework, "tf") + + @require_tf + def test_small_model_tf(self): + model_name = "hf-internal-testing/tiny-bert-for-token-classification" + token_classifier = pipeline(task="token-classification", model=model_name, framework="tf") + outputs = token_classifier("This is a test !") + self.assertEqual( + nested_simplify(outputs), + [ + {"entity": "I-MISC", "score": 0.115, "index": 1, "word": "this", "start": 0, "end": 4}, + {"entity": "I-MISC", "score": 0.115, "index": 2, "word": "is", "start": 5, "end": 7}, + ], + ) + + @require_torch + def test_no_offset_tokenizer(self): + model_name = "hf-internal-testing/tiny-bert-for-token-classification" + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False) + token_classifier = pipeline(task="token-classification", model=model_name, tokenizer=tokenizer, framework="pt") + outputs = token_classifier("This is a test !") + self.assertEqual( + nested_simplify(outputs), + [ + {"entity": "I-MISC", "score": 0.115, "index": 1, "word": "this", "start": None, "end": None}, + {"entity": "I-MISC", "score": 0.115, "index": 2, "word": "is", "start": None, "end": None}, + ], + ) + + @require_torch + def test_small_model_pt(self): + model_name = "hf-internal-testing/tiny-bert-for-token-classification" + token_classifier = pipeline(task="token-classification", model=model_name, framework="pt") + outputs = token_classifier("This is a test !") + self.assertEqual( + nested_simplify(outputs), + [ + {"entity": "I-MISC", "score": 0.115, "index": 1, "word": "this", "start": 0, "end": 4}, + {"entity": "I-MISC", "score": 0.115, "index": 2, "word": "is", "start": 5, "end": 7}, + ], + ) + + token_classifier = pipeline( + task="token-classification", model=model_name, framework="pt", ignore_labels=["O", "I-MISC"] + ) + outputs = token_classifier("This is a test !") + self.assertEqual( + nested_simplify(outputs), + [], + ) + + token_classifier = pipeline(task="token-classification", model=model_name, framework="pt") + # Overload offset_mapping + outputs = token_classifier( + "This is a test !", offset_mapping=[(0, 0), (0, 1), (0, 2), (0, 0), (0, 0), (0, 0), (0, 0)] + ) + self.assertEqual( + nested_simplify(outputs), + [ + {"entity": "I-MISC", "score": 0.115, "index": 1, "word": "this", "start": 0, "end": 1}, + {"entity": "I-MISC", "score": 0.115, "index": 2, "word": "is", "start": 0, "end": 2}, + ], + ) + + # Batch size does not affect outputs (attention_mask are required) + sentences = ["This is a test !", "Another test this is with longer sentence"] + outputs = token_classifier(sentences) + outputs_batched = token_classifier(sentences, batch_size=2) + # Batching does not make a difference in predictions + self.assertEqual(nested_simplify(outputs_batched), nested_simplify(outputs)) + self.assertEqual( + nested_simplify(outputs_batched), + [ + [ + {"entity": "I-MISC", "score": 0.115, "index": 1, "word": "this", "start": 0, "end": 4}, + {"entity": "I-MISC", "score": 0.115, "index": 2, "word": "is", "start": 5, "end": 7}, + ], + [], + ], + ) + + @require_torch + def test_pt_ignore_subwords_slow_tokenizer_raises(self): + model_name = "sshleifer/tiny-dbmdz-bert-large-cased-finetuned-conll03-english" + tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False) + + with self.assertRaises(ValueError): + pipeline(task="ner", model=model_name, tokenizer=tokenizer, aggregation_strategy=AggregationStrategy.FIRST) + with self.assertRaises(ValueError): + pipeline( + task="ner", model=model_name, tokenizer=tokenizer, aggregation_strategy=AggregationStrategy.AVERAGE + ) + with self.assertRaises(ValueError): + pipeline(task="ner", model=model_name, tokenizer=tokenizer, aggregation_strategy=AggregationStrategy.MAX) + + @slow + @require_torch + def test_simple(self): + token_classifier = pipeline(task="ner", model="dslim/bert-base-NER", grouped_entities=True) + sentence = "Hello Sarah Jessica Parker who Jessica lives in New York" + sentence2 = "This is a simple test" + output = token_classifier(sentence) + + output_ = nested_simplify(output) + + self.assertEqual( + output_, + [ + { + "entity_group": "PER", + "score": 0.996, + "word": "Sarah Jessica Parker", + "start": 6, + "end": 26, + }, + {"entity_group": "PER", "score": 0.977, "word": "Jessica", "start": 31, "end": 38}, + {"entity_group": "LOC", "score": 0.999, "word": "New York", "start": 48, "end": 56}, + ], + ) + + output = token_classifier([sentence, sentence2]) + output_ = nested_simplify(output) + + self.assertEqual( + output_, + [ + [ + {"entity_group": "PER", "score": 0.996, "word": "Sarah Jessica Parker", "start": 6, "end": 26}, + {"entity_group": "PER", "score": 0.977, "word": "Jessica", "start": 31, "end": 38}, + {"entity_group": "LOC", "score": 0.999, "word": "New York", "start": 48, "end": 56}, + ], + [], + ], + ) + + +class TokenClassificationArgumentHandlerTestCase(unittest.TestCase): + def setUp(self): + self.args_parser = TokenClassificationArgumentHandler() + + def test_simple(self): + string = "This is a simple input" + + inputs, offset_mapping = self.args_parser(string) + self.assertEqual(inputs, [string]) + self.assertEqual(offset_mapping, None) + + inputs, offset_mapping = self.args_parser([string, string]) + self.assertEqual(inputs, [string, string]) + self.assertEqual(offset_mapping, None) + + inputs, offset_mapping = self.args_parser(string, offset_mapping=[(0, 1), (1, 2)]) + self.assertEqual(inputs, [string]) + self.assertEqual(offset_mapping, [[(0, 1), (1, 2)]]) + + inputs, offset_mapping = self.args_parser( + [string, string], offset_mapping=[[(0, 1), (1, 2)], [(0, 2), (2, 3)]] + ) + self.assertEqual(inputs, [string, string]) + self.assertEqual(offset_mapping, [[(0, 1), (1, 2)], [(0, 2), (2, 3)]]) + + def test_errors(self): + string = "This is a simple input" + + # 2 sentences, 1 offset_mapping, args + with self.assertRaises(TypeError): + self.args_parser(string, string, offset_mapping=[[(0, 1), (1, 2)]]) + + # 2 sentences, 1 offset_mapping, args + with self.assertRaises(TypeError): + self.args_parser(string, string, offset_mapping=[(0, 1), (1, 2)]) + + # 2 sentences, 1 offset_mapping, input_list + with self.assertRaises(ValueError): + self.args_parser([string, string], offset_mapping=[[(0, 1), (1, 2)]]) + + # 2 sentences, 1 offset_mapping, input_list + with self.assertRaises(ValueError): + self.args_parser([string, string], offset_mapping=[(0, 1), (1, 2)]) + + # 1 sentences, 2 offset_mapping + with self.assertRaises(ValueError): + self.args_parser(string, offset_mapping=[[(0, 1), (1, 2)], [(0, 2), (2, 3)]]) + + # 0 sentences, 1 offset_mapping + with self.assertRaises(TypeError): + self.args_parser(offset_mapping=[[(0, 1), (1, 2)]]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_translation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..61d390fe76ebc1279ed62a6475cd94b9937d1c6f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_translation.py @@ -0,0 +1,175 @@ +# 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 unittest + +import pytest + +from transformers import ( + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + MBart50TokenizerFast, + MBartConfig, + MBartForConditionalGeneration, + TranslationPipeline, + pipeline, +) +from transformers.testing_utils import is_pipeline_test, require_tf, require_torch, slow + +from .test_pipelines_common import ANY + + +@is_pipeline_test +class TranslationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + tf_model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + if isinstance(model.config, MBartConfig): + src_lang, tgt_lang = list(tokenizer.lang_code_to_id.keys())[:2] + translator = TranslationPipeline(model=model, tokenizer=tokenizer, src_lang=src_lang, tgt_lang=tgt_lang) + else: + translator = TranslationPipeline(model=model, tokenizer=tokenizer) + return translator, ["Some string", "Some other text"] + + def run_pipeline_test(self, translator, _): + outputs = translator("Some string") + self.assertEqual(outputs, [{"translation_text": ANY(str)}]) + + outputs = translator(["Some string"]) + self.assertEqual(outputs, [{"translation_text": ANY(str)}]) + + outputs = translator(["Some string", "other string"]) + self.assertEqual(outputs, [{"translation_text": ANY(str)}, {"translation_text": ANY(str)}]) + + @require_torch + def test_small_model_pt(self): + translator = pipeline("translation_en_to_ro", model="patrickvonplaten/t5-tiny-random", framework="pt") + outputs = translator("This is a test string", max_length=20) + self.assertEqual( + outputs, + [ + { + "translation_text": ( + "Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide" + " Beide Beide" + ) + } + ], + ) + + @require_tf + def test_small_model_tf(self): + translator = pipeline("translation_en_to_ro", model="patrickvonplaten/t5-tiny-random", framework="tf") + outputs = translator("This is a test string", max_length=20) + self.assertEqual( + outputs, + [ + { + "translation_text": ( + "Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide" + " Beide Beide" + ) + } + ], + ) + + @require_torch + def test_en_to_de_pt(self): + translator = pipeline("translation_en_to_de", model="patrickvonplaten/t5-tiny-random", framework="pt") + outputs = translator("This is a test string", max_length=20) + self.assertEqual( + outputs, + [ + { + "translation_text": ( + "monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine" + " urine urine urine urine urine urine urine" + ) + } + ], + ) + + @require_tf + def test_en_to_de_tf(self): + translator = pipeline("translation_en_to_de", model="patrickvonplaten/t5-tiny-random", framework="tf") + outputs = translator("This is a test string", max_length=20) + self.assertEqual( + outputs, + [ + { + "translation_text": ( + "monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine" + " urine urine urine urine urine urine urine" + ) + } + ], + ) + + +class TranslationNewFormatPipelineTests(unittest.TestCase): + @require_torch + @slow + def test_default_translations(self): + # We don't provide a default for this pair + with self.assertRaises(ValueError): + pipeline(task="translation_cn_to_ar") + + # but we do for this one + translator = pipeline(task="translation_en_to_de") + self.assertEqual(translator._preprocess_params["src_lang"], "en") + self.assertEqual(translator._preprocess_params["tgt_lang"], "de") + + @require_torch + @slow + def test_multilingual_translation(self): + model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt") + tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt") + + translator = pipeline(task="translation", model=model, tokenizer=tokenizer) + # Missing src_lang, tgt_lang + with self.assertRaises(ValueError): + translator("This is a test") + + outputs = translator("This is a test", src_lang="en_XX", tgt_lang="ar_AR") + self.assertEqual(outputs, [{"translation_text": "هذا إختبار"}]) + + outputs = translator("This is a test", src_lang="en_XX", tgt_lang="hi_IN") + self.assertEqual(outputs, [{"translation_text": "यह एक परीक्षण है"}]) + + # src_lang, tgt_lang can be defined at pipeline call time + translator = pipeline(task="translation", model=model, tokenizer=tokenizer, src_lang="en_XX", tgt_lang="ar_AR") + outputs = translator("This is a test") + self.assertEqual(outputs, [{"translation_text": "هذا إختبار"}]) + + @require_torch + def test_translation_on_odd_language(self): + model = "patrickvonplaten/t5-tiny-random" + translator = pipeline(task="translation_cn_to_ar", model=model) + self.assertEqual(translator._preprocess_params["src_lang"], "cn") + self.assertEqual(translator._preprocess_params["tgt_lang"], "ar") + + @require_torch + def test_translation_default_language_selection(self): + model = "patrickvonplaten/t5-tiny-random" + with pytest.warns(UserWarning, match=r".*translation_en_to_de.*"): + translator = pipeline(task="translation", model=model) + self.assertEqual(translator.task, "translation_en_to_de") + self.assertEqual(translator._preprocess_params["src_lang"], "en") + self.assertEqual(translator._preprocess_params["tgt_lang"], "de") + + @require_torch + def test_translation_with_no_language_no_model_fails(self): + with self.assertRaises(ValueError): + pipeline(task="translation") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_video_classification.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_video_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..33e06e30f5ae0bf829a398f42ee5d2380eaa2be1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_video_classification.py @@ -0,0 +1,98 @@ +# Copyright 2021 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 unittest + +from huggingface_hub import hf_hub_download + +from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor +from transformers.pipelines import VideoClassificationPipeline, pipeline +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_decord, + require_tf, + require_torch, + require_torch_or_tf, + require_vision, +) + +from .test_pipelines_common import ANY + + +@is_pipeline_test +@require_torch_or_tf +@require_vision +@require_decord +class VideoClassificationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + example_video_filepath = hf_hub_download( + repo_id="nateraw/video-demo", filename="archery.mp4", repo_type="dataset" + ) + video_classifier = VideoClassificationPipeline(model=model, image_processor=processor, top_k=2) + examples = [ + example_video_filepath, + "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4", + ] + return video_classifier, examples + + def run_pipeline_test(self, video_classifier, examples): + for example in examples: + outputs = video_classifier(example) + + self.assertEqual( + outputs, + [ + {"score": ANY(float), "label": ANY(str)}, + {"score": ANY(float), "label": ANY(str)}, + ], + ) + + @require_torch + def test_small_model_pt(self): + small_model = "hf-internal-testing/tiny-random-VideoMAEForVideoClassification" + small_feature_extractor = VideoMAEFeatureExtractor( + size={"shortest_edge": 10}, crop_size={"height": 10, "width": 10} + ) + video_classifier = pipeline( + "video-classification", model=small_model, feature_extractor=small_feature_extractor, frame_sampling_rate=4 + ) + + video_file_path = hf_hub_download(repo_id="nateraw/video-demo", filename="archery.mp4", repo_type="dataset") + outputs = video_classifier(video_file_path, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}], + ) + + outputs = video_classifier( + [ + video_file_path, + video_file_path, + ], + top_k=2, + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}], + [{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}], + ], + ) + + @require_tf + def test_small_model_tf(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_visual_question_answering.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_visual_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..15db1ce714b60c69811cd44e02832ccdb422515f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_visual_question_answering.py @@ -0,0 +1,178 @@ +# Copyright 2022 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 unittest + +from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available +from transformers.pipelines import pipeline +from transformers.testing_utils import ( + is_pipeline_test, + is_torch_available, + nested_simplify, + require_tf, + require_torch, + require_torch_accelerator, + require_vision, + slow, + torch_device, +) + +from .test_pipelines_common import ANY + + +if is_torch_available(): + import torch + + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +@is_pipeline_test +@require_torch +@require_vision +class VisualQuestionAnsweringPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + vqa_pipeline = pipeline("visual-question-answering", model="hf-internal-testing/tiny-vilt-random-vqa") + examples = [ + { + "image": Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), + "question": "How many cats are there?", + }, + { + "image": "./tests/fixtures/tests_samples/COCO/000000039769.png", + "question": "How many cats are there?", + }, + ] + return vqa_pipeline, examples + + def run_pipeline_test(self, vqa_pipeline, examples): + outputs = vqa_pipeline(examples, top_k=1) + self.assertEqual( + outputs, + [ + [{"score": ANY(float), "answer": ANY(str)}], + [{"score": ANY(float), "answer": ANY(str)}], + ], + ) + + @require_torch + def test_small_model_pt(self): + vqa_pipeline = pipeline("visual-question-answering", model="hf-internal-testing/tiny-vilt-random-vqa") + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + question = "How many cats are there?" + + outputs = vqa_pipeline(image=image, question="How many cats are there?", top_k=2) + self.assertEqual( + outputs, [{"score": ANY(float), "answer": ANY(str)}, {"score": ANY(float), "answer": ANY(str)}] + ) + + outputs = vqa_pipeline({"image": image, "question": question}, top_k=2) + self.assertEqual( + outputs, [{"score": ANY(float), "answer": ANY(str)}, {"score": ANY(float), "answer": ANY(str)}] + ) + + @require_torch + @require_torch_accelerator + def test_small_model_pt_blip2(self): + vqa_pipeline = pipeline( + "visual-question-answering", model="hf-internal-testing/tiny-random-Blip2ForConditionalGeneration" + ) + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + question = "How many cats are there?" + + outputs = vqa_pipeline(image=image, question=question) + self.assertEqual(outputs, [{"answer": ANY(str)}]) + + outputs = vqa_pipeline({"image": image, "question": question}) + self.assertEqual(outputs, [{"answer": ANY(str)}]) + + outputs = vqa_pipeline([{"image": image, "question": question}, {"image": image, "question": question}]) + self.assertEqual(outputs, [[{"answer": ANY(str)}]] * 2) + + vqa_pipeline = pipeline( + "visual-question-answering", + model="hf-internal-testing/tiny-random-Blip2ForConditionalGeneration", + model_kwargs={"torch_dtype": torch.float16}, + device=torch_device, + ) + self.assertEqual(vqa_pipeline.model.device, torch.device("{}:0".format(torch_device))) + self.assertEqual(vqa_pipeline.model.language_model.dtype, torch.float16) + self.assertEqual(vqa_pipeline.model.vision_model.dtype, torch.float16) + + outputs = vqa_pipeline(image=image, question=question) + self.assertEqual(outputs, [{"answer": ANY(str)}]) + + @slow + @require_torch + def test_large_model_pt(self): + vqa_pipeline = pipeline("visual-question-answering", model="dandelin/vilt-b32-finetuned-vqa") + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + question = "How many cats are there?" + + outputs = vqa_pipeline(image=image, question=question, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), [{"score": 0.8799, "answer": "2"}, {"score": 0.296, "answer": "1"}] + ) + + outputs = vqa_pipeline({"image": image, "question": question}, top_k=2) + self.assertEqual( + nested_simplify(outputs, decimals=4), [{"score": 0.8799, "answer": "2"}, {"score": 0.296, "answer": "1"}] + ) + + outputs = vqa_pipeline( + [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [[{"score": 0.8799, "answer": "2"}, {"score": 0.296, "answer": "1"}]] * 2, + ) + + @slow + @require_torch + @require_torch_accelerator + def test_large_model_pt_blip2(self): + vqa_pipeline = pipeline( + "visual-question-answering", + model="Salesforce/blip2-opt-2.7b", + model_kwargs={"torch_dtype": torch.float16}, + device=torch_device, + ) + self.assertEqual(vqa_pipeline.model.device, torch.device("{}:0".format(torch_device))) + self.assertEqual(vqa_pipeline.model.language_model.dtype, torch.float16) + + image = "./tests/fixtures/tests_samples/COCO/000000039769.png" + question = "Question: how many cats are there? Answer:" + + outputs = vqa_pipeline(image=image, question=question) + self.assertEqual(outputs, [{"answer": "two"}]) + + outputs = vqa_pipeline({"image": image, "question": question}) + self.assertEqual(outputs, [{"answer": "two"}]) + + outputs = vqa_pipeline([{"image": image, "question": question}, {"image": image, "question": question}]) + self.assertEqual(outputs, [[{"answer": "two"}]] * 2) + + @require_tf + @unittest.skip("Visual question answering not implemented in TF") + def test_small_model_tf(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..9c37014ab81d31bb55a80a01f49fbf0b6e81361b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot.py @@ -0,0 +1,307 @@ +# 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 unittest + +from transformers import ( + MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + Pipeline, + ZeroShotClassificationPipeline, + pipeline, +) +from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow + +from .test_pipelines_common import ANY + + +# These 2 model types require different inputs than those of the usual text models. +_TO_SKIP = {"LayoutLMv2Config", "LayoutLMv3Config"} + + +@is_pipeline_test +class ZeroShotClassificationPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING + tf_model_mapping = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING + + if model_mapping is not None: + model_mapping = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} + if tf_model_mapping is not None: + tf_model_mapping = { + config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP + } + + def get_test_pipeline(self, model, tokenizer, processor): + classifier = ZeroShotClassificationPipeline( + model=model, tokenizer=tokenizer, candidate_labels=["polics", "health"] + ) + return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] + + def run_pipeline_test(self, classifier, _): + outputs = classifier("Who are you voting for in 2020?", candidate_labels="politics") + self.assertEqual(outputs, {"sequence": ANY(str), "labels": [ANY(str)], "scores": [ANY(float)]}) + + # No kwarg + outputs = classifier("Who are you voting for in 2020?", ["politics"]) + self.assertEqual(outputs, {"sequence": ANY(str), "labels": [ANY(str)], "scores": [ANY(float)]}) + + outputs = classifier("Who are you voting for in 2020?", candidate_labels=["politics"]) + self.assertEqual(outputs, {"sequence": ANY(str), "labels": [ANY(str)], "scores": [ANY(float)]}) + + outputs = classifier("Who are you voting for in 2020?", candidate_labels="politics, public health") + self.assertEqual( + outputs, {"sequence": ANY(str), "labels": [ANY(str), ANY(str)], "scores": [ANY(float), ANY(float)]} + ) + self.assertAlmostEqual(sum(nested_simplify(outputs["scores"])), 1.0) + + outputs = classifier("Who are you voting for in 2020?", candidate_labels=["politics", "public health"]) + self.assertEqual( + outputs, {"sequence": ANY(str), "labels": [ANY(str), ANY(str)], "scores": [ANY(float), ANY(float)]} + ) + self.assertAlmostEqual(sum(nested_simplify(outputs["scores"])), 1.0) + + outputs = classifier( + "Who are you voting for in 2020?", candidate_labels="politics", hypothesis_template="This text is about {}" + ) + self.assertEqual(outputs, {"sequence": ANY(str), "labels": [ANY(str)], "scores": [ANY(float)]}) + + # https://github.com/huggingface/transformers/issues/13846 + outputs = classifier(["I am happy"], ["positive", "negative"]) + self.assertEqual( + outputs, + [ + {"sequence": ANY(str), "labels": [ANY(str), ANY(str)], "scores": [ANY(float), ANY(float)]} + for i in range(1) + ], + ) + outputs = classifier(["I am happy", "I am sad"], ["positive", "negative"]) + self.assertEqual( + outputs, + [ + {"sequence": ANY(str), "labels": [ANY(str), ANY(str)], "scores": [ANY(float), ANY(float)]} + for i in range(2) + ], + ) + + with self.assertRaises(ValueError): + classifier("", candidate_labels="politics") + + with self.assertRaises(TypeError): + classifier(None, candidate_labels="politics") + + with self.assertRaises(ValueError): + classifier("Who are you voting for in 2020?", candidate_labels="") + + with self.assertRaises(TypeError): + classifier("Who are you voting for in 2020?", candidate_labels=None) + + with self.assertRaises(ValueError): + classifier( + "Who are you voting for in 2020?", + candidate_labels="politics", + hypothesis_template="Not formatting template", + ) + + with self.assertRaises(AttributeError): + classifier( + "Who are you voting for in 2020?", + candidate_labels="politics", + hypothesis_template=None, + ) + + self.run_entailment_id(classifier) + + def run_entailment_id(self, zero_shot_classifier: Pipeline): + config = zero_shot_classifier.model.config + original_label2id = config.label2id + original_entailment = zero_shot_classifier.entailment_id + + config.label2id = {"LABEL_0": 0, "LABEL_1": 1, "LABEL_2": 2} + self.assertEqual(zero_shot_classifier.entailment_id, -1) + + config.label2id = {"entailment": 0, "neutral": 1, "contradiction": 2} + self.assertEqual(zero_shot_classifier.entailment_id, 0) + + config.label2id = {"ENTAIL": 0, "NON-ENTAIL": 1} + self.assertEqual(zero_shot_classifier.entailment_id, 0) + + config.label2id = {"ENTAIL": 2, "NEUTRAL": 1, "CONTR": 0} + self.assertEqual(zero_shot_classifier.entailment_id, 2) + + zero_shot_classifier.model.config.label2id = original_label2id + self.assertEqual(original_entailment, zero_shot_classifier.entailment_id) + + @require_torch + def test_truncation(self): + zero_shot_classifier = pipeline( + "zero-shot-classification", + model="sshleifer/tiny-distilbert-base-cased-distilled-squad", + framework="pt", + ) + # There was a regression in 4.10 for this + # Adding a test so we don't make the mistake again. + # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 + zero_shot_classifier( + "Who are you voting for in 2020?" * 100, candidate_labels=["politics", "public health", "science"] + ) + + @require_torch + def test_small_model_pt(self): + zero_shot_classifier = pipeline( + "zero-shot-classification", + model="sshleifer/tiny-distilbert-base-cased-distilled-squad", + framework="pt", + ) + outputs = zero_shot_classifier( + "Who are you voting for in 2020?", candidate_labels=["politics", "public health", "science"] + ) + + self.assertEqual( + nested_simplify(outputs), + { + "sequence": "Who are you voting for in 2020?", + "labels": ["science", "public health", "politics"], + "scores": [0.333, 0.333, 0.333], + }, + ) + + @require_tf + def test_small_model_tf(self): + zero_shot_classifier = pipeline( + "zero-shot-classification", + model="sshleifer/tiny-distilbert-base-cased-distilled-squad", + framework="tf", + ) + outputs = zero_shot_classifier( + "Who are you voting for in 2020?", candidate_labels=["politics", "public health", "science"] + ) + + self.assertEqual( + nested_simplify(outputs), + { + "sequence": "Who are you voting for in 2020?", + "labels": ["science", "public health", "politics"], + "scores": [0.333, 0.333, 0.333], + }, + ) + + @slow + @require_torch + def test_large_model_pt(self): + zero_shot_classifier = pipeline("zero-shot-classification", model="roberta-large-mnli", framework="pt") + outputs = zero_shot_classifier( + "Who are you voting for in 2020?", candidate_labels=["politics", "public health", "science"] + ) + + self.assertEqual( + nested_simplify(outputs), + { + "sequence": "Who are you voting for in 2020?", + "labels": ["politics", "public health", "science"], + "scores": [0.976, 0.015, 0.009], + }, + ) + outputs = zero_shot_classifier( + "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks" + " in an encoder-decoder configuration. The best performing models also connect the encoder and decoder" + " through an attention mechanism. We propose a new simple network architecture, the Transformer, based" + " solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two" + " machine translation tasks show these models to be superior in quality while being more parallelizable" + " and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014" + " English-to-German translation task, improving over the existing best results, including ensembles by" + " over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new" + " single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small" + " fraction of the training costs of the best models from the literature. We show that the Transformer" + " generalizes well to other tasks by applying it successfully to English constituency parsing both with" + " large and limited training data.", + candidate_labels=["machine learning", "statistics", "translation", "vision"], + multi_label=True, + ) + self.assertEqual( + nested_simplify(outputs), + { + "sequence": ( + "The dominant sequence transduction models are based on complex recurrent or convolutional neural" + " networks in an encoder-decoder configuration. The best performing models also connect the" + " encoder and decoder through an attention mechanism. We propose a new simple network" + " architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence" + " and convolutions entirely. Experiments on two machine translation tasks show these models to be" + " superior in quality while being more parallelizable and requiring significantly less time to" + " train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task," + " improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014" + " English-to-French translation task, our model establishes a new single-model state-of-the-art" + " BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training" + " costs of the best models from the literature. We show that the Transformer generalizes well to" + " other tasks by applying it successfully to English constituency parsing both with large and" + " limited training data." + ), + "labels": ["translation", "machine learning", "vision", "statistics"], + "scores": [0.817, 0.713, 0.018, 0.018], + }, + ) + + @slow + @require_tf + def test_large_model_tf(self): + zero_shot_classifier = pipeline("zero-shot-classification", model="roberta-large-mnli", framework="tf") + outputs = zero_shot_classifier( + "Who are you voting for in 2020?", candidate_labels=["politics", "public health", "science"] + ) + + self.assertEqual( + nested_simplify(outputs), + { + "sequence": "Who are you voting for in 2020?", + "labels": ["politics", "public health", "science"], + "scores": [0.976, 0.015, 0.009], + }, + ) + outputs = zero_shot_classifier( + "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks" + " in an encoder-decoder configuration. The best performing models also connect the encoder and decoder" + " through an attention mechanism. We propose a new simple network architecture, the Transformer, based" + " solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two" + " machine translation tasks show these models to be superior in quality while being more parallelizable" + " and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014" + " English-to-German translation task, improving over the existing best results, including ensembles by" + " over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new" + " single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small" + " fraction of the training costs of the best models from the literature. We show that the Transformer" + " generalizes well to other tasks by applying it successfully to English constituency parsing both with" + " large and limited training data.", + candidate_labels=["machine learning", "statistics", "translation", "vision"], + multi_label=True, + ) + self.assertEqual( + nested_simplify(outputs), + { + "sequence": ( + "The dominant sequence transduction models are based on complex recurrent or convolutional neural" + " networks in an encoder-decoder configuration. The best performing models also connect the" + " encoder and decoder through an attention mechanism. We propose a new simple network" + " architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence" + " and convolutions entirely. Experiments on two machine translation tasks show these models to be" + " superior in quality while being more parallelizable and requiring significantly less time to" + " train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task," + " improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014" + " English-to-French translation task, our model establishes a new single-model state-of-the-art" + " BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training" + " costs of the best models from the literature. We show that the Transformer generalizes well to" + " other tasks by applying it successfully to English constituency parsing both with large and" + " limited training data." + ), + "labels": ["translation", "machine learning", "vision", "statistics"], + "scores": [0.817, 0.713, 0.018, 0.018], + }, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_audio_classification.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_audio_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..87f91a7d27ef90c781dca506c505350ade3228f9 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_audio_classification.py @@ -0,0 +1,94 @@ +# Copyright 2023 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 unittest + +from datasets import load_dataset + +from transformers.pipelines import pipeline +from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow + + +@is_pipeline_test +@require_torch +class ZeroShotAudioClassificationPipelineTests(unittest.TestCase): + # Deactivating auto tests since we don't have a good MODEL_FOR_XX mapping, + # and only CLAP would be there for now. + # model_mapping = {CLAPConfig: CLAPModel} + + @require_torch + def test_small_model_pt(self): + audio_classifier = pipeline( + task="zero-shot-audio-classification", model="hf-internal-testing/tiny-clap-htsat-unfused" + ) + dataset = load_dataset("ashraq/esc50") + audio = dataset["train"]["audio"][-1]["array"] + output = audio_classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) + self.assertEqual( + nested_simplify(output), + [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}], + ) + + @unittest.skip("No models are available in TF") + def test_small_model_tf(self): + pass + + @slow + @require_torch + def test_large_model_pt(self): + audio_classifier = pipeline( + task="zero-shot-audio-classification", + model="laion/clap-htsat-unfused", + ) + # This is an audio of a dog + dataset = load_dataset("ashraq/esc50") + audio = dataset["train"]["audio"][-1]["array"] + output = audio_classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) + + self.assertEqual( + nested_simplify(output), + [ + {"score": 0.999, "label": "Sound of a dog"}, + {"score": 0.001, "label": "Sound of vaccum cleaner"}, + ], + ) + + output = audio_classifier([audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) + self.assertEqual( + nested_simplify(output), + [ + [ + {"score": 0.999, "label": "Sound of a dog"}, + {"score": 0.001, "label": "Sound of vaccum cleaner"}, + ], + ] + * 5, + ) + output = audio_classifier( + [audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"], batch_size=5 + ) + self.assertEqual( + nested_simplify(output), + [ + [ + {"score": 0.999, "label": "Sound of a dog"}, + {"score": 0.001, "label": "Sound of vaccum cleaner"}, + ], + ] + * 5, + ) + + @unittest.skip("No models are available in TF") + def test_large_model_tf(self): + pass diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_image_classification.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_image_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..197019f42e7b18dcd648e00b7936711736f8eca5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_image_classification.py @@ -0,0 +1,243 @@ +# Copyright 2021 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 unittest + +from transformers import is_vision_available +from transformers.pipelines import pipeline +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_torch, + require_vision, + slow, +) + +from .test_pipelines_common import ANY + + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +@is_pipeline_test +@require_vision +class ZeroShotImageClassificationPipelineTests(unittest.TestCase): + # Deactivating auto tests since we don't have a good MODEL_FOR_XX mapping, + # and only CLIP would be there for now. + # model_mapping = {CLIPConfig: CLIPModel} + + # def get_test_pipeline(self, model, tokenizer, processor): + # if tokenizer is None: + # # Side effect of no Fast Tokenizer class for these model, so skipping + # # But the slow tokenizer test should still run as they're quite small + # self.skipTest("No tokenizer available") + # return + # # return None, None + + # image_classifier = ZeroShotImageClassificationPipeline( + # model=model, tokenizer=tokenizer, feature_extractor=processor + # ) + + # # test with a raw waveform + # image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + # image2 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + # return image_classifier, [image, image2] + + # def run_pipeline_test(self, pipe, examples): + # image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + # outputs = pipe(image, candidate_labels=["A", "B"]) + # self.assertEqual(outputs, {"text": ANY(str)}) + + # # Batching + # outputs = pipe([image] * 3, batch_size=2, candidate_labels=["A", "B"]) + + @require_torch + def test_small_model_pt(self): + image_classifier = pipeline( + model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification", + ) + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + output = image_classifier(image, candidate_labels=["a", "b", "c"]) + + # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across + # python and torch versions. + self.assertIn( + nested_simplify(output), + [ + [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], + [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], + [{"score": 0.333, "label": "b"}, {"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}], + ], + ) + + output = image_classifier([image] * 5, candidate_labels=["A", "B", "C"], batch_size=2) + self.assertEqual( + nested_simplify(output), + # Pipeline outputs are supposed to be deterministic and + # So we could in theory have real values "A", "B", "C" instead + # of ANY(str). + # However it seems that in this particular case, the floating + # scores are so close, we enter floating error approximation + # and the order is not guaranteed anymore with batching. + [ + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + ], + ) + + @require_tf + def test_small_model_tf(self): + image_classifier = pipeline( + model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification", framework="tf" + ) + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + output = image_classifier(image, candidate_labels=["a", "b", "c"]) + + self.assertEqual( + nested_simplify(output), + [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], + ) + + output = image_classifier([image] * 5, candidate_labels=["A", "B", "C"], batch_size=2) + self.assertEqual( + nested_simplify(output), + # Pipeline outputs are supposed to be deterministic and + # So we could in theory have real values "A", "B", "C" instead + # of ANY(str). + # However it seems that in this particular case, the floating + # scores are so close, we enter floating error approximation + # and the order is not guaranteed anymore with batching. + [ + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + [ + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + {"score": 0.333, "label": ANY(str)}, + ], + ], + ) + + @slow + @require_torch + def test_large_model_pt(self): + image_classifier = pipeline( + task="zero-shot-image-classification", + model="openai/clip-vit-base-patch32", + ) + # This is an image of 2 cats with remotes and no planes + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + output = image_classifier(image, candidate_labels=["cat", "plane", "remote"]) + + self.assertEqual( + nested_simplify(output), + [ + {"score": 0.511, "label": "remote"}, + {"score": 0.485, "label": "cat"}, + {"score": 0.004, "label": "plane"}, + ], + ) + + output = image_classifier([image] * 5, candidate_labels=["cat", "plane", "remote"], batch_size=2) + self.assertEqual( + nested_simplify(output), + [ + [ + {"score": 0.511, "label": "remote"}, + {"score": 0.485, "label": "cat"}, + {"score": 0.004, "label": "plane"}, + ], + ] + * 5, + ) + + @slow + @require_tf + def test_large_model_tf(self): + image_classifier = pipeline( + task="zero-shot-image-classification", model="openai/clip-vit-base-patch32", framework="tf" + ) + # This is an image of 2 cats with remotes and no planes + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + output = image_classifier(image, candidate_labels=["cat", "plane", "remote"]) + self.assertEqual( + nested_simplify(output), + [ + {"score": 0.511, "label": "remote"}, + {"score": 0.485, "label": "cat"}, + {"score": 0.004, "label": "plane"}, + ], + ) + + output = image_classifier([image] * 5, candidate_labels=["cat", "plane", "remote"], batch_size=2) + self.assertEqual( + nested_simplify(output), + [ + [ + {"score": 0.511, "label": "remote"}, + {"score": 0.485, "label": "cat"}, + {"score": 0.004, "label": "plane"}, + ], + ] + * 5, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_object_detection.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_object_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b424483fa20ec384c9696cea81495b4a64bc1e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/pipelines/test_pipelines_zero_shot_object_detection.py @@ -0,0 +1,229 @@ +# Copyright 2021 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 unittest + +from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline +from transformers.testing_utils import ( + is_pipeline_test, + nested_simplify, + require_tf, + require_torch, + require_vision, + slow, +) + +from .test_pipelines_common import ANY + + +if is_vision_available(): + from PIL import Image +else: + + class Image: + @staticmethod + def open(*args, **kwargs): + pass + + +@is_pipeline_test +@require_vision +@require_torch +class ZeroShotObjectDetectionPipelineTests(unittest.TestCase): + model_mapping = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING + + def get_test_pipeline(self, model, tokenizer, processor): + object_detector = pipeline( + "zero-shot-object-detection", model="hf-internal-testing/tiny-random-owlvit-object-detection" + ) + + examples = [ + { + "image": "./tests/fixtures/tests_samples/COCO/000000039769.png", + "candidate_labels": ["cat", "remote", "couch"], + } + ] + return object_detector, examples + + def run_pipeline_test(self, object_detector, examples): + outputs = object_detector(examples[0], threshold=0.0) + + n = len(outputs) + self.assertGreater(n, 0) + self.assertEqual( + outputs, + [ + { + "score": ANY(float), + "label": ANY(str), + "box": {"xmin": ANY(int), "ymin": ANY(int), "xmax": ANY(int), "ymax": ANY(int)}, + } + for i in range(n) + ], + ) + + @require_tf + @unittest.skip("Zero Shot Object Detection not implemented in TF") + def test_small_model_tf(self): + pass + + @require_torch + def test_small_model_pt(self): + object_detector = pipeline( + "zero-shot-object-detection", model="hf-internal-testing/tiny-random-owlvit-object-detection" + ) + + outputs = object_detector( + "./tests/fixtures/tests_samples/COCO/000000039769.png", + candidate_labels=["cat", "remote", "couch"], + threshold=0.64, + ) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.7235, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, + {"score": 0.7218, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, + {"score": 0.7184, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, + {"score": 0.6748, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, + {"score": 0.6656, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, + {"score": 0.6614, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, + {"score": 0.6456, "label": "remote", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, + {"score": 0.642, "label": "remote", "box": {"xmin": 67, "ymin": 274, "xmax": 93, "ymax": 297}}, + {"score": 0.6419, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, + ], + ) + + outputs = object_detector( + [ + { + "image": "./tests/fixtures/tests_samples/COCO/000000039769.png", + "candidate_labels": ["cat", "remote", "couch"], + } + ], + threshold=0.64, + ) + + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.7235, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, + {"score": 0.7218, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, + {"score": 0.7184, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, + {"score": 0.6748, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, + {"score": 0.6656, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, + {"score": 0.6614, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, + {"score": 0.6456, "label": "remote", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, + {"score": 0.642, "label": "remote", "box": {"xmin": 67, "ymin": 274, "xmax": 93, "ymax": 297}}, + {"score": 0.6419, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, + ] + ], + ) + + @require_torch + @slow + def test_large_model_pt(self): + object_detector = pipeline("zero-shot-object-detection") + + outputs = object_detector( + "http://images.cocodataset.org/val2017/000000039769.jpg", + candidate_labels=["cat", "remote", "couch"], + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.2868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, + {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, + {"score": 0.2537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, + {"score": 0.1474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, + {"score": 0.1208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, + ], + ) + + outputs = object_detector( + [ + { + "image": "http://images.cocodataset.org/val2017/000000039769.jpg", + "candidate_labels": ["cat", "remote", "couch"], + }, + { + "image": "http://images.cocodataset.org/val2017/000000039769.jpg", + "candidate_labels": ["cat", "remote", "couch"], + }, + ], + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + [ + {"score": 0.2868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, + {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, + {"score": 0.2537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, + {"score": 0.1474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, + {"score": 0.1208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, + ], + [ + {"score": 0.2868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, + {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, + {"score": 0.2537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, + {"score": 0.1474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, + {"score": 0.1208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, + ], + ], + ) + + @require_tf + @unittest.skip("Zero Shot Object Detection not implemented in TF") + def test_large_model_tf(self): + pass + + @require_torch + @slow + def test_threshold(self): + threshold = 0.2 + object_detector = pipeline("zero-shot-object-detection") + + outputs = object_detector( + "http://images.cocodataset.org/val2017/000000039769.jpg", + candidate_labels=["cat", "remote", "couch"], + threshold=threshold, + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.2868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, + {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, + {"score": 0.2537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, + ], + ) + + @require_torch + @slow + def test_top_k(self): + top_k = 2 + object_detector = pipeline("zero-shot-object-detection") + + outputs = object_detector( + "http://images.cocodataset.org/val2017/000000039769.jpg", + candidate_labels=["cat", "remote", "couch"], + top_k=top_k, + ) + self.assertEqual( + nested_simplify(outputs, decimals=4), + [ + {"score": 0.2868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, + {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, + ], + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/autoawq/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/autoawq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/autoawq/test_awq.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/autoawq/test_awq.py new file mode 100644 index 0000000000000000000000000000000000000000..8f9cbd91aad773b0b9805471e693f8987c8fbbb2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/autoawq/test_awq.py @@ -0,0 +1,365 @@ +# coding=utf-8 +# Copyright 2023 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 gc +import tempfile +import unittest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, AwqConfig, OPTForCausalLM +from transformers.testing_utils import ( + require_accelerate, + require_auto_awq, + require_torch_gpu, + require_torch_multi_gpu, + slow, + torch_device, +) +from transformers.utils import is_accelerate_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_accelerate_available(): + from accelerate import init_empty_weights + + +@require_torch_gpu +class AwqConfigTest(unittest.TestCase): + def test_wrong_backend(self): + """ + Simple test that checks if a user passes a wrong backend an error is raised + """ + # This should work fine + _ = AwqConfig(bits=4) + + with self.assertRaises(ValueError): + AwqConfig(bits=4, backend="") + + # These should work fine + _ = AwqConfig(bits=4, version="GEMM") + _ = AwqConfig(bits=4, version="gemm") + + with self.assertRaises(ValueError): + AwqConfig(bits=4, backend="unexisting-backend") + + # LLMAWQ does not work on a T4 + with self.assertRaises(ValueError): + AwqConfig(bits=4, backend="llm-awq") + + def test_to_dict(self): + """ + Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object + """ + quantization_config = AwqConfig(bits=4) + config_to_dict = quantization_config.to_dict() + + for key in config_to_dict: + self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) + + def test_from_dict(self): + """ + Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict + """ + dict = {"bits": 2, "zero_point": False, "backend": "autoawq"} + quantization_config = AwqConfig.from_dict(dict) + + self.assertEqual(dict["bits"], quantization_config.bits) + self.assertEqual(dict["zero_point"], quantization_config.zero_point) + self.assertEqual(dict["backend"], quantization_config.backend) + + +@slow +@require_torch_gpu +@require_auto_awq +@require_accelerate +class AwqTest(unittest.TestCase): + model_name = "TheBloke/Mistral-7B-v0.1-AWQ" + dummy_transformers_model_name = "bigscience/bloom-560m" + + input_text = "Hello my name is" + + EXPECTED_OUTPUT = "Hello my name is Katie and I am a 20 year old student at the University of North Carolina at Chapel Hill. I am a junior and I am majoring in Journalism and minoring in Spanish" + EXPECTED_OUTPUT_BF16 = "Hello my name is Katie and I am a 20 year old student at the University of North Carolina at Chapel Hill. I am a junior and I am majoring in Exercise and Sport Science with a" + + device_map = "cuda" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + device_map=cls.device_map, + ) + + def tearDown(self): + gc.collect() + torch.cuda.empty_cache() + gc.collect() + + def test_quantized_model_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly + """ + from awq.modules.linear import WQLinear_GEMM, WQLinear_GEMV + + from transformers.integrations.awq import replace_with_awq_linear + + model_id = "facebook/opt-350m" + config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") + quantization_config = AwqConfig(bits=4) + + with init_empty_weights(): + model = OPTForCausalLM(config) + + nb_linears = 0 + for module in model.modules(): + if isinstance(module, torch.nn.Linear): + nb_linears += 1 + + model, _ = replace_with_awq_linear(model, quantization_config=quantization_config) + nb_awq_linear = 0 + for module in model.modules(): + if isinstance(module, (WQLinear_GEMM, WQLinear_GEMV)): + nb_awq_linear += 1 + + self.assertEqual(nb_linears, nb_awq_linear) + + # Try with `modules_not_to_convert` + with init_empty_weights(): + model = OPTForCausalLM(config) + + model, _ = replace_with_awq_linear( + model, quantization_config=quantization_config, modules_to_not_convert=["lm_head"] + ) + nb_awq_linear = 0 + for module in model.modules(): + if isinstance(module, (WQLinear_GEMM, WQLinear_GEMV)): + nb_awq_linear += 1 + + self.assertEqual(nb_linears - 1, nb_awq_linear) + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=40) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_raise_if_non_quantized(self): + model_id = "facebook/opt-125m" + quantization_config = AwqConfig(bits=4) + + with self.assertRaises(ValueError): + _ = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config) + + def test_quantized_model_bf16(self): + """ + Simple test that checks if the quantized model is working properly with bf16 + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + quantized_model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.bfloat16).to( + torch_device + ) + + output = quantized_model.generate(**input_ids, max_new_tokens=40) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT_BF16) + + def test_quantized_model_no_device_map(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + quantized_model = AutoModelForCausalLM.from_pretrained(self.model_name).to(torch_device) + output = quantized_model.generate(**input_ids, max_new_tokens=40) + + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=40) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_quantized_model_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly with multiple GPUs + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + quantized_model = AutoModelForCausalLM.from_pretrained(self.model_name, device_map="auto") + + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1, 2, 3}) + + output = quantized_model.generate(**input_ids, max_new_tokens=40) + + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + +@slow +@require_torch_gpu +@require_auto_awq +@require_accelerate +class AwqFusedTest(unittest.TestCase): + model_name = "TheBloke/Mistral-7B-OpenOrca-AWQ" + model_revision = "7048b2af77d0dd1c81b000b19d73f9cc8950b510" + + custom_mapping_model_id = "TheBloke/Yi-34B-AWQ" + custom_model_revision = "f1b2cd1b7459ceecfdc1fac5bb8725f13707c589" + + prompt = ( + "You're standing on the surface of the Earth. " + "You walk one mile south, one mile west and one mile north. " + "You end up exactly where you started. Where are you?" + ) + + EXPECTED_GENERATION = prompt + "\n\nThis is a classic puzzle that has been around for" + EXPECTED_GENERATION_CUSTOM_MODEL = "HelloWorld.java:11)\r\n\tat org" + + def tearDown(self): + gc.collect() + torch.cuda.empty_cache() + gc.collect() + + def _check_fused_modules(self, model): + has_fused_modules = False + fused_modules_name = ["QuantAttentionFused", "QuantFusedMLP", "FasterTransformerRMSNorm"] + + for _, module in model.named_modules(): + if module.__class__.__name__ in fused_modules_name: + has_fused_modules = True + break + + self.assertTrue(has_fused_modules, "Modules fusing not performed correctly!") + + def test_raise_save_pretrained(self): + """ + Test that `save_pretrained` is effectively blocked for fused models + """ + quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) + + model = AutoModelForCausalLM.from_pretrained( + self.model_name, + quantization_config=quantization_config, + low_cpu_mem_usage=True, + revision=self.model_revision, + ).to(torch_device) + + self._check_fused_modules(model) + + with self.assertRaises(ValueError), tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + def test_generation_fused(self): + """ + Test generation quality for fused models - single batch case + """ + quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) + + model = AutoModelForCausalLM.from_pretrained( + self.model_name, + quantization_config=quantization_config, + low_cpu_mem_usage=True, + revision=self.model_revision, + ).to(torch_device) + + self._check_fused_modules(model) + + tokenizer = AutoTokenizer.from_pretrained(self.model_name, revision=self.model_revision) + + inputs = tokenizer(self.prompt, return_tensors="pt").to(torch_device) + + outputs = model.generate(**inputs, max_new_tokens=12) + + self.assertEqual(tokenizer.decode(outputs[0], skip_special_tokens=True), self.EXPECTED_GENERATION) + + def test_generation_fused_batched(self): + """ + Test generation quality for fused models - multi batch case + """ + quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) + + model = AutoModelForCausalLM.from_pretrained( + self.model_name, + quantization_config=quantization_config, + low_cpu_mem_usage=True, + revision=self.model_revision, + ).to(torch_device) + + self._check_fused_modules(model) + + tokenizer = AutoTokenizer.from_pretrained(self.model_name, revision=self.model_revision) + + tokenizer.pad_token_id = tokenizer.eos_token_id + inputs = tokenizer([self.prompt, self.prompt], return_tensors="pt", padding=True).to(torch_device) + + outputs = model.generate(**inputs, max_new_tokens=12) + + self.assertEqual(tokenizer.decode(outputs[0], skip_special_tokens=True), self.EXPECTED_GENERATION) + + @require_torch_multi_gpu + def test_generation_custom_model(self): + """ + Test generation quality for fused models using custom fused map. + """ + quantization_config = AwqConfig( + bits=4, + fuse_max_seq_len=512, + modules_to_fuse={ + "attention": ["q_proj", "k_proj", "v_proj", "o_proj"], + "layernorm": ["ln1", "ln2", "norm"], + "mlp": ["gate_proj", "up_proj", "down_proj"], + "use_alibi": False, + "num_attention_heads": 56, + "num_key_value_heads": 8, + "hidden_size": 7168, + }, + ) + + model = AutoModelForCausalLM.from_pretrained( + self.custom_mapping_model_id, + quantization_config=quantization_config, + trust_remote_code=True, + device_map="balanced", + revision=self.custom_model_revision, + ) + + self._check_fused_modules(model) + + tokenizer = AutoTokenizer.from_pretrained( + self.custom_mapping_model_id, revision=self.custom_model_revision, trust_remote_code=True + ) + + prompt = "Hello" + inputs = tokenizer(prompt, return_tensors="pt").to(torch_device) + + outputs = model.generate(**inputs, max_new_tokens=12) + self.assertEqual(tokenizer.decode(outputs[0], skip_special_tokens=True), self.EXPECTED_GENERATION_CUSTOM_MODEL) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/README.md b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3c1d3a0791885a7f5283a3984112dcf5c1b230d5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/README.md @@ -0,0 +1,120 @@ +# Testing mixed int8 quantization + +![HFxbitsandbytes.png](https://cdn-uploads.huggingface.co/production/uploads/1660567705337-62441d1d9fdefb55a0b7d12c.png) + +The following is the recipe on how to effectively debug `bitsandbytes` integration on Hugging Face `transformers`. + +## Library requirements + ++ `transformers>=4.22.0` ++ `accelerate>=0.12.0` ++ `bitsandbytes>=0.31.5`. +## Hardware requirements + +The following instructions are tested with 2 NVIDIA-Tesla T4 GPUs. To run successfully `bitsandbytes` you would need a 8-bit core tensor supported GPU. Note that Turing, Ampere or newer architectures - e.g. T4, RTX20s RTX30s, A40-A100, A6000 should be supported. + +## Virutal envs + +```bash +conda create --name int8-testing python==3.8 +pip install bitsandbytes>=0.31.5 +pip install accelerate>=0.12.0 +pip install transformers>=4.23.0 +``` +if `transformers>=4.23.0` is not released yet, then use: +``` +pip install git+https://github.com/huggingface/transformers.git +``` + +## Troubleshooting + +A list of common errors: + +### Torch does not correctly do the operations on GPU + +First check that: + +```py +import torch + +vec = torch.randn(1, 2, 3).to(0) +``` + +Works without any error. If not, install torch using `conda` like: + +```bash +conda create --name int8-testing python==3.8 +conda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c conda-forge +pip install bitsandbytes>=0.31.5 +pip install accelerate>=0.12.0 +pip install transformers>=4.23.0 +``` +For the latest pytorch instructions please see [this](https://pytorch.org/get-started/locally/) + +and the snippet above should work. + +### ` bitsandbytes operations are not supported under CPU!` + +This happens when some Linear weights are set to the CPU when using `accelerate`. Please check carefully `model.hf_device_map` and make sure that there is no `Linear` module that is assigned to CPU. It is fine to have the last module (usually the Lm_head) set on CPU. + +### `To use the type as a Parameter, please correct the detach() semantics defined by __torch_dispatch__() implementation.` + +Use the latest version of `accelerate` with a command such as: `pip install -U accelerate` and the problem should be solved. + +### `Parameter has no attribue .CB` + +Same solution as above. + +### `RuntimeError: CUDA error: an illegal memory access was encountered ... consider passing CUDA_LAUNCH_BLOCKING=1` + +Run your script by pre-pending `CUDA_LAUNCH_BLOCKING=1` and you should observe an error as described in the next section. + +### `CUDA illegal memory error: an illegal memory access at line...`: + +Check the CUDA verisons with: +``` +nvcc --version +``` +and confirm it is the same version as the one detected by `bitsandbytes`. If not, run: +``` +ls -l $CONDA_PREFIX/lib/libcudart.so +``` +or +``` +ls -l $LD_LIBRARY_PATH +``` +Check if `libcudart.so` has a correct symlink that is set. Sometimes `nvcc` detects the correct CUDA version but `bitsandbytes` doesn't. You have to make sure that the symlink that is set for the file `libcudart.so` is redirected to the correct CUDA file. + +Here is an example of a badly configured CUDA installation: + +`nvcc --version` gives: + +![Screenshot 2022-08-15 at 15.12.23.png](https://cdn-uploads.huggingface.co/production/uploads/1660569220888-62441d1d9fdefb55a0b7d12c.png) + +which means that the detected CUDA version is 11.3 but `bitsandbytes` outputs: + +![image.png](https://cdn-uploads.huggingface.co/production/uploads/1660569284243-62441d1d9fdefb55a0b7d12c.png) + +First check: + +```bash +echo $LD_LIBRARY_PATH +``` + +If this contains multiple paths separated by `:`. Then you have to make sure that the correct CUDA version is set. By doing: + +```bash +ls -l $path/libcudart.so +``` + +On each path (`$path`) separated by `:`. +If not, simply run +```bash +ls -l $LD_LIBRARY_PATH/libcudart.so +``` + +and you can see + +![Screenshot 2022-08-15 at 15.12.33.png](https://cdn-uploads.huggingface.co/production/uploads/1660569176504-62441d1d9fdefb55a0b7d12c.png) + +If you see that the file is linked to the wrong CUDA version (here 10.2), find the correct location for `libcudart.so` (`find --name libcudart.so`) and replace the environment variable `LD_LIBRARY_PATH` with the one containing the correct `libcudart.so` file. \ No newline at end of file diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/test_4bit.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/test_4bit.py new file mode 100644 index 0000000000000000000000000000000000000000..a70e3d8832f3d65da91d42181c497070c207fad8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/test_4bit.py @@ -0,0 +1,523 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Team Inc. +# +# 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 clone 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 gc +import importlib.metadata +import tempfile +import unittest + +from packaging import version + +from transformers import ( + AutoModel, + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoTokenizer, + BitsAndBytesConfig, + pipeline, +) +from transformers.testing_utils import ( + is_torch_available, + require_accelerate, + require_bitsandbytes, + require_torch, + require_torch_gpu, + require_torch_multi_gpu, + slow, +) + + +def get_some_linear_layer(model): + if model.config.model_type == "gpt2": + return model.transformer.h[0].mlp.c_fc + return model.transformer.h[0].mlp.dense_4h_to_h + + +if is_torch_available(): + import torch + import torch.nn as nn + + class LoRALayer(nn.Module): + """Wraps a linear layer with LoRA-like adapter - Used for testing purposes only""" + + def __init__(self, module: nn.Module, rank: int): + super().__init__() + self.module = module + self.adapter = nn.Sequential( + nn.Linear(module.in_features, rank, bias=False), + nn.Linear(rank, module.out_features, bias=False), + ) + small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5 + nn.init.normal_(self.adapter[0].weight, std=small_std) + nn.init.zeros_(self.adapter[1].weight) + self.adapter.to(module.weight.device) + + def forward(self, input, *args, **kwargs): + return self.module(input, *args, **kwargs) + self.adapter(input) + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu +@slow +class Base4bitTest(unittest.TestCase): + # We keep the constants inside the init function and model loading inside setUp function + + # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) + # Therefore here we use only bloom-1b3 to test our module + model_name = "bigscience/bloom-1b7" + + # Constant values + EXPECTED_RELATIVE_DIFFERENCE = ( + 2.109659552692574 # This was obtained on a RTX Titan so the number might slightly change + ) + + input_text = "Hello my name is" + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I") + EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n") + EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University") + MAX_NEW_TOKENS = 10 + + def setUp(self): + # Models and tokenizer + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + +class Bnb4BitTest(Base4bitTest): + def setUp(self): + super().setUp() + + # Models and tokenizer + self.model_fp16 = AutoModelForCausalLM.from_pretrained( + self.model_name, torch_dtype=torch.float16, device_map="auto" + ) + self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.model_fp16 + del self.model_4bit + + gc.collect() + torch.cuda.empty_cache() + + def test_quantization_num_parameters(self): + r""" + Test if the number of returned parameters is correct + + See: https://github.com/huggingface/transformers/issues/25978 + """ + num_params_4bit = self.model_4bit.num_parameters() + num_params_fp16 = self.model_fp16.num_parameters() + + self.assertEqual(num_params_4bit, num_params_fp16) + + def test_quantization_config_json_serialization(self): + r""" + A simple test to check if the quantization config is correctly serialized and deserialized + """ + config = self.model_4bit.config + + self.assertTrue(hasattr(config, "quantization_config")) + + _ = config.to_dict() + _ = config.to_diff_dict() + + _ = config.to_json_string() + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from bitsandbytes.nn import Params4bit + + mem_fp16 = self.model_fp16.get_memory_footprint() + mem_4bit = self.model_4bit.get_memory_footprint() + + self.assertAlmostEqual(mem_fp16 / mem_4bit, self.EXPECTED_RELATIVE_DIFFERENCE) + linear = get_some_linear_layer(self.model_4bit) + self.assertTrue(linear.weight.__class__ == Params4bit) + + def test_original_dtype(self): + r""" + A simple test to check if the model succesfully stores the original dtype + """ + self.assertTrue(hasattr(self.model_4bit.config, "_pre_quantization_dtype")) + self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype")) + self.assertTrue(self.model_4bit.config._pre_quantization_dtype == torch.float16) + + def test_linear_are_4bit(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from transformers import T5PreTrainedModel + + self.model_fp16.get_memory_footprint() + self.model_4bit.get_memory_footprint() + + for name, module in self.model_4bit.named_modules(): + if isinstance(module, torch.nn.Linear): + if name not in ["lm_head"] + T5PreTrainedModel._keep_in_fp32_modules: + # 4-bit parameters are packed in uint8 variables + self.assertTrue(module.weight.dtype == torch.uint8) + + def test_rwkv_4bit(self): + r""" + A simple test to check if 4-bit RWKV inference works as expected. + """ + model_id = "RWKV/rwkv-4-169m-pile" + + quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_use_double_quant=True) + + model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config) + tok = AutoTokenizer.from_pretrained(model_id) + + text = "Hello my name is" + input_ids = tok.encode(text, return_tensors="pt").to(0) + + _ = model.generate(input_ids, max_new_tokens=30) + + def test_generate_quality(self): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = self.model_4bit.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality_config(self): + r""" + Test that loading the model with the config is equivalent + """ + bnb_config = BitsAndBytesConfig() + bnb_config.load_in_4bit = True + + model_4bit_from_config = AutoModelForCausalLM.from_pretrained( + self.model_name, quantization_config=bnb_config, device_map="auto" + ) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_4bit_from_config.generate( + input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_raise_on_save_pretrained(self): + r""" + Test whether trying to save a model after converting it in 8-bit will throw a warning. + """ + with self.assertRaises(NotImplementedError), tempfile.TemporaryDirectory() as tmpdirname: + self.model_4bit.save_pretrained(tmpdirname) + + def test_raise_if_config_and_load_in_4bit(self): + r""" + Test that loading the model with the config and `load_in_4bit` raises an error + """ + bnb_config = BitsAndBytesConfig() + + with self.assertRaises(ValueError): + _ = AutoModelForCausalLM.from_pretrained( + self.model_name, + quantization_config=bnb_config, + load_in_4bit=True, + device_map="auto", + bnb_4bit_quant_type="nf4", + ) + + def test_device_and_dtype_assignment(self): + r""" + Test whether trying to cast (or assigning a device to) a model after converting it in 8-bit will throw an error. + Checks also if other models are casted correctly. + """ + with self.assertRaises(ValueError): + # Tries with `str` + self.model_4bit.to("cpu") + + with self.assertRaises(ValueError): + # Tries with a `dtype`` + self.model_4bit.to(torch.float16) + + with self.assertRaises(ValueError): + # Tries with a `device` + self.model_4bit.to(torch.device("cuda:0")) + + with self.assertRaises(ValueError): + # Tries with a `device` + self.model_4bit.float() + + with self.assertRaises(ValueError): + # Tries with a `device` + self.model_4bit.half() + + # Test if we did not break anything + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + self.model_fp16 = self.model_fp16.to(torch.float32) + _ = self.model_fp16.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Check this does not throw an error + _ = self.model_fp16.to("cpu") + + # Check this does not throw an error + _ = self.model_fp16.half() + + # Check this does not throw an error + _ = self.model_fp16.float() + + def test_fp32_4bit_conversion(self): + r""" + Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + """ + model = AutoModelForSeq2SeqLM.from_pretrained("t5-small", load_in_4bit=True, device_map="auto") + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32) + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu +@slow +class Bnb4BitT5Test(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.model_name = "t5-small" + cls.dense_act_model_name = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.input_text = "Translate in German: Hello, my dog is cute" + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + gc.collect() + torch.cuda.empty_cache() + + def test_inference_without_keep_in_fp32(self): + r""" + Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + from transformers import T5ForConditionalGeneration + + modules = T5ForConditionalGeneration._keep_in_fp32_modules + T5ForConditionalGeneration._keep_in_fp32_modules = None + + # test with `t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_4bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + T5ForConditionalGeneration._keep_in_fp32_modules = modules + + def test_inference_with_keep_in_fp32(self): + r""" + Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + import bitsandbytes as bnb + + from transformers import T5ForConditionalGeneration + + # test with `t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + + # there was a bug with decoders - this test checks that it is fixed + self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear4bit)) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_4bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + + +class Classes4BitModelTest(Base4bitTest): + def setUp(self): + super().setUp() + # model_name + self.model_name = "bigscience/bloom-560m" + self.seq_to_seq_name = "t5-small" + + # Different types of model + + self.base_model = AutoModel.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + # Sequence classification model + self.sequence_model = AutoModelForSequenceClassification.from_pretrained( + self.model_name, load_in_4bit=True, device_map="auto" + ) + # CausalLM model + self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + # Seq2seq model + self.seq_to_seq_model = AutoModelForSeq2SeqLM.from_pretrained( + self.seq_to_seq_name, load_in_4bit=True, device_map="auto" + ) + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.base_model + del self.sequence_model + del self.model_4bit + del self.seq_to_seq_model + + gc.collect() + torch.cuda.empty_cache() + + def test_correct_head_class(self): + r""" + A simple test to check if the last modules for some classes (AutoModelForCausalLM or SequenceClassification) + are kept in their native class. + """ + from bitsandbytes.nn import Params4bit + + self.assertTrue(self.base_model.h[-1].mlp.dense_4h_to_h.weight.__class__ == Params4bit) + + # Other heads should be nn.Parameter + self.assertTrue(self.model_4bit.lm_head.weight.__class__ == torch.nn.Parameter) + self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) + self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) + + +class Pipeline4BitTest(Base4bitTest): + def setUp(self): + super().setUp() + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.pipe + + gc.collect() + torch.cuda.empty_cache() + + def test_pipeline(self): + r""" + The aim of this test is to verify that the mixed 4bit is compatible with `pipeline` from transformers. Since + we used pipline for inference speed benchmarking we want to make sure that this feature does not break anything + on pipline. + """ + # self._clear_cuda_cache() + self.pipe = pipeline( + "text-generation", + model=self.model_name, + model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.float16}, + max_new_tokens=self.MAX_NEW_TOKENS, + ) + + # Real second forward pass + pipeline_output = self.pipe(self.input_text) + self.assertIn(pipeline_output[0]["generated_text"], self.EXPECTED_OUTPUTS) + + +@require_torch_multi_gpu +class Bnb4bitTestMultiGpu(Base4bitTest): + def setUp(self): + super().setUp() + + def test_multi_gpu_loading(self): + r""" + This tests that the model has been loaded and can be used correctly on a multi-GPU setup. + Let's just try to load a model on 2 GPUs and see if it works. The model we test has ~2GB of total, 3GB should suffice + """ + + model_parallel = AutoModelForCausalLM.from_pretrained( + self.model_name, load_in_4bit=True, device_map="balanced" + ) + + # Check correct device map + self.assertEqual(set(model_parallel.hf_device_map.values()), {0, 1}) + + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Second real batch + output_parallel = model_parallel.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + self.assertIn(self.tokenizer.decode(output_parallel[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + +class Bnb4BitTestTraining(Base4bitTest): + def setUp(self): + self.model_name = "facebook/opt-350m" + super().setUp() + + def test_training(self): + if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.0"): + return + + # Step 1: freeze all parameters + model = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True) + + self.assertEqual(set(model.hf_device_map.values()), {torch.cuda.current_device()}) + + for param in model.parameters(): + param.requires_grad = False # freeze the model - train adapters later + if param.ndim == 1: + # cast the small parameters (e.g. layernorm) to fp32 for stability + param.data = param.data.to(torch.float32) + + # Step 2: add adapters + for _, module in model.named_modules(): + if "OPTAttention" in repr(type(module)): + module.q_proj = LoRALayer(module.q_proj, rank=16) + module.k_proj = LoRALayer(module.k_proj, rank=16) + module.v_proj = LoRALayer(module.v_proj, rank=16) + + # Step 3: dummy batch + batch = self.tokenizer("Test batch ", return_tensors="pt").to(0) + + # Step 4: Check if the gradient is not None + with torch.cuda.amp.autocast(): + out = model.forward(**batch) + out.logits.norm().backward() + + for module in model.modules(): + if isinstance(module, LoRALayer): + self.assertTrue(module.adapter[1].weight.grad is not None) + self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) + elif isinstance(module, nn.Embedding): + self.assertTrue(module.weight.grad is None) + + +class Bnb4BitGPT2Test(Bnb4BitTest): + model_name = "gpt2-xl" + EXPECTED_RELATIVE_DIFFERENCE = 3.3191854854152187 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/test_mixed_int8.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/test_mixed_int8.py new file mode 100644 index 0000000000000000000000000000000000000000..da2ce55d3105ac36eccd0b70b91ef161114dedf7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/bnb/test_mixed_int8.py @@ -0,0 +1,872 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Team Inc. +# +# 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 clone 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 gc +import importlib.metadata +import tempfile +import unittest + +from packaging import version + +from transformers import ( + AutoConfig, + AutoModel, + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoTokenizer, + BitsAndBytesConfig, + pipeline, +) +from transformers.testing_utils import ( + is_accelerate_available, + is_torch_available, + require_accelerate, + require_bitsandbytes, + require_torch, + require_torch_gpu, + require_torch_multi_gpu, + slow, +) + + +def get_some_linear_layer(model): + if model.config.model_type == "gpt2": + return model.transformer.h[0].mlp.c_fc + return model.transformer.h[0].mlp.dense_4h_to_h + + +if is_accelerate_available(): + from accelerate import PartialState + from accelerate.logging import get_logger + + logger = get_logger(__name__) + _ = PartialState() + +if is_torch_available(): + import torch + import torch.nn as nn + + class LoRALayer(nn.Module): + """Wraps a linear layer with LoRA-like adapter - Used for testing purposes only""" + + def __init__(self, module: nn.Module, rank: int): + super().__init__() + self.module = module + self.adapter = nn.Sequential( + nn.Linear(module.in_features, rank, bias=False), + nn.Linear(rank, module.out_features, bias=False), + ) + small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5 + nn.init.normal_(self.adapter[0].weight, std=small_std) + nn.init.zeros_(self.adapter[1].weight) + self.adapter.to(module.weight.device) + + def forward(self, input, *args, **kwargs): + return self.module(input, *args, **kwargs) + self.adapter(input) + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu +@slow +class BaseMixedInt8Test(unittest.TestCase): + # We keep the constants inside the init function and model loading inside setUp function + + # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) + # Therefore here we use only bloom-1b3 to test our module + model_name = "bigscience/bloom-1b7" + + # Constant values + EXPECTED_RELATIVE_DIFFERENCE = ( + 1.540025 # This was obtained on a Quadro RTX 8000 so the number might slightly change + ) + + input_text = "Hello my name is" + EXPECTED_OUTPUT = "Hello my name is John.\nI am a friend of the family.\n" + MAX_NEW_TOKENS = 10 + + def setUp(self): + # Models and tokenizer + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + +class MixedInt8Test(BaseMixedInt8Test): + def setUp(self): + super().setUp() + + # Models and tokenizer + self.model_fp16 = AutoModelForCausalLM.from_pretrained( + self.model_name, torch_dtype=torch.float16, device_map="auto" + ) + self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.model_fp16 + del self.model_8bit + + gc.collect() + torch.cuda.empty_cache() + + def test_get_keys_to_not_convert_trust_remote_code(self): + r""" + Test the `get_keys_to_not_convert` function with `trust_remote_code` models. + """ + from accelerate import init_empty_weights + + from transformers.integrations.bitsandbytes import get_keys_to_not_convert + + model_id = "mosaicml/mpt-7b" + config = AutoConfig.from_pretrained( + model_id, trust_remote_code=True, revision="ada218f9a93b5f1c6dce48a4cc9ff01fcba431e7" + ) + with init_empty_weights(): + model = AutoModelForCausalLM.from_config( + config, trust_remote_code=True, code_revision="ada218f9a93b5f1c6dce48a4cc9ff01fcba431e7" + ) + self.assertEqual(get_keys_to_not_convert(model), ["transformer.wte"]) + + def test_get_keys_to_not_convert(self): + r""" + Test the `get_keys_to_not_convert` function. + """ + from accelerate import init_empty_weights + + from transformers import AutoModelForMaskedLM, Blip2ForConditionalGeneration, MptForCausalLM, OPTForCausalLM + from transformers.integrations.bitsandbytes import get_keys_to_not_convert + + model_id = "mosaicml/mpt-7b" + config = AutoConfig.from_pretrained(model_id, revision="72e5f594ce36f9cabfa2a9fd8f58b491eb467ee7") + with init_empty_weights(): + model = MptForCausalLM(config) + # The order of the keys does not matter, so we sort them before comparing, same for the other tests. + self.assertEqual(get_keys_to_not_convert(model).sort(), ["lm_head", "transformer.wte"].sort()) + + model_id = "Salesforce/blip2-opt-2.7b" + config = AutoConfig.from_pretrained(model_id, revision="1ef7f63a8f0a144c13fdca8103eb7b4691c74cec") + with init_empty_weights(): + model = Blip2ForConditionalGeneration(config) + self.assertEqual( + get_keys_to_not_convert(model).sort(), + ["language_model.lm_head", "language_model.model.decoder.embed_tokens"].sort(), + ) + + model_id = "facebook/opt-350m" + config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") + with init_empty_weights(): + model = OPTForCausalLM(config) + self.assertEqual(get_keys_to_not_convert(model).sort(), ["lm_head", "model.decoder.embed_tokens"].sort()) + + model_id = "roberta-large" + config = AutoConfig.from_pretrained(model_id, revision="716877d372b884cad6d419d828bac6c85b3b18d9") + with init_empty_weights(): + model = AutoModelForMaskedLM.from_config(config) + self.assertEqual( + get_keys_to_not_convert(model).sort(), + ["'roberta.embeddings.word_embeddings', 'lm_head', 'lm_head.decoder"].sort(), + ) + + def test_quantization_config_json_serialization(self): + r""" + A simple test to check if the quantization config is correctly serialized and deserialized + """ + config = self.model_8bit.config + + self.assertTrue(hasattr(config, "quantization_config")) + + _ = config.to_dict() + _ = config.to_diff_dict() + + _ = config.to_json_string() + + def test_original_dtype(self): + r""" + A simple test to check if the model succesfully stores the original dtype + """ + self.assertTrue(hasattr(self.model_8bit.config, "_pre_quantization_dtype")) + self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype")) + self.assertTrue(self.model_8bit.config._pre_quantization_dtype == torch.float16) + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from bitsandbytes.nn import Int8Params + + mem_fp16 = self.model_fp16.get_memory_footprint() + mem_8bit = self.model_8bit.get_memory_footprint() + + self.assertAlmostEqual(mem_fp16 / mem_8bit, self.EXPECTED_RELATIVE_DIFFERENCE) + self.assertTrue(get_some_linear_layer(self.model_8bit).weight.__class__ == Int8Params) + + def test_linear_are_8bit(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from transformers import T5PreTrainedModel + + self.model_fp16.get_memory_footprint() + self.model_8bit.get_memory_footprint() + + for name, module in self.model_8bit.named_modules(): + if isinstance(module, torch.nn.Linear): + if name not in ["lm_head"] + T5PreTrainedModel._keep_in_fp32_modules: + self.assertTrue(module.weight.dtype == torch.int8) + + def test_llm_skip(self): + r""" + A simple test to check if `llm_int8_skip_modules` works as expected + """ + import bitsandbytes as bnb + + quantization_config = BitsAndBytesConfig(load_in_8bit=True, llm_int8_skip_modules=["classifier"]) + seq_classification_model = AutoModelForSequenceClassification.from_pretrained( + "roberta-large-mnli", quantization_config=quantization_config + ) + self.assertTrue(seq_classification_model.roberta.encoder.layer[0].output.dense.weight.dtype == torch.int8) + self.assertTrue( + isinstance(seq_classification_model.roberta.encoder.layer[0].output.dense, bnb.nn.Linear8bitLt) + ) + + self.assertTrue(isinstance(seq_classification_model.classifier.dense, nn.Linear)) + self.assertTrue(seq_classification_model.classifier.dense.weight.dtype != torch.int8) + self.assertTrue(isinstance(seq_classification_model.classifier.out_proj, nn.Linear)) + self.assertTrue(seq_classification_model.classifier.out_proj != torch.int8) + + def test_generate_quality(self): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = self.model_8bit.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + self.assertEqual(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_generate_quality_config(self): + r""" + Test that loading the model with the config is equivalent + """ + bnb_config = BitsAndBytesConfig() + bnb_config.load_in_8bit = True + + model_8bit_from_config = AutoModelForCausalLM.from_pretrained( + self.model_name, quantization_config=bnb_config, device_map="auto" + ) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_8bit_from_config.generate( + input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10 + ) + + self.assertEqual(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_raise_if_config_and_load_in_8bit(self): + r""" + Test that loading the model with the config and `load_in_8bit` raises an error + """ + bnb_config = BitsAndBytesConfig() + + with self.assertRaises(ValueError): + _ = AutoModelForCausalLM.from_pretrained( + self.model_name, + quantization_config=bnb_config, + load_in_8bit=True, + device_map="auto", + llm_int8_enable_fp32_cpu_offload=True, + ) + + def test_device_and_dtype_assignment(self): + r""" + Test whether trying to cast (or assigning a device to) a model after converting it in 8-bit will throw an error. + Checks also if other models are casted correctly. + """ + with self.assertRaises(ValueError): + # Tries with `str` + self.model_8bit.to("cpu") + + with self.assertRaises(ValueError): + # Tries with a `dtype`` + self.model_8bit.to(torch.float16) + + with self.assertRaises(ValueError): + # Tries with a `device` + self.model_8bit.to(torch.device("cuda:0")) + + with self.assertRaises(ValueError): + # Tries with a `device` + self.model_8bit.float() + + with self.assertRaises(ValueError): + # Tries with a `device` + self.model_8bit.half() + + # Test if we did not break anything + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + self.model_fp16 = self.model_fp16.to(torch.float32) + _ = self.model_fp16.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Check this does not throw an error + _ = self.model_fp16.to("cpu") + + # Check this does not throw an error + _ = self.model_fp16.half() + + # Check this does not throw an error + _ = self.model_fp16.float() + + def test_fp32_int8_conversion(self): + r""" + Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly. + """ + model = AutoModelForSeq2SeqLM.from_pretrained("t5-small", load_in_8bit=True, device_map="auto") + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32) + + def test_int8_serialization(self): + r""" + Test whether it is possible to serialize a model in 8-bit. + """ + from bitsandbytes.nn import Int8Params + + with tempfile.TemporaryDirectory() as tmpdirname: + self.model_8bit.save_pretrained(tmpdirname) + + # check that the file `quantization_config` is present + config = AutoConfig.from_pretrained(tmpdirname) + self.assertTrue(hasattr(config, "quantization_config")) + + model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, load_in_8bit=True, device_map="auto") + + linear = get_some_linear_layer(model_from_saved) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_from_saved.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + self.assertEqual( + self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUT + ) + + def test_int8_serialization_regression(self): + r""" + Test whether it is possible to serialize a model in 8-bit - using not safetensors + """ + from bitsandbytes.nn import Int8Params + + with tempfile.TemporaryDirectory() as tmpdirname: + self.model_8bit.save_pretrained(tmpdirname, safe_serialization=False) + + # check that the file `quantization_config` is present + config = AutoConfig.from_pretrained(tmpdirname) + self.assertTrue(hasattr(config, "quantization_config")) + + model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, load_in_8bit=True, device_map="auto") + + linear = get_some_linear_layer(model_from_saved) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_from_saved.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + self.assertEqual( + self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUT + ) + + def test_int8_serialization_sharded(self): + r""" + Test whether it is possible to serialize a model in 8-bit - sharded version. + """ + from bitsandbytes.nn import Int8Params + + with tempfile.TemporaryDirectory() as tmpdirname: + self.model_8bit.save_pretrained(tmpdirname, max_shard_size="200MB") + + # check that the file `quantization_config` is present + config = AutoConfig.from_pretrained(tmpdirname) + self.assertTrue(hasattr(config, "quantization_config")) + + model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname) + + linear = get_some_linear_layer(model_from_saved) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_from_saved.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + self.assertEqual( + self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUT + ) + + def test_int8_from_pretrained(self): + r""" + Test whether loading a 8bit model from the Hub works as expected + """ + from bitsandbytes.nn import Int8Params + + model_id = "ybelkada/bloom-1b7-8bit" + + model = AutoModelForCausalLM.from_pretrained(model_id) + + linear = get_some_linear_layer(model) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + self.assertEqual(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu +@slow +class MixedInt8T5Test(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.model_name = "t5-small" + cls.dense_act_model_name = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.input_text = "Translate in German: Hello, my dog is cute" + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + gc.collect() + torch.cuda.empty_cache() + + def test_inference_without_keep_in_fp32(self): + r""" + Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + from transformers import T5ForConditionalGeneration + + modules = T5ForConditionalGeneration._keep_in_fp32_modules + T5ForConditionalGeneration._keep_in_fp32_modules = None + + # test with `t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_8bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + T5ForConditionalGeneration._keep_in_fp32_modules = modules + + def test_inference_with_keep_in_fp32(self): + r""" + Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + import bitsandbytes as bnb + + from transformers import T5ForConditionalGeneration + + # test with `t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + + # there was a bug with decoders - this test checks that it is fixed + self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear8bitLt)) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_8bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + + def test_inference_with_keep_in_fp32_serialized(self): + r""" + Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly on + a serialized model. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + import bitsandbytes as bnb + + from transformers import T5ForConditionalGeneration + + # test with `t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + model = T5ForConditionalGeneration.from_pretrained(tmp_dir) + + # there was a bug with decoders - this test checks that it is fixed + self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear8bitLt)) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_8bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(0) + _ = model.generate(**encoded_input) + + +class MixedInt8ModelClassesTest(BaseMixedInt8Test): + def setUp(self): + super().setUp() + # model_name + self.model_name = "bigscience/bloom-560m" + self.seq_to_seq_name = "t5-small" + + # Different types of model + + self.base_model = AutoModel.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + # Sequence classification model + self.sequence_model = AutoModelForSequenceClassification.from_pretrained( + self.model_name, load_in_8bit=True, device_map="auto" + ) + # CausalLM model + self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + # Seq2seq model + self.seq_to_seq_model = AutoModelForSeq2SeqLM.from_pretrained( + self.seq_to_seq_name, load_in_8bit=True, device_map="auto" + ) + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.base_model + del self.sequence_model + del self.model_8bit + del self.seq_to_seq_model + + gc.collect() + torch.cuda.empty_cache() + + def test_correct_head_class(self): + r""" + A simple test to check if the last modules for some classes (AutoModelForCausalLM or SequenceClassification) + are kept in their native class. + """ + from bitsandbytes.nn import Int8Params + + # last param of a base model should be a linear8bit module + self.assertTrue(self.base_model.h[-1].mlp.dense_4h_to_h.weight.__class__ == Int8Params) + + # Other heads should be nn.Parameter + self.assertTrue(self.model_8bit.lm_head.weight.__class__ == torch.nn.Parameter) + self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) + self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) + + +class MixedInt8TestPipeline(BaseMixedInt8Test): + def setUp(self): + super().setUp() + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.pipe + + gc.collect() + torch.cuda.empty_cache() + + def test_pipeline(self): + r""" + The aim of this test is to verify that the mixed int8 is compatible with `pipeline` from transformers. Since + we used pipline for inference speed benchmarking we want to make sure that this feature does not break anything + on pipline. + """ + # self._clear_cuda_cache() + self.pipe = pipeline( + "text-generation", + model=self.model_name, + model_kwargs={"device_map": "auto", "load_in_8bit": True}, + max_new_tokens=self.MAX_NEW_TOKENS, + ) + + # Real second forward pass + pipeline_output = self.pipe(self.input_text) + self.assertEqual(pipeline_output[0]["generated_text"], self.EXPECTED_OUTPUT) + + +@require_torch_multi_gpu +class MixedInt8TestMultiGpu(BaseMixedInt8Test): + def setUp(self): + super().setUp() + + def test_multi_gpu_loading(self): + r""" + This tests that the model has been loaded and can be used correctly on a multi-GPU setup. + Let's just try to load a model on 2 GPUs and see if it works. The model we test has ~2GB of total, 3GB should suffice + """ + + model_parallel = AutoModelForCausalLM.from_pretrained( + self.model_name, load_in_8bit=True, device_map="balanced" + ) + + # Check correct device map + self.assertEqual(set(model_parallel.hf_device_map.values()), {0, 1}) + + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Second real batch + output_parallel = model_parallel.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + self.assertEqual(self.tokenizer.decode(output_parallel[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + +@require_torch_multi_gpu +class MixedInt8TestCpuGpu(BaseMixedInt8Test): + def setUp(self): + super().setUp() + + def check_inference_correctness(self, model): + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_parallel = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Get the generation + output_text = self.tokenizer.decode(output_parallel[0], skip_special_tokens=True) + self.assertEqual(output_text, self.EXPECTED_OUTPUT) + + def test_cpu_gpu_loading_random_device_map(self): + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`. + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": 0, + "lm_head": 0, + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": 0, + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 1, + "transformer.h.10": 0, + "transformer.h.11": 1, + "transformer.h.12": 0, + "transformer.h.13": 0, + "transformer.h.14": 1, + "transformer.h.15": 0, + "transformer.h.16": 0, + "transformer.h.17": 1, + "transformer.h.18": 1, + "transformer.h.19": 0, + "transformer.h.20": 1, + "transformer.h.21": 1, + "transformer.h.22": 0, + "transformer.h.23": 0, + "transformer.ln_f": 1, + } + + bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True) + + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=device_map, + quantization_config=bnb_config, + ) + + # Check that the model has been correctly set on device 0, 1, and `cpu`. + self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu"}) + + self.check_inference_correctness(model_8bit) + + def test_cpu_gpu_loading_custom_device_map(self): + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + This time the device map is more organized than the test above and uses the abstraction + `transformer.h` to encapsulate all the decoder layers. + """ + device_map = { + "transformer.word_embeddings": "cpu", + "transformer.word_embeddings_layernorm": "cpu", + "lm_head": "cpu", + "transformer.h": 0, + "transformer.ln_f": 1, + } + bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True) + + # Load model + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=device_map, + quantization_config=bnb_config, + ) + + # Check that the model has been correctly set on device 0, 1, and `cpu`. + self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu"}) + + self.check_inference_correctness(model_8bit) + + def test_cpu_gpu_disk_loading_custom_device_map(self): + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + This time we also add `disk` on the device_map. + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": "cpu", + "lm_head": 0, + "transformer.h": 1, + "transformer.ln_f": "disk", + } + bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True) + with tempfile.TemporaryDirectory() as tmpdirname: + # Load model + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=device_map, + quantization_config=bnb_config, + offload_folder=tmpdirname, + ) + + # Check that the model has been correctly set on device 0, 1, and `cpu`. + self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu", "disk"}) + + self.check_inference_correctness(model_8bit) + + def test_cpu_gpu_disk_loading_custom_device_map_kwargs(self): + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": "cpu", + "lm_head": 0, + "transformer.h": 1, + "transformer.ln_f": "disk", + } + with tempfile.TemporaryDirectory() as tmpdirname: + # Load model + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=device_map, + load_in_8bit=True, + llm_int8_enable_fp32_cpu_offload=True, + offload_folder=tmpdirname, + ) + + # Check that the model has been correctly set on device 0, 1, and `cpu`. + self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu", "disk"}) + + self.check_inference_correctness(model_8bit) + + +class MixedInt8TestTraining(BaseMixedInt8Test): + def setUp(self): + self.model_name = "facebook/opt-350m" + super().setUp() + + def test_training(self): + if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.0"): + return + + # Step 1: freeze all parameters + model = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True) + + self.assertEqual(set(model.hf_device_map.values()), {torch.cuda.current_device()}) + + for param in model.parameters(): + param.requires_grad = False # freeze the model - train adapters later + if param.ndim == 1: + # cast the small parameters (e.g. layernorm) to fp32 for stability + param.data = param.data.to(torch.float32) + + # Step 2: add adapters + for _, module in model.named_modules(): + if "OPTAttention" in repr(type(module)): + module.q_proj = LoRALayer(module.q_proj, rank=16) + module.k_proj = LoRALayer(module.k_proj, rank=16) + module.v_proj = LoRALayer(module.v_proj, rank=16) + + # Step 3: dummy batch + batch = self.tokenizer("Test batch ", return_tensors="pt").to(0) + + # Step 4: Check if the gradient is not None + with torch.cuda.amp.autocast(): + out = model.forward(**batch) + out.logits.norm().backward() + + for module in model.modules(): + if isinstance(module, LoRALayer): + self.assertTrue(module.adapter[1].weight.grad is not None) + self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) + elif isinstance(module, nn.Embedding): + self.assertTrue(module.weight.grad is None) + + +class MixedInt8GPT2Test(MixedInt8Test): + model_name = "gpt2-xl" + EXPECTED_RELATIVE_DIFFERENCE = 1.8720077507258357 + EXPECTED_OUTPUT = "Hello my name is John Doe, and I'm a big fan of" + + def test_int8_from_pretrained(self): + r""" + Test whether loading a 8bit model from the Hub works as expected + """ + from bitsandbytes.nn import Int8Params + + model_id = "ybelkada/gpt2-xl-8bit" + + model = AutoModelForCausalLM.from_pretrained(model_id) + + linear = get_some_linear_layer(model) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + self.assertEqual(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/gptq/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/gptq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/gptq/test_gptq.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/gptq/test_gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..30eae22ccdaba041f2fcd3b99ea428c6b7348964 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/quantization/gptq/test_gptq.py @@ -0,0 +1,438 @@ +# coding=utf-8 +# Copyright 2023 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 tempfile +import unittest + +import pytest + +from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig +from transformers.testing_utils import ( + is_torch_available, + require_accelerate, + require_auto_gptq, + require_optimum, + require_torch_gpu, + require_torch_multi_gpu, + slow, +) + + +if is_torch_available(): + import torch + + +class GPTQConfigTest(unittest.TestCase): + def test_bits(self): + with self.assertRaises(ValueError): + GPTQConfig(bits="") + GPTQConfig(bits=1) + GPTQConfig(bits=2) + GPTQConfig(bits=4) + + def test_dataset(self): + with self.assertRaises(ValueError): + GPTQConfig(bits=2, dataset="auto_gpt") + GPTQConfig(bits=2, dataset="c4") + GPTQConfig(bits=2, dataset="ptb-new") + + def test_damp_percent(self): + with self.assertRaises(ValueError): + GPTQConfig(bits=2, damp_percent=10) + GPTQConfig(bits=2, damp_percent=-1) + GPTQConfig(bits=2, damp_percent="0") + GPTQConfig(bits=2, damp_percent=0.01) + + def test_to_dict(self): + quantization_config = GPTQConfig(bits=2) + quantization_config.to_dict() + + def test_from_dict(self): + dict = {"bits": 2} + quantization_config = GPTQConfig.from_dict(dict) + self.assertEqual(dict["bits"], quantization_config.bits) + + @require_optimum + def test_optimum_config(self): + from optimum.gptq import GPTQQuantizer + + config = GPTQConfig(bits=2) + optimum_config = GPTQQuantizer.from_dict(config.to_dict_optimum()) + self.assertEqual(optimum_config.bits, config.bits) + new_config = GPTQConfig.from_dict_optimum(optimum_config.to_dict()) + self.assertEqual(optimum_config.bits, new_config.bits) + + +@slow +@require_optimum +@require_auto_gptq +@require_torch_gpu +class GPTQTest(unittest.TestCase): + model_name = "bigscience/bloom-560m" + + input_text = "Hello my name is" + + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I") + EXPECTED_OUTPUTS.add("Hello my name is John, I am a professional photographer and I") + EXPECTED_OUTPUTS.add("Hello my name is John, I am a student in the University of") + EXPECTED_OUTPUTS.add("Hello my name is John and I am a very good looking man.") + EXPECTED_OUTPUTS.add("Hello my name is Alyson, I am a student in the") + EXPECTED_OUTPUTS.add("Hello my name is Alyson and I am a very sweet,") + + # this seems a little small considering that we are doing 4bit quant but we have a small model and ww don't quantize the embeddings + EXPECTED_RELATIVE_DIFFERENCE = 1.664253062 + + bits = 4 + group_size = 128 + desc_act = False + use_exllama = False + + dataset = [ + "auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm." + ] + + device_map = None + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.model_fp16 = AutoModelForCausalLM.from_pretrained( + cls.model_name, torch_dtype=torch.float16, device_map=cls.device_map + ) + cls.mem_fp16 = cls.model_fp16.get_memory_footprint() + + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True) + + quantization_config = GPTQConfig( + bits=cls.bits, + dataset=cls.dataset, + tokenizer=cls.tokenizer, + group_size=cls.group_size, + desc_act=cls.desc_act, + use_exllama=cls.use_exllama, + ) + + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + torch_dtype=torch.float16, + device_map=cls.device_map, + quantization_config=quantization_config, + ) + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model + """ + + mem_quantized = self.quantized_model.get_memory_footprint() + + self.assertAlmostEqual(self.mem_fp16 / mem_quantized, self.EXPECTED_RELATIVE_DIFFERENCE) + + def test_device_and_dtype_assignment(self): + r""" + Test whether trying to cast (or assigning a device to) a model after quantization will throw an error. + Checks also if other models are casted correctly. + """ + # This should work + if self.device_map is None: + _ = self.quantized_model.to(0) + + with self.assertRaises(ValueError): + # Tries with a `dtype`` + self.quantized_model.to(torch.float16) + + def test_original_dtype(self): + r""" + A simple test to check if the model succesfully stores the original dtype + """ + self.assertTrue(hasattr(self.quantized_model.config, "_pre_quantization_dtype")) + self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype")) + self.assertTrue(self.quantized_model.config._pre_quantization_dtype == torch.float16) + + def test_quantized_layers_class(self): + """ + Simple test to check if the model conversion has been done correctly by checking on + the class type of the linear layers of the converted models + """ + from auto_gptq.utils.import_utils import dynamically_import_QuantLinear + + QuantLinear = dynamically_import_QuantLinear( + use_triton=False, + desc_act=self.desc_act, + group_size=self.group_size, + bits=self.bits, + disable_exllama=not self.use_exllama, + disable_exllamav2=True, + ) + self.assertTrue(self.quantized_model.transformer.h[0].mlp.dense_4h_to_h.__class__ == QuantLinear) + + def check_inference_correctness(self, model): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Get the generation + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def check_quantized_layers_type(self, model, value): + self.assertTrue(model.transformer.h[0].mlp.dense_4h_to_h.QUANT_TYPE == value) + + def test_generate_quality(self): + """ + Simple test to check the quality of the model by comparing the generated tokens with the expected tokens + """ + if self.device_map is None: + self.check_inference_correctness(self.quantized_model.to(0)) + else: + self.check_inference_correctness(self.quantized_model) + + def test_serialization(self): + """ + Test the serialization of the model and the loading of the quantized weights works + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + if not self.use_exllama: + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname).to(0) + self.check_quantized_layers_type(quantized_model_from_saved, "cuda-old") + else: + # we need to put it directly to the gpu. Otherwise, we won't be able to initialize the exllama kernel + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map={"": 0}) + self.check_quantized_layers_type(quantized_model_from_saved, "exllama") + self.check_inference_correctness(quantized_model_from_saved) + + @require_accelerate + def test_serialization_big_model_inference(self): + """ + Test the serialization of the model and the loading of the quantized weights with big model inference + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto") + self.check_inference_correctness(quantized_model_from_saved) + + def test_change_loading_attributes(self): + """ + Test the serialization of the model and the loading of the quantized weights works with another config file + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + if not self.use_exllama: + self.assertEqual(self.quantized_model.config.quantization_config.use_exllama, False) + # we need to put it directly to the gpu. Otherwise, we won't be able to initialize the exllama kernel + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained( + tmpdirname, quantization_config=GPTQConfig(use_exllama=True, bits=4), device_map={"": 0} + ) + self.assertEqual(quantized_model_from_saved.config.quantization_config.use_exllama, True) + self.assertEqual(quantized_model_from_saved.config.quantization_config.bits, self.bits) + self.check_quantized_layers_type(quantized_model_from_saved, "exllama") + self.check_inference_correctness(quantized_model_from_saved) + + +@require_accelerate +@require_torch_multi_gpu +class GPTQTestDeviceMap(GPTQTest): + device_map = "auto" + + +@require_accelerate +@require_torch_multi_gpu +class GPTQTestDeviceMapExllama(GPTQTest): + device_map = "auto" + use_exllama = True + + +@slow +@require_optimum +@require_auto_gptq +@require_torch_gpu +@require_accelerate +class GPTQTestActOrderExllama(unittest.TestCase): + """ + Test GPTQ model with exllama kernel and desc_act=True (also known as act-order). + More information on those arguments here: + https://huggingface.co/docs/transformers/main_classes/quantization#transformers.GPTQConfig + """ + + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is Katie and I am a 20 year") + model_name = "hf-internal-testing/Llama-2-7B-GPTQ" + revision = "gptq-4bit-128g-actorder_True" + input_text = "Hello my name is" + + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.quantization_config = GPTQConfig(bits=4, max_input_length=4028) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + revision=cls.revision, + torch_dtype=torch.float16, + device_map={"": 0}, + quantization_config=cls.quantization_config, + ) + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True) + + def check_inference_correctness(self, model): + """ + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Get the generation + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_quantized_layers_type(self): + self.assertTrue(self.quantized_model.model.layers[0].self_attn.k_proj.QUANT_TYPE == "exllama") + + def test_generate_quality(self): + """ + Simple test to check the quality of the model by comparing the generated tokens with the expected tokens + """ + self.check_inference_correctness(self.quantized_model) + + def test_max_input_length(self): + """ + Test if the max_input_length works. It modifies the maximum input length that of the model that runs with exllama backend. + """ + + prompt = "I am in Paris and" * 1000 + inp = self.tokenizer(prompt, return_tensors="pt").to(0) + self.assertTrue(inp["input_ids"].shape[1] > 4028) + with self.assertRaises(RuntimeError) as cm: + self.quantized_model.generate(**inp, num_beams=1, min_new_tokens=3, max_new_tokens=3) + self.assertTrue("temp_state buffer is too small" in str(cm.exception)) + + prompt = "I am in Paris and" * 500 + inp = self.tokenizer(prompt, return_tensors="pt").to(0) + self.assertTrue(inp["input_ids"].shape[1] < 4028) + self.quantized_model.generate(**inp, num_beams=1, min_new_tokens=3, max_new_tokens=3) + + +@slow +@require_optimum +@require_auto_gptq +@require_torch_gpu +@require_accelerate +class GPTQTestExllamaV2(unittest.TestCase): + """ + Test GPTQ model with exllamav2 kernel and desc_act=True (also known as act-order). + More information on those arguments here: + https://huggingface.co/docs/transformers/main_classes/quantization#transformers.GPTQConfig + """ + + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is Katie and I am a 20 year") + model_name = "hf-internal-testing/Llama-2-7B-GPTQ" + revision = "gptq-4bit-128g-actorder_True" + input_text = "Hello my name is" + + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.quantization_config = GPTQConfig(bits=4, exllama_config={"version": 2}) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + revision=cls.revision, + torch_dtype=torch.float16, + device_map={"": 0}, + quantization_config=cls.quantization_config, + ) + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True) + + def test_quantized_layers_type(self): + self.assertTrue(self.quantized_model.model.layers[0].self_attn.k_proj.QUANT_TYPE == "exllamav2") + + def check_inference_correctness(self, model): + """ + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Get the generation + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality(self): + """ + Simple test to check the quality of the model by comapring the the generated tokens with the expected tokens + """ + self.check_inference_correctness(self.quantized_model) + + +# fail when run all together +@pytest.mark.skip +@require_accelerate +@require_torch_multi_gpu +class GPTQTestDeviceMapCPUOffload(GPTQTest): + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": 0, + "lm_head": 0, + "transformer.h.0": 0, + "transformer.h.1": 0, + "transformer.h.2": 0, + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 0, + "transformer.h.10": 1, + "transformer.h.11": 1, + "transformer.h.12": 1, + "transformer.h.13": 1, + "transformer.h.14": 1, + "transformer.h.15": 1, + "transformer.h.16": 1, + "transformer.h.17": 0, + "transformer.h.18": "cpu", + "transformer.h.19": "cpu", + "transformer.h.20": "cpu", + "transformer.h.21": "cpu", + "transformer.h.22": "cpu", + "transformer.h.23": 1, + "transformer.ln_f": 0, + } diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_copies.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_copies.py new file mode 100644 index 0000000000000000000000000000000000000000..6afed02895a9b38eece76810950fe34113326c21 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_copies.py @@ -0,0 +1,454 @@ +# 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 os +import shutil +import sys +import tempfile +import unittest +from contextlib import contextmanager +from pathlib import Path + + +git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(git_repo_path, "utils")) + +import check_copies # noqa: E402 +from check_copies import convert_to_localized_md, find_code_in_transformers, is_copy_consistent # noqa: E402 + + +# This is the reference code that will be used in the tests. +# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. +REFERENCE_CODE = """ def __init__(self, config): + super().__init__() + self.transform = BertPredictionHeadTransform(config) + + # The output weights are the same as the input embeddings, but there is + # an output-only bias for each token. + self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + self.bias = nn.Parameter(torch.zeros(config.vocab_size)) + + # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` + self.decoder.bias = self.bias + + def forward(self, hidden_states): + hidden_states = self.transform(hidden_states) + hidden_states = self.decoder(hidden_states) + return hidden_states +""" + +MOCK_BERT_CODE = """from ...modeling_utils import PreTrainedModel + +def bert_function(x): + return x + + +class BertAttention(nn.Module): + def __init__(self, config): + super().__init__() + + +class BertModel(BertPreTrainedModel): + def __init__(self, config): + super().__init__() + self.bert = BertEncoder(config) + + @add_docstring(BERT_DOCSTRING) + def forward(self, x): + return self.bert(x) +""" + +MOCK_BERT_COPY_CODE = """from ...modeling_utils import PreTrainedModel + +# Copied from transformers.models.bert.modeling_bert.bert_function +def bert_copy_function(x): + return x + + +# Copied from transformers.models.bert.modeling_bert.BertAttention +class BertCopyAttention(nn.Module): + def __init__(self, config): + super().__init__() + + +# Copied from transformers.models.bert.modeling_bert.BertModel with Bert->BertCopy all-casing +class BertCopyModel(BertCopyPreTrainedModel): + def __init__(self, config): + super().__init__() + self.bertcopy = BertCopyEncoder(config) + + @add_docstring(BERTCOPY_DOCSTRING) + def forward(self, x): + return self.bertcopy(x) +""" + + +MOCK_DUMMY_BERT_CODE_MATCH = """ +class BertDummyModel: + attr_1 = 1 + attr_2 = 2 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def existing_common(self, c): + return 4 + + def existing_diff_to_be_ignored(self, c): + return 9 +""" + + +MOCK_DUMMY_ROBERTA_CODE_MATCH = """ +# Copied from transformers.models.dummy_bert_match.modeling_dummy_bert_match.BertDummyModel with BertDummy->RobertaBertDummy +class RobertaBertDummyModel: + + attr_1 = 1 + attr_2 = 2 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Ignore copy + def only_in_roberta_to_be_ignored(self, c): + return 3 + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def existing_common(self, c): + return 4 + + # Ignore copy + def existing_diff_to_be_ignored(self, c): + return 6 +""" + + +MOCK_DUMMY_BERT_CODE_NO_MATCH = """ +class BertDummyModel: + attr_1 = 1 + attr_2 = 2 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def only_in_bert(self, c): + return 7 + + def existing_common(self, c): + return 4 + + def existing_diff_not_ignored(self, c): + return 8 + + def existing_diff_to_be_ignored(self, c): + return 9 +""" + + +MOCK_DUMMY_ROBERTA_CODE_NO_MATCH = """ +# Copied from transformers.models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel with BertDummy->RobertaBertDummy +class RobertaBertDummyModel: + + attr_1 = 1 + attr_2 = 3 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Ignore copy + def only_in_roberta_to_be_ignored(self, c): + return 3 + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def only_in_roberta_not_ignored(self, c): + return 2 + + def existing_common(self, c): + return 4 + + def existing_diff_not_ignored(self, c): + return 5 + + # Ignore copy + def existing_diff_to_be_ignored(self, c): + return 6 +""" + + +EXPECTED_REPLACED_CODE = """ +# Copied from transformers.models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel with BertDummy->RobertaBertDummy +class RobertaBertDummyModel: + attr_1 = 1 + attr_2 = 2 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def only_in_bert(self, c): + return 7 + + def existing_common(self, c): + return 4 + + def existing_diff_not_ignored(self, c): + return 8 + + # Ignore copy + def existing_diff_to_be_ignored(self, c): + return 6 + + # Ignore copy + def only_in_roberta_to_be_ignored(self, c): + return 3 +""" + + +def replace_in_file(filename, old, new): + with open(filename, "r", encoding="utf-8") as f: + content = f.read() + + content = content.replace(old, new) + + with open(filename, "w", encoding="utf-8", newline="\n") as f: + f.write(content) + + +def create_tmp_repo(tmp_dir): + """ + Creates a mock repository in a temporary folder for testing. + """ + tmp_dir = Path(tmp_dir) + if tmp_dir.exists(): + shutil.rmtree(tmp_dir) + tmp_dir.mkdir(exist_ok=True) + + model_dir = tmp_dir / "src" / "transformers" / "models" + model_dir.mkdir(parents=True, exist_ok=True) + + models = { + "bert": MOCK_BERT_CODE, + "bertcopy": MOCK_BERT_COPY_CODE, + "dummy_bert_match": MOCK_DUMMY_BERT_CODE_MATCH, + "dummy_roberta_match": MOCK_DUMMY_ROBERTA_CODE_MATCH, + "dummy_bert_no_match": MOCK_DUMMY_BERT_CODE_NO_MATCH, + "dummy_roberta_no_match": MOCK_DUMMY_ROBERTA_CODE_NO_MATCH, + } + for model, code in models.items(): + model_subdir = model_dir / model + model_subdir.mkdir(exist_ok=True) + with open(model_subdir / f"modeling_{model}.py", "w", encoding="utf-8", newline="\n") as f: + f.write(code) + + +@contextmanager +def patch_transformer_repo_path(new_folder): + """ + Temporarily patches the variables defines in `check_copies` to use a different location for the repo. + """ + old_repo_path = check_copies.REPO_PATH + old_doc_path = check_copies.PATH_TO_DOCS + old_transformer_path = check_copies.TRANSFORMERS_PATH + repo_path = Path(new_folder).resolve() + check_copies.REPO_PATH = str(repo_path) + check_copies.PATH_TO_DOCS = str(repo_path / "docs" / "source" / "en") + check_copies.TRANSFORMERS_PATH = str(repo_path / "src" / "transformers") + try: + yield + finally: + check_copies.REPO_PATH = old_repo_path + check_copies.PATH_TO_DOCS = old_doc_path + check_copies.TRANSFORMERS_PATH = old_transformer_path + + +class CopyCheckTester(unittest.TestCase): + def test_find_code_in_transformers(self): + with tempfile.TemporaryDirectory() as tmp_folder: + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + code = find_code_in_transformers("models.bert.modeling_bert.BertAttention") + + reference_code = ( + "class BertAttention(nn.Module):\n def __init__(self, config):\n super().__init__()\n" + ) + self.assertEqual(code, reference_code) + + def test_is_copy_consistent(self): + path_to_check = ["src", "transformers", "models", "bertcopy", "modeling_bertcopy.py"] + with tempfile.TemporaryDirectory() as tmp_folder: + # Base check + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + file_to_check = os.path.join(tmp_folder, *path_to_check) + diffs = is_copy_consistent(file_to_check) + self.assertEqual(diffs, []) + + # Base check with an inconsistency + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + file_to_check = os.path.join(tmp_folder, *path_to_check) + + replace_in_file(file_to_check, "self.bertcopy(x)", "self.bert(x)") + diffs = is_copy_consistent(file_to_check) + self.assertEqual(diffs, [["models.bert.modeling_bert.BertModel", 22]]) + + _ = is_copy_consistent(file_to_check, overwrite=True) + + with open(file_to_check, "r", encoding="utf-8") as f: + self.assertEqual(f.read(), MOCK_BERT_COPY_CODE) + + def test_is_copy_consistent_with_ignored_match(self): + path_to_check = ["src", "transformers", "models", "dummy_roberta_match", "modeling_dummy_roberta_match.py"] + with tempfile.TemporaryDirectory() as tmp_folder: + # Base check + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + file_to_check = os.path.join(tmp_folder, *path_to_check) + diffs = is_copy_consistent(file_to_check) + self.assertEqual(diffs, []) + + def test_is_copy_consistent_with_ignored_no_match(self): + path_to_check = [ + "src", + "transformers", + "models", + "dummy_roberta_no_match", + "modeling_dummy_roberta_no_match.py", + ] + with tempfile.TemporaryDirectory() as tmp_folder: + # Base check with an inconsistency + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + file_to_check = os.path.join(tmp_folder, *path_to_check) + + diffs = is_copy_consistent(file_to_check) + # line 6: `attr_2 = 3` in `MOCK_DUMMY_ROBERTA_CODE_NO_MATCH`. + # (which has a leading `\n`.) + self.assertEqual( + diffs, [["models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel", 6]] + ) + + _ = is_copy_consistent(file_to_check, overwrite=True) + + with open(file_to_check, "r", encoding="utf-8") as f: + self.assertEqual(f.read(), EXPECTED_REPLACED_CODE) + + def test_convert_to_localized_md(self): + localized_readme = check_copies.LOCALIZED_READMES["README_zh-hans.md"] + + md_list = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" + " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" + " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong" + " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1." + " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace)," + " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" + " lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same" + " method has been applied to compress GPT2 into" + " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" + " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," + " Multilingual BERT into" + " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" + " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**" + " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders" + " as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang" + " Luong, Quoc V. Le, Christopher D. Manning." + ) + localized_md_list = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" + " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" + " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" + " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" + ) + converted_md_list_sample = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" + " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" + " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" + " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1." + " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文" + " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" + " lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same" + " method has been applied to compress GPT2 into" + " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" + " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," + " Multilingual BERT into" + " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" + " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自" + " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather" + " than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le," + " Christopher D. Manning 发布。\n" + ) + + num_models_equal, converted_md_list = convert_to_localized_md( + md_list, localized_md_list, localized_readme["format_model_list"] + ) + + self.assertFalse(num_models_equal) + self.assertEqual(converted_md_list, converted_md_list_sample) + + num_models_equal, converted_md_list = convert_to_localized_md( + md_list, converted_md_list, localized_readme["format_model_list"] + ) + + # Check whether the number of models is equal to README.md after conversion. + self.assertTrue(num_models_equal) + + link_changed_md_list = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" + " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" + " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong" + " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut." + ) + link_unchanged_md_list = ( + "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and" + " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" + " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" + " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" + ) + converted_md_list_sample = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" + " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" + " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" + " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" + ) + + num_models_equal, converted_md_list = convert_to_localized_md( + link_changed_md_list, link_unchanged_md_list, localized_readme["format_model_list"] + ) + + # Check if the model link is synchronized. + self.assertEqual(converted_md_list, converted_md_list_sample) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_docstrings.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..f761514a084d0087cfddb8306803f5e654f668d1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_docstrings.py @@ -0,0 +1,98 @@ +# Copyright 2023 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 inspect +import os +import sys +import unittest + + +git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(git_repo_path, "utils")) + +from check_docstrings import get_default_description, replace_default_in_arg_description # noqa: E402 + + +class CheckDostringsTested(unittest.TestCase): + def test_replace_default_in_arg_description(self): + # Standard docstring with default. + desc_with_default = "`float`, *optional*, defaults to 2.0" + self.assertEqual( + replace_default_in_arg_description(desc_with_default, 2.0), "`float`, *optional*, defaults to 2.0" + ) + self.assertEqual( + replace_default_in_arg_description(desc_with_default, 1.0), "`float`, *optional*, defaults to 1.0" + ) + self.assertEqual(replace_default_in_arg_description(desc_with_default, inspect._empty), "`float`") + + # Standard docstring with default but optional is not using the stars. + desc_with_default_typo = "`float`, `optional`, defaults to 2.0" + self.assertEqual( + replace_default_in_arg_description(desc_with_default_typo, 2.0), "`float`, *optional*, defaults to 2.0" + ) + self.assertEqual( + replace_default_in_arg_description(desc_with_default_typo, 1.0), "`float`, *optional*, defaults to 1.0" + ) + + # If the default is None we do not erase the value in the docstring. + self.assertEqual( + replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*, defaults to 2.0" + ) + # If the default is None (and set as such in the docstring), we do not include it. + desc_with_default = "`float`, *optional*, defaults to None" + self.assertEqual(replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*") + desc_with_default = "`float`, *optional*, defaults to `None`" + self.assertEqual(replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*") + + # Operations are not replaced, but put in backtiks. + desc_with_default = "`float`, *optional*, defaults to 1/255" + self.assertEqual( + replace_default_in_arg_description(desc_with_default, 1 / 255), "`float`, *optional*, defaults to `1/255`" + ) + desc_with_default = "`float`, *optional*, defaults to `1/255`" + self.assertEqual( + replace_default_in_arg_description(desc_with_default, 1 / 255), "`float`, *optional*, defaults to `1/255`" + ) + + desc_with_optional = "`float`, *optional*" + self.assertEqual( + replace_default_in_arg_description(desc_with_optional, 2.0), "`float`, *optional*, defaults to 2.0" + ) + self.assertEqual( + replace_default_in_arg_description(desc_with_optional, 1.0), "`float`, *optional*, defaults to 1.0" + ) + self.assertEqual(replace_default_in_arg_description(desc_with_optional, None), "`float`, *optional*") + self.assertEqual(replace_default_in_arg_description(desc_with_optional, inspect._empty), "`float`") + + desc_with_no_optional = "`float`" + self.assertEqual( + replace_default_in_arg_description(desc_with_no_optional, 2.0), "`float`, *optional*, defaults to 2.0" + ) + self.assertEqual( + replace_default_in_arg_description(desc_with_no_optional, 1.0), "`float`, *optional*, defaults to 1.0" + ) + self.assertEqual(replace_default_in_arg_description(desc_with_no_optional, None), "`float`, *optional*") + self.assertEqual(replace_default_in_arg_description(desc_with_no_optional, inspect._empty), "`float`") + + def test_get_default_description(self): + # Fake function to have arguments to test. + def _fake_function(a, b: int, c=1, d: float = 2.0, e: str = "blob"): + pass + + params = inspect.signature(_fake_function).parameters + assert get_default_description(params["a"]) == "``" + assert get_default_description(params["b"]) == "`int`" + assert get_default_description(params["c"]) == "``, *optional*, defaults to 1" + assert get_default_description(params["d"]) == "`float`, *optional*, defaults to 2.0" + assert get_default_description(params["e"]) == '`str`, *optional*, defaults to `"blob"`' diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_dummies.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_dummies.py new file mode 100644 index 0000000000000000000000000000000000000000..25461b2a8c1565c40198d745c3b0dba7471d5738 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_check_dummies.py @@ -0,0 +1,126 @@ +# Copyright 2022 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 os +import sys +import unittest + + +git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(git_repo_path, "utils")) + +import check_dummies # noqa: E402 +from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 + + +# Align TRANSFORMERS_PATH in check_dummies with the current path +check_dummies.PATH_TO_TRANSFORMERS = os.path.join(git_repo_path, "src", "transformers") + +DUMMY_CONSTANT = """ +{0} = None +""" + +DUMMY_CLASS = """ +class {0}(metaclass=DummyObject): + _backends = {1} + + def __init__(self, *args, **kwargs): + requires_backends(self, {1}) +""" + + +DUMMY_FUNCTION = """ +def {0}(*args, **kwargs): + requires_backends({0}, {1}) +""" + + +class CheckDummiesTester(unittest.TestCase): + def test_find_backend(self): + no_backend = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")') + self.assertIsNone(no_backend) + + simple_backend = find_backend(" if not is_tokenizers_available():") + self.assertEqual(simple_backend, "tokenizers") + + backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") + self.assertEqual(backend_with_underscore, "tensorflow_text") + + double_backend = find_backend(" if not (is_sentencepiece_available() and is_tokenizers_available()):") + self.assertEqual(double_backend, "sentencepiece_and_tokenizers") + + double_backend_with_underscore = find_backend( + " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" + ) + self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") + + triple_backend = find_backend( + " if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):" + ) + self.assertEqual(triple_backend, "sentencepiece_and_tokenizers_and_vision") + + def test_read_init(self): + objects = read_init() + # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects + self.assertIn("torch", objects) + self.assertIn("tensorflow_text", objects) + self.assertIn("sentencepiece_and_tokenizers", objects) + + # Likewise, we can't assert on the exact content of a key + self.assertIn("BertModel", objects["torch"]) + self.assertIn("TFBertModel", objects["tf"]) + self.assertIn("FlaxBertModel", objects["flax"]) + self.assertIn("BertModel", objects["torch"]) + self.assertIn("TFBertTokenizer", objects["tensorflow_text"]) + self.assertIn("convert_slow_tokenizer", objects["sentencepiece_and_tokenizers"]) + + def test_create_dummy_object(self): + dummy_constant = create_dummy_object("CONSTANT", "'torch'") + self.assertEqual(dummy_constant, "\nCONSTANT = None\n") + + dummy_function = create_dummy_object("function", "'torch'") + self.assertEqual( + dummy_function, "\ndef function(*args, **kwargs):\n requires_backends(function, 'torch')\n" + ) + + expected_dummy_class = """ +class FakeClass(metaclass=DummyObject): + _backends = 'torch' + + def __init__(self, *args, **kwargs): + requires_backends(self, 'torch') +""" + dummy_class = create_dummy_object("FakeClass", "'torch'") + self.assertEqual(dummy_class, expected_dummy_class) + + def test_create_dummy_files(self): + expected_dummy_pytorch_file = """# This file is autogenerated by the command `make fix-copies`, do not edit. +from ..utils import DummyObject, requires_backends + + +CONSTANT = None + + +def function(*args, **kwargs): + requires_backends(function, ["torch"]) + + +class FakeClass(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) +""" + dummy_files = create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]}) + self.assertEqual(dummy_files["torch"], expected_dummy_pytorch_file) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_get_test_info.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_get_test_info.py new file mode 100644 index 0000000000000000000000000000000000000000..a6d4a9984d321e68c343630a902977190a53adba --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_get_test_info.py @@ -0,0 +1,109 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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 os +import sys +import unittest + + +git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(git_repo_path, "utils")) + +import get_test_info # noqa: E402 +from get_test_info import ( # noqa: E402 + get_model_to_test_mapping, + get_model_to_tester_mapping, + get_test_to_tester_mapping, +) + + +BERT_TEST_FILE = os.path.join("tests", "models", "bert", "test_modeling_bert.py") +BLIP_TEST_FILE = os.path.join("tests", "models", "blip", "test_modeling_blip.py") + + +class GetTestInfoTester(unittest.TestCase): + def test_get_test_to_tester_mapping(self): + bert_test_tester_mapping = get_test_to_tester_mapping(BERT_TEST_FILE) + blip_test_tester_mapping = get_test_to_tester_mapping(BLIP_TEST_FILE) + + EXPECTED_BERT_MAPPING = {"BertModelTest": "BertModelTester"} + + EXPECTED_BLIP_MAPPING = { + "BlipModelTest": "BlipModelTester", + "BlipTextImageModelTest": "BlipTextImageModelsModelTester", + "BlipTextModelTest": "BlipTextModelTester", + "BlipTextRetrievalModelTest": "BlipTextRetrievalModelTester", + "BlipVQAModelTest": "BlipVQAModelTester", + "BlipVisionModelTest": "BlipVisionModelTester", + } + + self.assertEqual(get_test_info.to_json(bert_test_tester_mapping), EXPECTED_BERT_MAPPING) + self.assertEqual(get_test_info.to_json(blip_test_tester_mapping), EXPECTED_BLIP_MAPPING) + + def test_get_model_to_test_mapping(self): + bert_model_test_mapping = get_model_to_test_mapping(BERT_TEST_FILE) + blip_model_test_mapping = get_model_to_test_mapping(BLIP_TEST_FILE) + + EXPECTED_BERT_MAPPING = { + "BertForMaskedLM": ["BertModelTest"], + "BertForMultipleChoice": ["BertModelTest"], + "BertForNextSentencePrediction": ["BertModelTest"], + "BertForPreTraining": ["BertModelTest"], + "BertForQuestionAnswering": ["BertModelTest"], + "BertForSequenceClassification": ["BertModelTest"], + "BertForTokenClassification": ["BertModelTest"], + "BertLMHeadModel": ["BertModelTest"], + "BertModel": ["BertModelTest"], + } + + EXPECTED_BLIP_MAPPING = { + "BlipForConditionalGeneration": ["BlipTextImageModelTest"], + "BlipForImageTextRetrieval": ["BlipTextRetrievalModelTest"], + "BlipForQuestionAnswering": ["BlipVQAModelTest"], + "BlipModel": ["BlipModelTest"], + "BlipTextModel": ["BlipTextModelTest"], + "BlipVisionModel": ["BlipVisionModelTest"], + } + + self.assertEqual(get_test_info.to_json(bert_model_test_mapping), EXPECTED_BERT_MAPPING) + self.assertEqual(get_test_info.to_json(blip_model_test_mapping), EXPECTED_BLIP_MAPPING) + + def test_get_model_to_tester_mapping(self): + bert_model_tester_mapping = get_model_to_tester_mapping(BERT_TEST_FILE) + blip_model_tester_mapping = get_model_to_tester_mapping(BLIP_TEST_FILE) + + EXPECTED_BERT_MAPPING = { + "BertForMaskedLM": ["BertModelTester"], + "BertForMultipleChoice": ["BertModelTester"], + "BertForNextSentencePrediction": ["BertModelTester"], + "BertForPreTraining": ["BertModelTester"], + "BertForQuestionAnswering": ["BertModelTester"], + "BertForSequenceClassification": ["BertModelTester"], + "BertForTokenClassification": ["BertModelTester"], + "BertLMHeadModel": ["BertModelTester"], + "BertModel": ["BertModelTester"], + } + + EXPECTED_BLIP_MAPPING = { + "BlipForConditionalGeneration": ["BlipTextImageModelsModelTester"], + "BlipForImageTextRetrieval": ["BlipTextRetrievalModelTester"], + "BlipForQuestionAnswering": ["BlipVQAModelTester"], + "BlipModel": ["BlipModelTester"], + "BlipTextModel": ["BlipTextModelTester"], + "BlipVisionModel": ["BlipVisionModelTester"], + } + + self.assertEqual(get_test_info.to_json(bert_model_tester_mapping), EXPECTED_BERT_MAPPING) + self.assertEqual(get_test_info.to_json(blip_model_tester_mapping), EXPECTED_BLIP_MAPPING) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_tests_fetcher.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_tests_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..a897bb3f0d08285294d89beaee23b2ac1682890c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/repo_utils/test_tests_fetcher.py @@ -0,0 +1,820 @@ +# Copyright 2022 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 os +import shutil +import sys +import tempfile +import unittest +from contextlib import contextmanager +from pathlib import Path + +from git import Repo + +from transformers.testing_utils import CaptureStdout + + +REPO_PATH = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(REPO_PATH, "utils")) + +import tests_fetcher # noqa: E402 +from tests_fetcher import ( # noqa: E402 + checkout_commit, + clean_code, + create_module_to_test_map, + create_reverse_dependency_map, + create_reverse_dependency_tree, + diff_is_docstring_only, + extract_imports, + get_all_tests, + get_diff, + get_module_dependencies, + get_tree_starting_at, + infer_tests_to_run, + init_test_examples_dependencies, + parse_commit_message, + print_tree_deps_of, +) + + +BERT_MODELING_FILE = "src/transformers/models/bert/modeling_bert.py" +BERT_MODEL_FILE = """from ...modeling_utils import PreTrainedModel +from ...utils import is_torch_available +from .configuration_bert import BertConfig + +class BertModel: + ''' + This is the docstring. + ''' + This is the code +""" + +BERT_MODEL_FILE_NEW_DOCSTRING = """from ...modeling_utils import PreTrainedModel +from ...utils import is_torch_available +from .configuration_bert import BertConfig + +class BertModel: + ''' + This is the docstring. It has been updated. + ''' + This is the code +""" + +BERT_MODEL_FILE_NEW_CODE = """from ...modeling_utils import PreTrainedModel +from ...utils import is_torch_available +from .configuration_bert import BertConfig + +class BertModel: + ''' + This is the docstring. + ''' + This is the code. It has been updated +""" + + +def create_tmp_repo(tmp_dir, models=None): + """ + Creates a repository in a temporary directory mimicking the structure of Transformers. Uses the list of models + provided (which defaults to just `["bert"]`). + """ + tmp_dir = Path(tmp_dir) + if tmp_dir.exists(): + shutil.rmtree(tmp_dir) + tmp_dir.mkdir(exist_ok=True) + repo = Repo.init(tmp_dir) + + if models is None: + models = ["bert"] + class_names = [model[0].upper() + model[1:] for model in models] + + transformers_dir = tmp_dir / "src" / "transformers" + transformers_dir.mkdir(parents=True, exist_ok=True) + with open(transformers_dir / "__init__.py", "w") as f: + init_lines = ["from .utils import cached_file, is_torch_available"] + init_lines.extend( + [f"from .models.{model} import {cls}Config, {cls}Model" for model, cls in zip(models, class_names)] + ) + f.write("\n".join(init_lines) + "\n") + with open(transformers_dir / "configuration_utils.py", "w") as f: + f.write("from .utils import cached_file\n\ncode") + with open(transformers_dir / "modeling_utils.py", "w") as f: + f.write("from .utils import cached_file\n\ncode") + + utils_dir = tmp_dir / "src" / "transformers" / "utils" + utils_dir.mkdir(exist_ok=True) + with open(utils_dir / "__init__.py", "w") as f: + f.write("from .hub import cached_file\nfrom .imports import is_torch_available\n") + with open(utils_dir / "hub.py", "w") as f: + f.write("import huggingface_hub\n\ncode") + with open(utils_dir / "imports.py", "w") as f: + f.write("code") + + model_dir = tmp_dir / "src" / "transformers" / "models" + model_dir.mkdir(parents=True, exist_ok=True) + with open(model_dir / "__init__.py", "w") as f: + f.write("\n".join([f"import {model}" for model in models])) + + for model, cls in zip(models, class_names): + model_dir = tmp_dir / "src" / "transformers" / "models" / model + model_dir.mkdir(parents=True, exist_ok=True) + with open(model_dir / "__init__.py", "w") as f: + f.write(f"from .configuration_{model} import {cls}Config\nfrom .modeling_{model} import {cls}Model\n") + with open(model_dir / f"configuration_{model}.py", "w") as f: + f.write("from ...configuration_utils import PretrainedConfig\ncode") + with open(model_dir / f"modeling_{model}.py", "w") as f: + modeling_code = BERT_MODEL_FILE.replace("bert", model).replace("Bert", cls) + f.write(modeling_code) + + test_dir = tmp_dir / "tests" + test_dir.mkdir(exist_ok=True) + with open(test_dir / "test_modeling_common.py", "w") as f: + f.write("from transformers.modeling_utils import PreTrainedModel\ncode") + + for model, cls in zip(models, class_names): + test_model_dir = test_dir / "models" / model + test_model_dir.mkdir(parents=True, exist_ok=True) + (test_model_dir / "__init__.py").touch() + with open(test_model_dir / f"test_modeling_{model}.py", "w") as f: + f.write( + f"from transformers import {cls}Config, {cls}Model\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode" + ) + + example_dir = tmp_dir / "examples" + example_dir.mkdir(exist_ok=True) + for framework in ["flax", "pytorch", "tensorflow"]: + framework_dir = example_dir / framework + framework_dir.mkdir(exist_ok=True) + with open(framework_dir / f"test_{framework}_examples.py", "w") as f: + f.write("""test_args = "run_glue.py"\n""") + glue_dir = framework_dir / "text-classification" + glue_dir.mkdir(exist_ok=True) + with open(glue_dir / "run_glue.py", "w") as f: + f.write("from transformers import BertModel\n\ncode") + + repo.index.add(["examples", "src", "tests"]) + repo.index.commit("Initial commit") + repo.create_head("main") + repo.head.reference = repo.refs.main + repo.delete_head("master") + return repo + + +@contextmanager +def patch_transformer_repo_path(new_folder): + """ + Temporarily patches the variables defines in `tests_fetcher` to use a different location for the repo. + """ + old_repo_path = tests_fetcher.PATH_TO_REPO + tests_fetcher.PATH_TO_REPO = Path(new_folder).resolve() + tests_fetcher.PATH_TO_EXAMPLES = tests_fetcher.PATH_TO_REPO / "examples" + tests_fetcher.PATH_TO_TRANFORMERS = tests_fetcher.PATH_TO_REPO / "src/transformers" + tests_fetcher.PATH_TO_TESTS = tests_fetcher.PATH_TO_REPO / "tests" + try: + yield + finally: + tests_fetcher.PATH_TO_REPO = old_repo_path + tests_fetcher.PATH_TO_EXAMPLES = tests_fetcher.PATH_TO_REPO / "examples" + tests_fetcher.PATH_TO_TRANFORMERS = tests_fetcher.PATH_TO_REPO / "src/transformers" + tests_fetcher.PATH_TO_TESTS = tests_fetcher.PATH_TO_REPO / "tests" + + +def commit_changes(filenames, contents, repo, commit_message="Commit"): + """ + Commit new `contents` to `filenames` inside a given `repo`. + """ + if not isinstance(filenames, list): + filenames = [filenames] + if not isinstance(contents, list): + contents = [contents] + + folder = Path(repo.working_dir) + for filename, content in zip(filenames, contents): + with open(folder / filename, "w") as f: + f.write(content) + repo.index.add(filenames) + commit = repo.index.commit(commit_message) + return commit.hexsha + + +class TestFetcherTester(unittest.TestCase): + def test_checkout_commit(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + repo = create_tmp_repo(tmp_folder) + initial_sha = repo.head.commit.hexsha + new_sha = commit_changes(BERT_MODELING_FILE, BERT_MODEL_FILE_NEW_DOCSTRING, repo) + + assert repo.head.commit.hexsha == new_sha + with checkout_commit(repo, initial_sha): + assert repo.head.commit.hexsha == initial_sha + with open(tmp_folder / BERT_MODELING_FILE) as f: + assert f.read() == BERT_MODEL_FILE + + assert repo.head.commit.hexsha == new_sha + with open(tmp_folder / BERT_MODELING_FILE) as f: + assert f.read() == BERT_MODEL_FILE_NEW_DOCSTRING + + def test_clean_code(self): + # Clean code removes all strings in triple quotes + assert clean_code('"""\nDocstring\n"""\ncode\n"""Long string"""\ncode\n') == "code\ncode" + assert clean_code("'''\nDocstring\n'''\ncode\n'''Long string'''\ncode\n'''") == "code\ncode" + + # Clean code removes all comments + assert clean_code("code\n# Comment\ncode") == "code\ncode" + assert clean_code("code # inline comment\ncode") == "code \ncode" + + def test_get_all_tests(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + assert get_all_tests() == ["tests/models/bert", "tests/test_modeling_common.py"] + + def test_get_all_tests_on_full_repo(self): + all_tests = get_all_tests() + assert "tests/models/albert" in all_tests + assert "tests/models/bert" in all_tests + assert "tests/repo_utils" in all_tests + assert "tests/test_pipeline_mixin.py" in all_tests + assert "tests/models" not in all_tests + assert "tests/__pycache__" not in all_tests + assert "tests/models/albert/test_modeling_albert.py" not in all_tests + assert "tests/repo_utils/test_tests_fetcher.py" not in all_tests + + def test_diff_is_docstring_only(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + repo = create_tmp_repo(tmp_folder) + + branching_point = repo.refs.main.commit + bert_file = BERT_MODELING_FILE + commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING, repo) + assert diff_is_docstring_only(repo, branching_point, bert_file) + + commit_changes(bert_file, BERT_MODEL_FILE_NEW_CODE, repo) + assert not diff_is_docstring_only(repo, branching_point, bert_file) + + def test_get_diff(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + repo = create_tmp_repo(tmp_folder) + + initial_commit = repo.refs.main.commit + bert_file = BERT_MODELING_FILE + commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING, repo) + assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == [] + + commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING + "\n# Adding a comment\n", repo) + assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == [] + + commit_changes(bert_file, BERT_MODEL_FILE_NEW_CODE, repo) + assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == [ + "src/transformers/models/bert/modeling_bert.py" + ] + + commit_changes("src/transformers/utils/hub.py", "import huggingface_hub\n\nnew code", repo) + assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == ["src/transformers/utils/hub.py"] + assert get_diff(repo, repo.head.commit, [initial_commit]) == [ + "src/transformers/models/bert/modeling_bert.py", + "src/transformers/utils/hub.py", + ] + + def test_extract_imports_relative(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + expected_bert_imports = [ + ("src/transformers/modeling_utils.py", ["PreTrainedModel"]), + ("src/transformers/utils/__init__.py", ["is_torch_available"]), + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ] + expected_utils_imports = [ + ("src/transformers/utils/hub.py", ["cached_file"]), + ("src/transformers/utils/imports.py", ["is_torch_available"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + assert extract_imports("src/transformers/utils/__init__.py") == expected_utils_imports + + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from ...utils import cached_file, is_torch_available\nfrom .configuration_bert import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + # Test with multi-line imports + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from ...utils import (\n cached_file,\n is_torch_available\n)\nfrom .configuration_bert import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + def test_extract_imports_absolute(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from transformers.utils import cached_file, is_torch_available\nfrom transformers.models.bert.configuration_bert import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + # Test with multi-line imports + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from transformers.utils import (\n cached_file,\n is_torch_available\n)\nfrom transformers.models.bert.configuration_bert import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + # Test with base imports + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from transformers.utils import (\n cached_file,\n is_torch_available\n)\nfrom transformers import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/__init__.py", ["BertConfig"]), + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + def test_get_module_dependencies(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + expected_bert_dependencies = [ + "src/transformers/modeling_utils.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/utils/imports.py", + ] + with patch_transformer_repo_path(tmp_folder): + assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies + + expected_test_bert_dependencies = [ + "tests/test_modeling_common.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + ] + + with patch_transformer_repo_path(tmp_folder): + assert ( + get_module_dependencies("tests/models/bert/test_modeling_bert.py") + == expected_test_bert_dependencies + ) + + # Test with a submodule + (tmp_folder / "src/transformers/utils/logging.py").touch() + with open(tmp_folder / BERT_MODELING_FILE, "a") as f: + f.write("from ...utils import logging\n") + + expected_bert_dependencies = [ + "src/transformers/modeling_utils.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/utils/logging.py", + "src/transformers/utils/imports.py", + ] + with patch_transformer_repo_path(tmp_folder): + assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies + + # Test with an object non-imported in the init + create_tmp_repo(tmp_folder) + with open(tmp_folder / BERT_MODELING_FILE, "a") as f: + f.write("from ...utils import CONSTANT\n") + + expected_bert_dependencies = [ + "src/transformers/modeling_utils.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/utils/__init__.py", + "src/transformers/utils/imports.py", + ] + with patch_transformer_repo_path(tmp_folder): + assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies + + # Test with an example + create_tmp_repo(tmp_folder) + + expected_example_dependencies = ["src/transformers/models/bert/modeling_bert.py"] + + with patch_transformer_repo_path(tmp_folder): + assert ( + get_module_dependencies("examples/pytorch/text-classification/run_glue.py") + == expected_example_dependencies + ) + + def test_create_reverse_dependency_tree(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + tree = create_reverse_dependency_tree() + + init_edges = [ + "src/transformers/utils/hub.py", + "src/transformers/utils/imports.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + ] + assert {f for f, g in tree if g == "src/transformers/__init__.py"} == set(init_edges) + + bert_edges = [ + "src/transformers/modeling_utils.py", + "src/transformers/utils/imports.py", + "src/transformers/models/bert/configuration_bert.py", + ] + assert {f for f, g in tree if g == "src/transformers/models/bert/modeling_bert.py"} == set(bert_edges) + + test_bert_edges = [ + "tests/test_modeling_common.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + ] + assert {f for f, g in tree if g == "tests/models/bert/test_modeling_bert.py"} == set(test_bert_edges) + + def test_get_tree_starting_at(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + edges = create_reverse_dependency_tree() + + bert_tree = get_tree_starting_at("src/transformers/models/bert/modeling_bert.py", edges) + config_utils_tree = get_tree_starting_at("src/transformers/configuration_utils.py", edges) + + expected_bert_tree = [ + "src/transformers/models/bert/modeling_bert.py", + [("src/transformers/models/bert/modeling_bert.py", "tests/models/bert/test_modeling_bert.py")], + ] + assert bert_tree == expected_bert_tree + + expected_config_tree = [ + "src/transformers/configuration_utils.py", + [("src/transformers/configuration_utils.py", "src/transformers/models/bert/configuration_bert.py")], + [ + ("src/transformers/models/bert/configuration_bert.py", "tests/models/bert/test_modeling_bert.py"), + ( + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + ), + ], + ] + # Order of the edges is random + assert [set(v) for v in config_utils_tree] == [set(v) for v in expected_config_tree] + + def test_print_tree_deps_of(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + # There are two possible outputs since the order of the last two lines is non-deterministic. + expected_std_out = """src/transformers/models/bert/modeling_bert.py + tests/models/bert/test_modeling_bert.py +src/transformers/configuration_utils.py + src/transformers/models/bert/configuration_bert.py + src/transformers/models/bert/modeling_bert.py + tests/models/bert/test_modeling_bert.py""" + + expected_std_out_2 = """src/transformers/models/bert/modeling_bert.py + tests/models/bert/test_modeling_bert.py +src/transformers/configuration_utils.py + src/transformers/models/bert/configuration_bert.py + tests/models/bert/test_modeling_bert.py + src/transformers/models/bert/modeling_bert.py""" + + with patch_transformer_repo_path(tmp_folder), CaptureStdout() as cs: + print_tree_deps_of("src/transformers/models/bert/modeling_bert.py") + print_tree_deps_of("src/transformers/configuration_utils.py") + + assert cs.out.strip() in [expected_std_out, expected_std_out_2] + + def test_init_test_examples_dependencies(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + expected_example_deps = { + "examples/flax/test_flax_examples.py": [ + "examples/flax/text-classification/run_glue.py", + "examples/flax/test_flax_examples.py", + ], + "examples/pytorch/test_pytorch_examples.py": [ + "examples/pytorch/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + ], + "examples/tensorflow/test_tensorflow_examples.py": [ + "examples/tensorflow/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + ], + } + + expected_examples = { + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + + with patch_transformer_repo_path(tmp_folder): + example_deps, all_examples = init_test_examples_dependencies() + assert example_deps == expected_example_deps + assert {str(f.relative_to(tmp_folder)) for f in all_examples} == expected_examples + + def test_create_reverse_dependency_map(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + reverse_map = create_reverse_dependency_map() + + # impact of BERT modeling file (note that we stop at the inits and don't go down further) + expected_bert_deps = { + "src/transformers/__init__.py", + "src/transformers/models/bert/__init__.py", + "tests/models/bert/test_modeling_bert.py", + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + assert set(reverse_map["src/transformers/models/bert/modeling_bert.py"]) == expected_bert_deps + + # init gets the direct deps (and their recursive deps) + expected_init_deps = { + "src/transformers/utils/__init__.py", + "src/transformers/utils/hub.py", + "src/transformers/utils/imports.py", + "src/transformers/models/bert/__init__.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + "src/transformers/configuration_utils.py", + "src/transformers/modeling_utils.py", + "tests/test_modeling_common.py", + "tests/models/bert/test_modeling_bert.py", + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + assert set(reverse_map["src/transformers/__init__.py"]) == expected_init_deps + + expected_init_deps = { + "src/transformers/__init__.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + "tests/models/bert/test_modeling_bert.py", + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + assert set(reverse_map["src/transformers/models/bert/__init__.py"]) == expected_init_deps + + # Test that with more models init of bert only gets deps to bert. + create_tmp_repo(tmp_folder, models=["bert", "gpt2"]) + with patch_transformer_repo_path(tmp_folder): + reverse_map = create_reverse_dependency_map() + + # init gets the direct deps (and their recursive deps) + expected_init_deps = { + "src/transformers/__init__.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + "tests/models/bert/test_modeling_bert.py", + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + assert set(reverse_map["src/transformers/models/bert/__init__.py"]) == expected_init_deps + + def test_create_module_to_test_map(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + models = models = ["bert", "gpt2"] + [f"bert{i}" for i in range(10)] + create_tmp_repo(tmp_folder, models=models) + with patch_transformer_repo_path(tmp_folder): + test_map = create_module_to_test_map(filter_models=True) + + expected_bert_tests = { + "examples/flax/test_flax_examples.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/tensorflow/test_tensorflow_examples.py", + "tests/models/bert/test_modeling_bert.py", + } + + for model in models: + if model != "bert": + assert test_map[f"src/transformers/models/{model}/modeling_{model}.py"] == [ + f"tests/models/{model}/test_modeling_{model}.py" + ] + else: + assert set(test_map[f"src/transformers/models/{model}/modeling_{model}.py"]) == expected_bert_tests + + # Init got filtered + expected_init_tests = { + "examples/flax/test_flax_examples.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/tensorflow/test_tensorflow_examples.py", + "tests/test_modeling_common.py", + "tests/models/bert/test_modeling_bert.py", + "tests/models/gpt2/test_modeling_gpt2.py", + } + assert set(test_map["src/transformers/__init__.py"]) == expected_init_tests + + def test_infer_tests_to_run(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + models = ["bert", "gpt2"] + [f"bert{i}" for i in range(10)] + repo = create_tmp_repo(tmp_folder, models=models) + + commit_changes("src/transformers/models/bert/modeling_bert.py", BERT_MODEL_FILE_NEW_CODE, repo) + + example_tests = { + "examples/flax/test_flax_examples.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/tensorflow/test_tensorflow_examples.py", + } + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True) + with open(tmp_folder / "test-output.txt", "r") as f: + tests_to_run = f.read() + with open(tmp_folder / "examples_test_list.txt", "r") as f: + example_tests_to_run = f.read() + + assert tests_to_run == "tests/models/bert/test_modeling_bert.py" + assert set(example_tests_to_run.split(" ")) == example_tests + + # Fake a new model addition + repo = create_tmp_repo(tmp_folder, models=models) + + branch = repo.create_head("new_model") + branch.checkout() + + with open(tmp_folder / "src/transformers/__init__.py", "a") as f: + f.write("from .models.t5 import T5Config, T5Model\n") + + model_dir = tmp_folder / "src/transformers/models/t5" + model_dir.mkdir(exist_ok=True) + + with open(model_dir / "__init__.py", "w") as f: + f.write("from .configuration_t5 import T5Config\nfrom .modeling_t5 import T5Model\n") + with open(model_dir / "configuration_t5.py", "w") as f: + f.write("from ...configuration_utils import PretrainedConfig\ncode") + with open(model_dir / "modeling_t5.py", "w") as f: + modeling_code = BERT_MODEL_FILE.replace("bert", "t5").replace("Bert", "T5") + f.write(modeling_code) + + test_dir = tmp_folder / "tests/models/t5" + test_dir.mkdir(exist_ok=True) + (test_dir / "__init__.py").touch() + with open(test_dir / "test_modeling_t5.py", "w") as f: + f.write( + "from transformers import T5Config, T5Model\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode" + ) + + repo.index.add(["src", "tests"]) + repo.index.commit("Add T5 model") + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt") + with open(tmp_folder / "test-output.txt", "r") as f: + tests_to_run = f.read() + with open(tmp_folder / "examples_test_list.txt", "r") as f: + example_tests_to_run = f.read() + + expected_tests = { + "tests/models/bert/test_modeling_bert.py", + "tests/models/gpt2/test_modeling_gpt2.py", + "tests/models/t5/test_modeling_t5.py", + "tests/test_modeling_common.py", + } + assert set(tests_to_run.split(" ")) == expected_tests + assert set(example_tests_to_run.split(" ")) == example_tests + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", filter_models=False) + with open(tmp_folder / "test-output.txt", "r") as f: + tests_to_run = f.read() + with open(tmp_folder / "examples_test_list.txt", "r") as f: + example_tests_to_run = f.read() + + expected_tests = [f"tests/models/{name}/test_modeling_{name}.py" for name in models + ["t5"]] + expected_tests = set(expected_tests + ["tests/test_modeling_common.py"]) + assert set(tests_to_run.split(" ")) == expected_tests + assert set(example_tests_to_run.split(" ")) == example_tests + + def test_infer_tests_to_run_with_test_modifs(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + models = ["bert", "gpt2"] + [f"bert{i}" for i in range(10)] + repo = create_tmp_repo(tmp_folder, models=models) + + commit_changes( + "tests/models/bert/test_modeling_bert.py", + "from transformers import BertConfig, BertModel\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode1", + repo, + ) + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True) + with open(tmp_folder / "test-output.txt", "r") as f: + tests_to_run = f.read() + + assert tests_to_run == "tests/models/bert/test_modeling_bert.py" + + def test_infer_tests_to_run_with_examples_modifs(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + models = ["bert", "gpt2"] + repo = create_tmp_repo(tmp_folder, models=models) + + # Modification in one example trigger the corresponding test + commit_changes( + "examples/pytorch/text-classification/run_glue.py", + "from transformers import BertModeln\n\ncode1", + repo, + ) + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True) + with open(tmp_folder / "examples_test_list.txt", "r") as f: + example_tests_to_run = f.read() + + assert example_tests_to_run == "examples/pytorch/test_pytorch_examples.py" + + # Modification in one test example file trigger that test + repo = create_tmp_repo(tmp_folder, models=models) + commit_changes( + "examples/pytorch/test_pytorch_examples.py", + """test_args = "run_glue.py"\nmore_code""", + repo, + ) + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True) + with open(tmp_folder / "examples_test_list.txt", "r") as f: + example_tests_to_run = f.read() + + assert example_tests_to_run == "examples/pytorch/test_pytorch_examples.py" + + def test_parse_commit_message(self): + assert parse_commit_message("Normal commit") == {"skip": False, "no_filter": False, "test_all": False} + + assert parse_commit_message("[skip ci] commit") == {"skip": True, "no_filter": False, "test_all": False} + assert parse_commit_message("[ci skip] commit") == {"skip": True, "no_filter": False, "test_all": False} + assert parse_commit_message("[skip-ci] commit") == {"skip": True, "no_filter": False, "test_all": False} + assert parse_commit_message("[skip_ci] commit") == {"skip": True, "no_filter": False, "test_all": False} + + assert parse_commit_message("[no filter] commit") == {"skip": False, "no_filter": True, "test_all": False} + assert parse_commit_message("[no-filter] commit") == {"skip": False, "no_filter": True, "test_all": False} + assert parse_commit_message("[no_filter] commit") == {"skip": False, "no_filter": True, "test_all": False} + assert parse_commit_message("[filter-no] commit") == {"skip": False, "no_filter": True, "test_all": False} + + assert parse_commit_message("[test all] commit") == {"skip": False, "no_filter": False, "test_all": True} + assert parse_commit_message("[all test] commit") == {"skip": False, "no_filter": False, "test_all": True} + assert parse_commit_message("[test-all] commit") == {"skip": False, "no_filter": False, "test_all": True} + assert parse_commit_message("[all_test] commit") == {"skip": False, "no_filter": False, "test_all": True} diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/README.md b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cfbcf390b993e9b391c9077f26eb2785921d6756 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/README.md @@ -0,0 +1,148 @@ +# Testing new Hugging Face Deep Learning Container. + +This document explains the testing strategy for releasing the new Hugging Face Deep Learning Container. AWS maintains 14 days of currency with framework releases. Besides framework releases, AWS release train is bi-weekly on Monday. Code cutoff date for any changes is the Wednesday before release-Monday. + + +## Test Case 1: Releasing a New Version (Minor/Major) of 🤗 Transformers + +### Requirements: Test should run on Release Candidate for new `transformers` release to validate the new release is compatible with the DLCs. To run these tests you need credentials for the HF SageMaker AWS Account. You can ask @philschmid or @n1t0 to get access. + +### Run Tests: + +Before we can run the tests we need to adjust the `requirements.txt` for PyTorch under `/tests/sagemaker/scripts/pytorch` and for TensorFlow under `/tests/sagemaker/scripts/pytorch`. We adjust the branch to the new RC-tag. + +``` +git+https://github.com/huggingface/transformers.git@v4.5.0.rc0 # install main or adjust ist with vX.X.X for installing version specific-transforms +``` + +After we adjusted the `requirements.txt` we can run Amazon SageMaker tests with: + +```bash +AWS_PROFILE= make test-sagemaker +``` +These tests take around 10-15 minutes to finish. Preferably make a screenshot of the successfully ran tests. + +### After Transformers Release: + +After we have released the Release Candidate we need to create a PR at the [Deep Learning Container Repository](https://github.com/aws/deep-learning-containers). + +**Creating the update PR:** + +1. Update the two latest `buildspec.yaml` config for [PyTorch](https://github.com/aws/deep-learning-containers/tree/master/huggingface/pytorch) and [TensorFlow](https://github.com/aws/deep-learning-containers/tree/master/huggingface/tensorflow). The two latest `buildspec.yaml` are the `buildspec.yaml` without a version tag and the one with the highest framework version, e.g. `buildspec-1-7-1.yml` and not `buildspec-1-6.yml`. + +To update the `buildspec.yaml` we need to adjust either the `transformers_version` or the `datasets_version` or both. Example for upgrading to `transformers 4.5.0` and `datasets 1.6.0`. +```yaml +account_id: &ACCOUNT_ID +region: ®ION +base_framework: &BASE_FRAMEWORK pytorch +framework: &FRAMEWORK !join [ "huggingface_", *BASE_FRAMEWORK] +version: &VERSION 1.6.0 +short_version: &SHORT_VERSION 1.6 + +repository_info: + training_repository: &TRAINING_REPOSITORY + image_type: &TRAINING_IMAGE_TYPE training + root: !join [ "huggingface/", *BASE_FRAMEWORK, "/", *TRAINING_IMAGE_TYPE ] + repository_name: &REPOSITORY_NAME !join ["pr", "-", "huggingface", "-", *BASE_FRAMEWORK, "-", *TRAINING_IMAGE_TYPE] + repository: &REPOSITORY !join [ *ACCOUNT_ID, .dkr.ecr., *REGION, .amazonaws.com/, + *REPOSITORY_NAME ] + +images: + BuildHuggingFacePytorchGpuPy37Cu110TrainingDockerImage: + <<: *TRAINING_REPOSITORY + build: &HUGGINGFACE_PYTORCH_GPU_TRAINING_PY3 false + image_size_baseline: &IMAGE_SIZE_BASELINE 15000 + device_type: &DEVICE_TYPE gpu + python_version: &DOCKER_PYTHON_VERSION py3 + tag_python_version: &TAG_PYTHON_VERSION py36 + cuda_version: &CUDA_VERSION cu110 + os_version: &OS_VERSION ubuntu18.04 + transformers_version: &TRANSFORMERS_VERSION 4.5.0 # this was adjusted from 4.4.2 to 4.5.0 + datasets_version: &DATASETS_VERSION 1.6.0 # this was adjusted from 1.5.0 to 1.6.0 + tag: !join [ *VERSION, '-', 'transformers', *TRANSFORMERS_VERSION, '-', *DEVICE_TYPE, '-', *TAG_PYTHON_VERSION, '-', + *CUDA_VERSION, '-', *OS_VERSION ] + docker_file: !join [ docker/, *SHORT_VERSION, /, *DOCKER_PYTHON_VERSION, /, + *CUDA_VERSION, /Dockerfile., *DEVICE_TYPE ] +``` +2. In the PR comment describe what test, we ran and with which package versions. Here you can copy the table from [Current Tests](#current-tests). + +2. In the PR comment describe what test we ran and with which framework versions. Here you can copy the table from [Current Tests](#current-tests). You can take a look at this [PR](https://github.com/aws/deep-learning-containers/pull/1016), which information are needed. +## Test Case 2: Releasing a New AWS Framework DLC + + +## Execute Tests + +### Requirements: +AWS is going to release new DLCs for PyTorch and/or TensorFlow. The Tests should run on the new framework versions with current `transformers` release to validate the new framework release is compatible with the `transformers` version. To run these tests you need credentials for the HF SageMaker AWS Account. You can ask @philschmid or @n1t0 to get access. AWS will notify us with a new issue in the repository pointing to their framework upgrade PR. + +### Run Tests: + +Before we can run the tests we need to adjust the `requirements.txt` for Pytorch under `/tests/sagemaker/scripts/pytorch` and for Tensorflow under `/tests/sagemaker/scripts/pytorch`. We add the new framework version to it. + +``` +torch==1.8.1 # for pytorch +tensorflow-gpu==2.5.0 # for tensorflow +``` + +After we adjusted the `requirements.txt` we can run Amazon SageMaker tests with. + +```bash +AWS_PROFILE= make test-sagemaker +``` +These tests take around 10-15 minutes to finish. Preferably make a screenshot of the successfully ran tests. + +### After successful Tests: + +After we have successfully run tests for the new framework version we need to create a PR at the [Deep Learning Container Repository](https://github.com/aws/deep-learning-containers). + +**Creating the update PR:** + +1. Create a new `buildspec.yaml` config for [PyTorch](https://github.com/aws/deep-learning-containers/tree/master/huggingface/pytorch) and [TensorFlow](https://github.com/aws/deep-learning-containers/tree/master/huggingface/tensorflow) and rename the old `buildspec.yaml` to `buildespec-x.x.x`, where `x.x.x` is the base framework version, e.g. if pytorch 1.6.0 is the latest version in `buildspec.yaml` the file should be renamed to `buildspec-yaml-1-6.yaml`. + +To create the new `buildspec.yaml` we need to adjust the `version` and the `short_version`. Example for upgrading to `pytorch 1.7.1`. + +```yaml +account_id: &ACCOUNT_ID +region: ®ION +base_framework: &BASE_FRAMEWORK pytorch +framework: &FRAMEWORK !join [ "huggingface_", *BASE_FRAMEWORK] +version: &VERSION 1.7.1 # this was adjusted from 1.6.0 to 1.7.1 +short_version: &SHORT_VERSION 1.7 # this was adjusted from 1.6 to 1.7 + +repository_info: + training_repository: &TRAINING_REPOSITORY + image_type: &TRAINING_IMAGE_TYPE training + root: !join [ "huggingface/", *BASE_FRAMEWORK, "/", *TRAINING_IMAGE_TYPE ] + repository_name: &REPOSITORY_NAME !join ["pr", "-", "huggingface", "-", *BASE_FRAMEWORK, "-", *TRAINING_IMAGE_TYPE] + repository: &REPOSITORY !join [ *ACCOUNT_ID, .dkr.ecr., *REGION, .amazonaws.com/, + *REPOSITORY_NAME ] + +images: + BuildHuggingFacePytorchGpuPy37Cu110TrainingDockerImage: + <<: *TRAINING_REPOSITORY + build: &HUGGINGFACE_PYTORCH_GPU_TRAINING_PY3 false + image_size_baseline: &IMAGE_SIZE_BASELINE 15000 + device_type: &DEVICE_TYPE gpu + python_version: &DOCKER_PYTHON_VERSION py3 + tag_python_version: &TAG_PYTHON_VERSION py36 + cuda_version: &CUDA_VERSION cu110 + os_version: &OS_VERSION ubuntu18.04 + transformers_version: &TRANSFORMERS_VERSION 4.4.2 + datasets_version: &DATASETS_VERSION 1.5.0 + tag: !join [ *VERSION, '-', 'transformers', *TRANSFORMERS_VERSION, '-', *DEVICE_TYPE, '-', *TAG_PYTHON_VERSION, '-', + *CUDA_VERSION, '-', *OS_VERSION ] + docker_file: !join [ docker/, *SHORT_VERSION, /, *DOCKER_PYTHON_VERSION, /, + *CUDA_VERSION, /Dockerfile., *DEVICE_TYPE ] +``` +2. In the PR comment describe what test we ran and with which framework versions. Here you can copy the table from [Current Tests](#current-tests). You can take a look at this [PR](https://github.com/aws/deep-learning-containers/pull/1025), which information are needed. + +## Current Tests + +| ID | Description | Platform | #GPUS | Collected & evaluated metrics | +|-------------------------------------|-------------------------------------------------------------------|-----------------------------|-------|------------------------------------------| +| pytorch-transfromers-test-single | test bert finetuning using BERT fromtransformerlib+PT | SageMaker createTrainingJob | 1 | train_runtime, eval_accuracy & eval_loss | +| pytorch-transfromers-test-2-ddp | test bert finetuning using BERT from transformer lib+ PT DPP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss | +| pytorch-transfromers-test-2-smd | test bert finetuning using BERT from transformer lib+ PT SM DDP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss | +| pytorch-transfromers-test-1-smp | test roberta finetuning using BERT from transformer lib+ PT SM MP | SageMaker createTrainingJob | 8 | train_runtime, eval_accuracy & eval_loss | +| tensorflow-transfromers-test-single | Test bert finetuning using BERT from transformer lib+TF | SageMaker createTrainingJob | 1 | train_runtime, eval_accuracy & eval_loss | +| tensorflow-transfromers-test-2-smd | test bert finetuning using BERT from transformer lib+ TF SM DDP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss | diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ecda04614d4218221a399640932b6ecf4f9b60f2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/__init__.py @@ -0,0 +1,5 @@ +import importlib + + +def is_sagemaker_available(): + return importlib.util.find_spec("sagemaker") is not None diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/conftest.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9d987bc8d0066caf1f2ab1b56484311d0e56caf0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/conftest.py @@ -0,0 +1,64 @@ +# we define a fixture function below and it will be "used" by +# referencing its name from tests + +import os + +import pytest +from attr import dataclass + + +os.environ["AWS_DEFAULT_REGION"] = "us-east-1" # defaults region + + +@dataclass +class SageMakerTestEnvironment: + framework: str + role = "arn:aws:iam::558105141721:role/sagemaker_execution_role" + hyperparameters = { + "task_name": "mnli", + "per_device_train_batch_size": 16, + "per_device_eval_batch_size": 16, + "do_train": True, + "do_eval": True, + "do_predict": True, + "output_dir": "/opt/ml/model", + "overwrite_output_dir": True, + "max_steps": 500, + "save_steps": 5500, + } + distributed_hyperparameters = {**hyperparameters, "max_steps": 1000} + + @property + def metric_definitions(self) -> str: + if self.framework == "pytorch": + return [ + {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, + {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, + {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, + ] + else: + return [ + {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, + {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, + {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, + ] + + @property + def base_job_name(self) -> str: + return f"{self.framework}-transfromers-test" + + @property + def test_path(self) -> str: + return f"./tests/sagemaker/scripts/{self.framework}" + + @property + def image_uri(self) -> str: + if self.framework == "pytorch": + return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" + else: + return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" + + +@pytest.fixture(scope="class") +def sm_env(request): + request.cls.env = SageMakerTestEnvironment(framework=request.cls.framework) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/requirements.txt b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..2e2ed672726689713a8b62564c1f744f579907df --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/requirements.txt @@ -0,0 +1,2 @@ +git+https://github.com/huggingface/transformers.git@main # install main or adjust it with vX.X.X for installing version specific transforms +datasets==1.8.0 \ No newline at end of file diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/run_ddp.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/run_ddp.py new file mode 100644 index 0000000000000000000000000000000000000000..1191caeb96a29fab1bf11610ece865d73bf512a5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/run_ddp.py @@ -0,0 +1,52 @@ +import json +import logging +import os +import subprocess +from argparse import ArgumentParser + + +logger = logging.getLogger(__name__) + + +def parse_args(): + parser = ArgumentParser() + parsed, unknown = parser.parse_known_args() + for arg in unknown: + if arg.startswith(("-", "--")): + parser.add_argument(arg.split("=")[0]) + + return parser.parse_args() + + +def main(): + args = parse_args() + port = 8888 + num_gpus = int(os.environ["SM_NUM_GPUS"]) + hosts = json.loads(os.environ["SM_HOSTS"]) + num_nodes = len(hosts) + current_host = os.environ["SM_CURRENT_HOST"] + rank = hosts.index(current_host) + os.environ["NCCL_DEBUG"] = "INFO" + + if num_nodes > 1: + cmd = f"""python -m torch.distributed.launch \ + --nnodes={num_nodes} \ + --node_rank={rank} \ + --nproc_per_node={num_gpus} \ + --master_addr={hosts[0]} \ + --master_port={port} \ + ./run_glue.py \ + {"".join([f" --{parameter} {value}" for parameter,value in args.__dict__.items()])}""" + else: + cmd = f"""python -m torch.distributed.launch \ + --nproc_per_node={num_gpus} \ + ./run_glue.py \ + {"".join([f" --{parameter} {value}" for parameter,value in args.__dict__.items()])}""" + try: + subprocess.run(cmd, shell=True) + except Exception as e: + logger.info(e) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8b36fc9ab208e0b6838f3b036937d0ed353421 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py @@ -0,0 +1,541 @@ +#!/usr/bin/env python +# coding=utf-8 +# 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. +""" Finetuning the library models for sequence classification on GLUE.""" +# You can also adapt this script on your own text classification task. Pointers for this are left as comments. + +import logging +import os +import random +import sys +from dataclasses import dataclass, field +from typing import Optional + +import numpy as np +from datasets import load_dataset, load_metric + +import transformers +from transformers import ( # Trainer,; TrainingArguments, + AutoConfig, + AutoModelForSequenceClassification, + AutoTokenizer, + DataCollatorWithPadding, + EvalPrediction, + HfArgumentParser, + PretrainedConfig, + default_data_collator, + set_seed, +) + +# Will import SageMaker Model parallelism specific Trainer +from transformers.sagemaker import SageMakerTrainer as Trainer +from transformers.sagemaker import SageMakerTrainingArguments as TrainingArguments +from transformers.trainer_utils import get_last_checkpoint +from transformers.utils import check_min_version + + +# Will error if the minimal version of Transformers is not installed. Remove at your own risks. +check_min_version("4.4.2") + +task_to_keys = { + "cola": ("sentence", None), + "mnli": ("premise", "hypothesis"), + "mrpc": ("sentence1", "sentence2"), + "qnli": ("question", "sentence"), + "qqp": ("question1", "question2"), + "rte": ("sentence1", "sentence2"), + "sst2": ("sentence", None), + "stsb": ("sentence1", "sentence2"), + "wnli": ("sentence1", "sentence2"), +} + +logger = logging.getLogger(__name__) + + +@dataclass +class DataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + + Using `HfArgumentParser` we can turn this class + into argparse arguments to be able to specify them on + the command line. + """ + + task_name: Optional[str] = field( + default=None, + metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())}, + ) + max_seq_length: int = field( + default=128, + metadata={ + "help": ( + "The maximum total input sequence length after tokenization. Sequences longer " + "than this will be truncated, sequences shorter will be padded." + ) + }, + ) + overwrite_cache: bool = field( + default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."} + ) + pad_to_max_length: bool = field( + default=True, + metadata={ + "help": ( + "Whether to pad all samples to `max_seq_length`. " + "If False, will pad the samples dynamically when batching to the maximum length in the batch." + ) + }, + ) + max_train_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of training examples to this " + "value if set." + ) + }, + ) + max_val_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of validation examples to this " + "value if set." + ) + }, + ) + max_test_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of test examples to this " + "value if set." + ) + }, + ) + train_file: Optional[str] = field( + default=None, metadata={"help": "A csv or a json file containing the training data."} + ) + validation_file: Optional[str] = field( + default=None, metadata={"help": "A csv or a json file containing the validation data."} + ) + test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."}) + + def __post_init__(self): + if self.task_name is not None: + self.task_name = self.task_name.lower() + if self.task_name not in task_to_keys.keys(): + raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys())) + elif self.train_file is None or self.validation_file is None: + raise ValueError("Need either a GLUE task or a training/validation file.") + else: + train_extension = self.train_file.split(".")[-1] + assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." + validation_extension = self.validation_file.split(".")[-1] + assert ( + validation_extension == train_extension + ), "`validation_file` should have the same extension (csv or json) as `train_file`." + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. + """ + + model_name_or_path: str = field( + metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} + ) + config_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + tokenizer_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} + ) + cache_dir: Optional[str] = field( + default=None, + metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, + ) + use_fast_tokenizer: bool = field( + default=True, + metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, + ) + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + ) + use_auth_token: bool = field( + default=False, + metadata={ + "help": ( + "Will use the token generated when running `huggingface-cli login` (necessary to use this script " + "with private models)." + ) + }, + ) + + +def main(): + # See all possible arguments in src/transformers/training_args.py + # or by passing the --help flag to this script. + # We now keep distinct sets of args, for a cleaner separation of concerns. + + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + # Detecting last checkpoint. + last_checkpoint = None + if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(training_args.output_dir) + if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: + raise ValueError( + f"Output directory ({training_args.output_dir}) already exists and is not empty. " + "Use --overwrite_output_dir to overcome." + ) + elif last_checkpoint is not None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + logger.setLevel(logging.INFO if training_args.should_log else logging.WARN) + + # Log on each process the small summary: + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" + ) + # Set the verbosity to info of the Transformers logger (on main process only): + if training_args.should_log: + transformers.utils.logging.set_verbosity_info() + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + logger.info(f"Training/evaluation parameters {training_args}") + + # Set seed before initializing model. + set_seed(training_args.seed) + + # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) + # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). + # + # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the + # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named + # label if at least two columns are provided. + # + # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this + # single column. You can easily tweak this behavior (see below) + # + # In distributed training, the load_dataset function guarantee that only one local process can concurrently + # download the dataset. + if data_args.task_name is not None: + # Downloading and loading a dataset from the hub. + datasets = load_dataset("glue", data_args.task_name) + else: + # Loading a dataset from your local files. + # CSV/JSON training and evaluation files are needed. + data_files = {"train": data_args.train_file, "validation": data_args.validation_file} + + # Get the test dataset: you can provide your own CSV/JSON test file (see below) + # when you use `do_predict` without specifying a GLUE benchmark task. + if training_args.do_predict: + if data_args.test_file is not None: + train_extension = data_args.train_file.split(".")[-1] + test_extension = data_args.test_file.split(".")[-1] + assert ( + test_extension == train_extension + ), "`test_file` should have the same extension (csv or json) as `train_file`." + data_files["test"] = data_args.test_file + else: + raise ValueError("Need either a GLUE task or a test file for `do_predict`.") + + for key in data_files.keys(): + logger.info(f"load a local file for {key}: {data_files[key]}") + + if data_args.train_file.endswith(".csv"): + # Loading a dataset from local csv files + datasets = load_dataset("csv", data_files=data_files) + else: + # Loading a dataset from local json files + datasets = load_dataset("json", data_files=data_files) + # See more about loading any type of standard or custom dataset at + # https://huggingface.co/docs/datasets/loading_datasets. + + # Labels + if data_args.task_name is not None: + is_regression = data_args.task_name == "stsb" + if not is_regression: + label_list = datasets["train"].features["label"].names + num_labels = len(label_list) + else: + num_labels = 1 + else: + # Trying to have good defaults here, don't hesitate to tweak to your needs. + is_regression = datasets["train"].features["label"].dtype in ["float32", "float64"] + if is_regression: + num_labels = 1 + else: + # A useful fast method: + # https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.unique + label_list = datasets["train"].unique("label") + label_list.sort() # Let's sort it for determinism + num_labels = len(label_list) + + # Load pretrained model and tokenizer + # + # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently + # download model & vocab. + config = AutoConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + token=True if model_args.use_auth_token else None, + ) + tokenizer = AutoTokenizer.from_pretrained( + model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, + cache_dir=model_args.cache_dir, + use_fast=model_args.use_fast_tokenizer, + revision=model_args.model_revision, + token=True if model_args.use_auth_token else None, + ) + model = AutoModelForSequenceClassification.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + token=True if model_args.use_auth_token else None, + ) + + # Preprocessing the datasets + if data_args.task_name is not None: + sentence1_key, sentence2_key = task_to_keys[data_args.task_name] + else: + # Again, we try to have some nice defaults but don't hesitate to tweak to your use case. + non_label_column_names = [name for name in datasets["train"].column_names if name != "label"] + if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names: + sentence1_key, sentence2_key = "sentence1", "sentence2" + else: + if len(non_label_column_names) >= 2: + sentence1_key, sentence2_key = non_label_column_names[:2] + else: + sentence1_key, sentence2_key = non_label_column_names[0], None + + # Padding strategy + if data_args.pad_to_max_length: + padding = "max_length" + else: + # We will pad later, dynamically at batch creation, to the max sequence length in each batch + padding = False + + # Some models have set the order of the labels to use, so let's make sure we do use it. + label_to_id = None + if ( + model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id + and data_args.task_name is not None + and not is_regression + ): + # Some have all caps in their config, some don't. + label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()} + if sorted(label_name_to_id.keys()) == sorted(label_list): + label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)} + else: + logger.warning( + "Your model seems to have been trained with labels, but they don't match the dataset: ", + f"model labels: {sorted(label_name_to_id.keys())}, dataset labels: {sorted(label_list)}." + "\nIgnoring the model labels as a result.", + ) + elif data_args.task_name is None and not is_regression: + label_to_id = {v: i for i, v in enumerate(label_list)} + + if data_args.max_seq_length > tokenizer.model_max_length: + logger.warning( + f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the " + f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." + ) + max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) + + def preprocess_function(examples): + # Tokenize the texts + args = ( + (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key]) + ) + result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True) + + # Map labels to IDs (not necessary for GLUE tasks) + if label_to_id is not None and "label" in examples: + result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]] + return result + + datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache) + if training_args.do_train: + if "train" not in datasets: + raise ValueError("--do_train requires a train dataset") + train_dataset = datasets["train"] + if data_args.max_train_samples is not None: + train_dataset = train_dataset.select(range(data_args.max_train_samples)) + + if training_args.do_eval: + if "validation" not in datasets and "validation_matched" not in datasets: + raise ValueError("--do_eval requires a validation dataset") + eval_dataset = datasets["validation_matched" if data_args.task_name == "mnli" else "validation"] + if data_args.max_val_samples is not None: + eval_dataset = eval_dataset.select(range(data_args.max_val_samples)) + + if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None: + if "test" not in datasets and "test_matched" not in datasets: + raise ValueError("--do_predict requires a test dataset") + test_dataset = datasets["test_matched" if data_args.task_name == "mnli" else "test"] + if data_args.max_test_samples is not None: + test_dataset = test_dataset.select(range(data_args.max_test_samples)) + + # Log a few random samples from the training set: + if training_args.do_train: + for index in random.sample(range(len(train_dataset)), 3): + logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") + + # Get the metric function + if data_args.task_name is not None: + metric = load_metric("glue", data_args.task_name) + # TODO: When datasets metrics include regular accuracy, make an else here and remove special branch from + # compute_metrics + + # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a + # predictions and label_ids field) and has to return a dictionary string to float. + def compute_metrics(p: EvalPrediction): + preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions + preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1) + if data_args.task_name is not None: + result = metric.compute(predictions=preds, references=p.label_ids) + if len(result) > 1: + result["combined_score"] = np.mean(list(result.values())).item() + return result + elif is_regression: + return {"mse": ((preds - p.label_ids) ** 2).mean().item()} + else: + return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()} + + # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. + if data_args.pad_to_max_length: + data_collator = default_data_collator + elif training_args.fp16: + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) + else: + data_collator = None + + # Initialize our Trainer + trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset if training_args.do_train else None, + eval_dataset=eval_dataset if training_args.do_eval else None, + compute_metrics=compute_metrics, + tokenizer=tokenizer, + data_collator=data_collator, + ) + + # Training + if training_args.do_train: + checkpoint = None + if last_checkpoint is not None: + checkpoint = last_checkpoint + elif os.path.isdir(model_args.model_name_or_path): + # Check the config from that potential checkpoint has the right number of labels before using it as a + # checkpoint. + if AutoConfig.from_pretrained(model_args.model_name_or_path).num_labels == num_labels: + checkpoint = model_args.model_name_or_path + + train_result = trainer.train(resume_from_checkpoint=checkpoint) + metrics = train_result.metrics + max_train_samples = ( + data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) + ) + metrics["train_samples"] = min(max_train_samples, len(train_dataset)) + + trainer.save_model() # Saves the tokenizer too for easy upload + + trainer.log_metrics("train", metrics) + trainer.save_metrics("train", metrics) + trainer.save_state() + + # Evaluation + if training_args.do_eval: + logger.info("*** Evaluate ***") + + # Loop to handle MNLI double evaluation (matched, mis-matched) + tasks = [data_args.task_name] + eval_datasets = [eval_dataset] + if data_args.task_name == "mnli": + tasks.append("mnli-mm") + eval_datasets.append(datasets["validation_mismatched"]) + + for eval_dataset, task in zip(eval_datasets, tasks): + metrics = trainer.evaluate(eval_dataset=eval_dataset) + + max_val_samples = data_args.max_val_samples if data_args.max_val_samples is not None else len(eval_dataset) + metrics["eval_samples"] = min(max_val_samples, len(eval_dataset)) + + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + if training_args.do_predict: + logger.info("*** Test ***") + + # Loop to handle MNLI double evaluation (matched, mis-matched) + tasks = [data_args.task_name] + test_datasets = [test_dataset] + if data_args.task_name == "mnli": + tasks.append("mnli-mm") + test_datasets.append(datasets["test_mismatched"]) + + for test_dataset, task in zip(test_datasets, tasks): + # Removing the `label` columns because it contains -1 and Trainer won't like that. + test_dataset = test_dataset.remove_columns("label") + predictions = trainer.predict(test_dataset=test_dataset).predictions + predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1) + + output_test_file = os.path.join(training_args.output_dir, f"test_results_{task}.txt") + if trainer.is_world_process_zero(): + with open(output_test_file, "w") as writer: + logger.info(f"***** Test results {task} *****") + writer.write("index\tprediction\n") + for index, item in enumerate(predictions): + if is_regression: + writer.write(f"{index}\t{item:3.3f}\n") + else: + item = label_list[item] + writer.write(f"{index}\t{item}\n") + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/requirements.txt b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..34a3d05b460e2dcac55c9cf3d186afed24c7f9fb --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/requirements.txt @@ -0,0 +1 @@ +git+https://github.com/huggingface/transformers.git@main # install main or adjust ist with vX.X.X for installing version specific transforms \ No newline at end of file diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/run_tf.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/run_tf.py new file mode 100644 index 0000000000000000000000000000000000000000..03f631d2667995680f1fe0ef1d0fdf3531772378 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/run_tf.py @@ -0,0 +1,90 @@ +import argparse +import logging +import sys +import time + +import tensorflow as tf +from datasets import load_dataset + +from transformers import AutoTokenizer, TFAutoModelForSequenceClassification + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + # Hyperparameters sent by the client are passed as command-line arguments to the script. + parser.add_argument("--epochs", type=int, default=1) + parser.add_argument("--per_device_train_batch_size", type=int, default=16) + parser.add_argument("--per_device_eval_batch_size", type=int, default=8) + parser.add_argument("--model_name_or_path", type=str) + parser.add_argument("--learning_rate", type=str, default=5e-5) + parser.add_argument("--do_train", type=bool, default=True) + parser.add_argument("--do_eval", type=bool, default=True) + parser.add_argument("--output_dir", type=str) + + args, _ = parser.parse_known_args() + + # overwrite batch size until we have tf_glue.py + args.per_device_train_batch_size = 16 + args.per_device_eval_batch_size = 16 + + # Set up logging + logger = logging.getLogger(__name__) + + logging.basicConfig( + level=logging.getLevelName("INFO"), + handlers=[logging.StreamHandler(sys.stdout)], + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + ) + + # Load model and tokenizer + model = TFAutoModelForSequenceClassification.from_pretrained(args.model_name_or_path) + tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) + + # Load dataset + train_dataset, test_dataset = load_dataset("imdb", split=["train", "test"]) + train_dataset = train_dataset.shuffle().select(range(5000)) # smaller the size for train dataset to 5k + test_dataset = test_dataset.shuffle().select(range(500)) # smaller the size for test dataset to 500 + + # Preprocess train dataset + train_dataset = train_dataset.map( + lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True + ) + train_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"]) + + train_features = { + x: train_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) + for x in ["input_ids", "attention_mask"] + } + tf_train_dataset = tf.data.Dataset.from_tensor_slices((train_features, train_dataset["label"])).batch( + args.per_device_train_batch_size + ) + + # Preprocess test dataset + test_dataset = test_dataset.map( + lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True + ) + test_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"]) + + test_features = { + x: test_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) + for x in ["input_ids", "attention_mask"] + } + tf_test_dataset = tf.data.Dataset.from_tensor_slices((test_features, test_dataset["label"])).batch( + args.per_device_eval_batch_size + ) + + # fine optimizer and loss + optimizer = tf.keras.optimizers.Adam(learning_rate=args.learning_rate) + loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) + metrics = [tf.keras.metrics.SparseCategoricalAccuracy()] + model.compile(optimizer=optimizer, loss=loss, metrics=metrics) + + start_train_time = time.time() + train_results = model.fit(tf_train_dataset, epochs=args.epochs, batch_size=args.per_device_train_batch_size) + end_train_time = time.time() - start_train_time + + logger.info("*** Train ***") + logger.info(f"train_runtime = {end_train_time}") + for key, value in train_results.history.items(): + logger.info(f" {key} = {value}") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/run_tf_dist.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/run_tf_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f2e4bcf29d491f23277e70090523ca3baff132 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/scripts/tensorflow/run_tf_dist.py @@ -0,0 +1,191 @@ +import argparse +import logging +import os +import sys +import time + +import tensorflow as tf +from datasets import load_dataset +from tqdm import tqdm + +from transformers import AutoTokenizer, TFAutoModelForSequenceClassification +from transformers.utils import is_sagemaker_dp_enabled + + +if os.environ.get("SDP_ENABLED") or is_sagemaker_dp_enabled(): + SDP_ENABLED = True + os.environ["SAGEMAKER_INSTANCE_TYPE"] = "p3dn.24xlarge" + import smdistributed.dataparallel.tensorflow as sdp +else: + SDP_ENABLED = False + + +def fit(model, loss, opt, train_dataset, epochs, train_batch_size, max_steps=None): + pbar = tqdm(train_dataset) + for i, batch in enumerate(pbar): + with tf.GradientTape() as tape: + inputs, targets = batch + outputs = model(batch) + loss_value = loss(targets, outputs.logits) + + if SDP_ENABLED: + tape = sdp.DistributedGradientTape(tape, sparse_as_dense=True) + + grads = tape.gradient(loss_value, model.trainable_variables) + opt.apply_gradients(zip(grads, model.trainable_variables)) + + pbar.set_description(f"Loss: {loss_value:.4f}") + + if SDP_ENABLED and i == 0: + sdp.broadcast_variables(model.variables, root_rank=0) + sdp.broadcast_variables(opt.variables(), root_rank=0) + + if max_steps and i >= max_steps: + break + + train_results = {"loss": loss_value.numpy()} + return train_results + + +def get_datasets(tokenizer, train_batch_size, eval_batch_size): + # Load dataset + train_dataset, test_dataset = load_dataset("imdb", split=["train", "test"]) + + # Preprocess train dataset + train_dataset = train_dataset.map( + lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True + ) + train_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"]) + + train_features = { + x: train_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) + for x in ["input_ids", "attention_mask"] + } + tf_train_dataset = tf.data.Dataset.from_tensor_slices((train_features, train_dataset["label"])) + + # Preprocess test dataset + test_dataset = test_dataset.map( + lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True + ) + test_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"]) + + test_features = { + x: test_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) + for x in ["input_ids", "attention_mask"] + } + tf_test_dataset = tf.data.Dataset.from_tensor_slices((test_features, test_dataset["label"])) + + if SDP_ENABLED: + tf_train_dataset = tf_train_dataset.shard(sdp.size(), sdp.rank()) + tf_test_dataset = tf_test_dataset.shard(sdp.size(), sdp.rank()) + tf_train_dataset = tf_train_dataset.batch(train_batch_size, drop_remainder=True) + tf_test_dataset = tf_test_dataset.batch(eval_batch_size, drop_remainder=True) + + return tf_train_dataset, tf_test_dataset + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + # Hyperparameters sent by the client are passed as command-line arguments to the script. + parser.add_argument("--epochs", type=int, default=3) + parser.add_argument("--per_device_train_batch_size", type=int, default=16) + parser.add_argument("--per_device_eval_batch_size", type=int, default=8) + parser.add_argument("--model_name_or_path", type=str) + parser.add_argument("--learning_rate", type=str, default=5e-5) + parser.add_argument("--do_train", type=bool, default=True) + parser.add_argument("--do_eval", type=bool, default=True) + parser.add_argument("--output_dir", type=str) + parser.add_argument("--max_steps", type=int, default=None) + + # Data, model, and output directories + parser.add_argument("--output_data_dir", type=str, default=os.environ["SM_OUTPUT_DATA_DIR"]) + parser.add_argument("--model_dir", type=str, default=os.environ["SM_MODEL_DIR"]) + parser.add_argument("--n_gpus", type=str, default=os.environ["SM_NUM_GPUS"]) + + args, _ = parser.parse_known_args() + + # Set up logging + logger = logging.getLogger(__name__) + + logging.basicConfig( + level=logging.getLevelName("INFO"), + handlers=[logging.StreamHandler(sys.stdout)], + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + ) + + if SDP_ENABLED: + sdp.init() + + gpus = tf.config.experimental.list_physical_devices("GPU") + for gpu in gpus: + tf.config.experimental.set_memory_growth(gpu, True) + if gpus: + tf.config.experimental.set_visible_devices(gpus[sdp.local_rank()], "GPU") + + # Load model and tokenizer + model = TFAutoModelForSequenceClassification.from_pretrained(args.model_name_or_path) + tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) + + # get datasets + tf_train_dataset, tf_test_dataset = get_datasets( + tokenizer=tokenizer, + train_batch_size=args.per_device_train_batch_size, + eval_batch_size=args.per_device_eval_batch_size, + ) + + # fine optimizer and loss + optimizer = tf.keras.optimizers.Adam(learning_rate=args.learning_rate) + loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) + metrics = [tf.keras.metrics.SparseCategoricalAccuracy()] + model.compile(optimizer=optimizer, loss=loss, metrics=metrics) + + # Training + if args.do_train: + # train_results = model.fit(tf_train_dataset, epochs=args.epochs, batch_size=args.train_batch_size) + start_train_time = time.time() + train_results = fit( + model, + loss, + optimizer, + tf_train_dataset, + args.epochs, + args.per_device_train_batch_size, + max_steps=args.max_steps, + ) + end_train_time = time.time() - start_train_time + logger.info("*** Train ***") + logger.info(f"train_runtime = {end_train_time}") + + output_eval_file = os.path.join(args.output_dir, "train_results.txt") + + if not SDP_ENABLED or sdp.rank() == 0: + with open(output_eval_file, "w") as writer: + logger.info("***** Train results *****") + logger.info(train_results) + for key, value in train_results.items(): + logger.info(f" {key} = {value}") + writer.write(f"{key} = {value}\n") + + # Evaluation + if args.do_eval and (not SDP_ENABLED or sdp.rank() == 0): + result = model.evaluate(tf_test_dataset, batch_size=args.per_device_eval_batch_size, return_dict=True) + logger.info("*** Evaluate ***") + + output_eval_file = os.path.join(args.output_dir, "eval_results.txt") + + with open(output_eval_file, "w") as writer: + logger.info("***** Eval results *****") + logger.info(result) + for key, value in result.items(): + logger.info(f" {key} = {value}") + writer.write(f"{key} = {value}\n") + + # Save result + if SDP_ENABLED: + if sdp.rank() == 0: + model.save_pretrained(args.output_dir) + tokenizer.save_pretrained(args.output_dir) + else: + model.save_pretrained(args.output_dir) + tokenizer.save_pretrained(args.output_dir) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_multi_node_data_parallel.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_multi_node_data_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..cc7f9e5e84f8bf02d36e50f028eb7506cbe2f6c1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_multi_node_data_parallel.py @@ -0,0 +1,109 @@ +import json +import os +import subprocess +import unittest +from ast import literal_eval + +import pytest +from parameterized import parameterized, parameterized_class + +from . import is_sagemaker_available + + +if is_sagemaker_available(): + from sagemaker import Session, TrainingJobAnalytics + from sagemaker.huggingface import HuggingFace + + +@pytest.mark.skipif( + literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True, + reason="Skipping test because should only be run when releasing minor transformers version", +) +@pytest.mark.usefixtures("sm_env") +@parameterized_class( + [ + { + "framework": "pytorch", + "script": "run_glue.py", + "model_name_or_path": "distilbert-base-cased", + "instance_type": "ml.p3.16xlarge", + "results": {"train_runtime": 650, "eval_accuracy": 0.7, "eval_loss": 0.6}, + }, + { + "framework": "pytorch", + "script": "run_ddp.py", + "model_name_or_path": "distilbert-base-cased", + "instance_type": "ml.p3.16xlarge", + "results": {"train_runtime": 600, "eval_accuracy": 0.7, "eval_loss": 0.6}, + }, + { + "framework": "tensorflow", + "script": "run_tf_dist.py", + "model_name_or_path": "distilbert-base-cased", + "instance_type": "ml.p3.16xlarge", + "results": {"train_runtime": 600, "eval_accuracy": 0.6, "eval_loss": 0.7}, + }, + ] +) +class MultiNodeTest(unittest.TestCase): + def setUp(self): + if self.framework == "pytorch": + subprocess.run( + f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(), + encoding="utf-8", + check=True, + ) + assert hasattr(self, "env") + + def create_estimator(self, instance_count): + job_name = f"{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}" + # distributed data settings + distribution = {"smdistributed": {"dataparallel": {"enabled": True}}} if self.script != "run_ddp.py" else None + + # creates estimator + return HuggingFace( + entry_point=self.script, + source_dir=self.env.test_path, + role=self.env.role, + image_uri=self.env.image_uri, + base_job_name=job_name, + instance_count=instance_count, + instance_type=self.instance_type, + debugger_hook_config=False, + hyperparameters={**self.env.distributed_hyperparameters, "model_name_or_path": self.model_name_or_path}, + metric_definitions=self.env.metric_definitions, + distribution=distribution, + py_version="py36", + ) + + def save_results_as_csv(self, job_name): + TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv") + + # @parameterized.expand([(2,), (4,),]) + @parameterized.expand([(2,)]) + def test_script(self, instance_count): + # create estimator + estimator = self.create_estimator(instance_count) + + # run training + estimator.fit() + + # result dataframe + result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() + + # extract kpis + eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]) + eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]) + # get train time from SageMaker job, this includes starting, preprocessing, stopping + train_runtime = ( + Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999) + ) + + # assert kpis + assert train_runtime <= self.results["train_runtime"] + assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy) + assert all(t <= self.results["eval_loss"] for t in eval_loss) + + # dump tests result into json file to share in PR + with open(f"{estimator.latest_training_job.name}.json", "w") as outfile: + json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_multi_node_model_parallel.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_multi_node_model_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..95d5b9fa8559044acd9ebf6de787f83d787d0228 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_multi_node_model_parallel.py @@ -0,0 +1,122 @@ +import json +import os +import subprocess +import unittest +from ast import literal_eval + +import pytest +from parameterized import parameterized, parameterized_class + +from . import is_sagemaker_available + + +if is_sagemaker_available(): + from sagemaker import Session, TrainingJobAnalytics + from sagemaker.huggingface import HuggingFace + + +@pytest.mark.skipif( + literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True, + reason="Skipping test because should only be run when releasing minor transformers version", +) +@pytest.mark.usefixtures("sm_env") +@parameterized_class( + [ + { + "framework": "pytorch", + "script": "run_glue_model_parallelism.py", + "model_name_or_path": "roberta-large", + "instance_type": "ml.p3dn.24xlarge", + "results": {"train_runtime": 1600, "eval_accuracy": 0.3, "eval_loss": 1.2}, + }, + { + "framework": "pytorch", + "script": "run_glue.py", + "model_name_or_path": "roberta-large", + "instance_type": "ml.p3dn.24xlarge", + "results": {"train_runtime": 1600, "eval_accuracy": 0.3, "eval_loss": 1.2}, + }, + ] +) +class MultiNodeTest(unittest.TestCase): + def setUp(self): + if self.framework == "pytorch": + subprocess.run( + f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(), + encoding="utf-8", + check=True, + ) + assert hasattr(self, "env") + + def create_estimator(self, instance_count): + # configuration for running training on smdistributed Model Parallel + mpi_options = { + "enabled": True, + "processes_per_host": 8, + } + smp_options = { + "enabled": True, + "parameters": { + "microbatches": 4, + "placement_strategy": "spread", + "pipeline": "interleaved", + "optimize": "speed", + "partitions": 4, + "ddp": True, + }, + } + + distribution = {"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options} + + name_extension = "trainer" if self.script == "run_glue.py" else "smtrainer" + # creates estimator + return HuggingFace( + entry_point=self.script, + source_dir=self.env.test_path, + role=self.env.role, + image_uri=self.env.image_uri, + base_job_name=f"{self.env.base_job_name}-{instance_count}-smp-{name_extension}", + instance_count=instance_count, + instance_type=self.instance_type, + debugger_hook_config=False, + hyperparameters={ + **self.env.hyperparameters, + "model_name_or_path": self.model_name_or_path, + "max_steps": 500, + }, + metric_definitions=self.env.metric_definitions, + distribution=distribution, + py_version="py36", + ) + + def save_results_as_csv(self, job_name): + TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv") + + # @parameterized.expand([(2,), (4,),]) + @parameterized.expand([(1,)]) + def test_scripz(self, instance_count): + # create estimator + estimator = self.create_estimator(instance_count) + + # run training + estimator.fit() + + # result dataframe + result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() + + # extract kpis + eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]) + eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]) + # get train time from SageMaker job, this includes starting, preprocessing, stopping + train_runtime = ( + Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999) + ) + + # assert kpis + assert train_runtime <= self.results["train_runtime"] + assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy) + assert all(t <= self.results["eval_loss"] for t in eval_loss) + + # dump tests result into json file to share in PR + with open(f"{estimator.latest_training_job.name}.json", "w") as outfile: + json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_single_node_gpu.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_single_node_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a62547e787c604c7d0ee419b3a9e9dcb0dba21 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/sagemaker/test_single_node_gpu.py @@ -0,0 +1,95 @@ +import json +import os +import subprocess +import unittest +from ast import literal_eval + +import pytest +from parameterized import parameterized_class + +from . import is_sagemaker_available + + +if is_sagemaker_available(): + from sagemaker import Session, TrainingJobAnalytics + from sagemaker.huggingface import HuggingFace + + +@pytest.mark.skipif( + literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True, + reason="Skipping test because should only be run when releasing minor transformers version", +) +@pytest.mark.usefixtures("sm_env") +@parameterized_class( + [ + { + "framework": "pytorch", + "script": "run_glue.py", + "model_name_or_path": "distilbert-base-cased", + "instance_type": "ml.g4dn.xlarge", + "results": {"train_runtime": 650, "eval_accuracy": 0.6, "eval_loss": 0.9}, + }, + { + "framework": "tensorflow", + "script": "run_tf.py", + "model_name_or_path": "distilbert-base-cased", + "instance_type": "ml.g4dn.xlarge", + "results": {"train_runtime": 600, "eval_accuracy": 0.3, "eval_loss": 0.9}, + }, + ] +) +class SingleNodeTest(unittest.TestCase): + def setUp(self): + if self.framework == "pytorch": + subprocess.run( + f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(), + encoding="utf-8", + check=True, + ) + assert hasattr(self, "env") + + def create_estimator(self, instance_count=1): + # creates estimator + return HuggingFace( + entry_point=self.script, + source_dir=self.env.test_path, + role=self.env.role, + image_uri=self.env.image_uri, + base_job_name=f"{self.env.base_job_name}-single", + instance_count=instance_count, + instance_type=self.instance_type, + debugger_hook_config=False, + hyperparameters={**self.env.hyperparameters, "model_name_or_path": self.model_name_or_path}, + metric_definitions=self.env.metric_definitions, + py_version="py36", + ) + + def save_results_as_csv(self, job_name): + TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv") + + def test_glue(self): + # create estimator + estimator = self.create_estimator() + + # run training + estimator.fit() + + # result dataframe + result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() + + # extract kpis + eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]) + eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]) + # get train time from SageMaker job, this includes starting, preprocessing, stopping + train_runtime = ( + Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999) + ) + + # assert kpis + assert train_runtime <= self.results["train_runtime"] + assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy) + assert all(t <= self.results["eval_loss"] for t in eval_loss) + + # dump tests result into json file to share in PR + with open(f"{estimator.latest_training_job.name}.json", "w") as outfile: + json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_backbone_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_backbone_common.py new file mode 100644 index 0000000000000000000000000000000000000000..7735107d4f361212375839af43185a3571164444 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_backbone_common.py @@ -0,0 +1,203 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import inspect +import tempfile + +from transformers.testing_utils import require_torch, torch_device +from transformers.utils.backbone_utils import BackboneType + + +@require_torch +class BackboneTesterMixin: + all_model_classes = () + has_attentions = True + + def test_config(self): + config_class = self.config_class + + # test default config + config = config_class() + self.assertIsNotNone(config) + num_stages = len(config.depths) if hasattr(config, "depths") else config.num_hidden_layers + expected_stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, num_stages + 1)] + self.assertEqual(config.stage_names, expected_stage_names) + self.assertTrue(set(config.out_features).issubset(set(config.stage_names))) + + # Test out_features and out_indices are correctly set + # out_features and out_indices both None + config = config_class(out_features=None, out_indices=None) + self.assertEqual(config.out_features, [config.stage_names[-1]]) + self.assertEqual(config.out_indices, [len(config.stage_names) - 1]) + + # out_features and out_indices both set + config = config_class(out_features=["stem", "stage1"], out_indices=[0, 1]) + self.assertEqual(config.out_features, ["stem", "stage1"]) + self.assertEqual(config.out_indices, [0, 1]) + + # Only out_features set + config = config_class(out_features=["stage1", "stage3"]) + self.assertEqual(config.out_features, ["stage1", "stage3"]) + self.assertEqual(config.out_indices, [1, 3]) + + # Only out_indices set + config = config_class(out_indices=[0, 2]) + self.assertEqual(config.out_features, [config.stage_names[0], config.stage_names[2]]) + self.assertEqual(config.out_indices, [0, 2]) + + # Error raised when out_indices do not correspond to out_features + with self.assertRaises(ValueError): + config = config_class(out_features=["stage1", "stage2"], out_indices=[0, 2]) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_config_save_pretrained(self): + config_class = self.config_class + config_first = config_class(out_indices=[0, 1, 2, 3]) + + with tempfile.TemporaryDirectory() as tmpdirname: + config_first.save_pretrained(tmpdirname) + config_second = self.config_class.from_pretrained(tmpdirname) + + self.assertEqual(config_second.to_dict(), config_first.to_dict()) + + def test_channels(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertEqual(len(model.channels), len(config.out_features)) + num_features = model.num_features + out_indices = [config.stage_names.index(feat) for feat in config.out_features] + out_channels = [num_features[idx] for idx in out_indices] + self.assertListEqual(model.channels, out_channels) + + new_config = copy.deepcopy(config) + new_config.out_features = None + model = model_class(new_config) + self.assertEqual(len(model.channels), 1) + self.assertListEqual(model.channels, [num_features[-1]]) + + new_config = copy.deepcopy(config) + new_config.out_indices = None + model = model_class(new_config) + self.assertEqual(len(model.channels), 1) + self.assertListEqual(model.channels, [num_features[-1]]) + + def test_create_from_modified_config(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + self.assertEqual(len(result.feature_maps), len(config.out_features)) + self.assertEqual(len(model.channels), len(config.out_features)) + self.assertEqual(len(result.feature_maps), len(config.out_indices)) + self.assertEqual(len(model.channels), len(config.out_indices)) + + # Check output of last stage is taken if out_features=None, out_indices=None + modified_config = copy.deepcopy(config) + modified_config.out_features = None + model = model_class(modified_config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + self.assertEqual(len(result.feature_maps), 1) + self.assertEqual(len(model.channels), 1) + + modified_config = copy.deepcopy(config) + modified_config.out_indices = None + model = model_class(modified_config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + self.assertEqual(len(result.feature_maps), 1) + self.assertEqual(len(model.channels), 1) + + # Check backbone can be initialized with fresh weights + modified_config = copy.deepcopy(config) + modified_config.use_pretrained_backbone = False + model = model_class(modified_config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + def test_backbone_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for backbone_class in self.all_model_classes: + backbone = backbone_class(config) + + self.assertTrue(hasattr(backbone, "backbone_type")) + self.assertTrue(hasattr(backbone, "stage_names")) + self.assertTrue(hasattr(backbone, "num_features")) + self.assertTrue(hasattr(backbone, "out_indices")) + self.assertTrue(hasattr(backbone, "out_features")) + self.assertTrue(hasattr(backbone, "out_feature_channels")) + self.assertTrue(hasattr(backbone, "channels")) + + self.assertIsInstance(backbone.backbone_type, BackboneType) + # Verify num_features has been initialized in the backbone init + self.assertIsNotNone(backbone.num_features) + self.assertTrue(len(backbone.channels) == len(backbone.out_indices)) + self.assertTrue(len(backbone.stage_names) == len(backbone.num_features)) + self.assertTrue(len(backbone.channels) <= len(backbone.num_features)) + self.assertTrue(len(backbone.out_feature_channels) == len(backbone.stage_names)) + + def test_backbone_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + batch_size = inputs_dict["pixel_values"].shape[0] + + for backbone_class in self.all_model_classes: + backbone = backbone_class(config) + backbone.to(torch_device) + backbone.eval() + + outputs = backbone(**inputs_dict) + + # Test default outputs and verify feature maps + self.assertIsInstance(outputs.feature_maps, tuple) + self.assertTrue(len(outputs.feature_maps) == len(backbone.channels)) + for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels): + self.assertTrue(feature_map.shape[:2], (batch_size, n_channels)) + self.assertIsNone(outputs.hidden_states) + self.assertIsNone(outputs.attentions) + + # Test output_hidden_states=True + outputs = backbone(**inputs_dict, output_hidden_states=True) + self.assertIsNotNone(outputs.hidden_states) + self.assertTrue(len(outputs.hidden_states), len(backbone.stage_names)) + for hidden_state, n_channels in zip(outputs.hidden_states, backbone.channels): + self.assertTrue(hidden_state.shape[:2], (batch_size, n_channels)) + + # Test output_attentions=True + if self.has_attentions: + outputs = backbone(**inputs_dict, output_attentions=True) + self.assertIsNotNone(outputs.attentions) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_cache_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_cache_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..72d055c8806afd04c102f3ffb5389dcda5d5b1bb --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_cache_utils.py @@ -0,0 +1,231 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers import set_seed +from transformers.testing_utils import is_torch_available, require_auto_gptq, require_torch, require_torch_gpu, slow + + +if is_torch_available(): + import torch + + from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache, LlamaForCausalLM, SinkCache + + +@require_torch +class CacheTest(unittest.TestCase): + def test_cache_equivalence(self): + """Tests that we can convert back and forth between the legacy cache format and DynamicCache""" + legacy_cache = () + new_cache = DynamicCache() + + # Creates a new cache with 10 layers in both formats + for layer_idx in range(10): + new_key = torch.rand((2, 4, 8, 16)) + new_value = torch.rand((2, 4, 8, 16)) + new_cache.update(new_key, new_value, layer_idx) + legacy_cache += ((new_key, new_value),) + + # Sanity check 1: they must have the same shapes + self.assertTrue(len(legacy_cache), len(new_cache)) + for layer_idx in range(10): + self.assertTrue(len(legacy_cache[layer_idx]), len(legacy_cache[layer_idx])) + for key_value_idx in range(2): + self.assertTrue( + legacy_cache[layer_idx][key_value_idx].shape == new_cache[layer_idx][key_value_idx].shape + ) + + # Sanity check 2: we can get the sequence length in multiple ways with DynamicCache, and they return the + # expected value + self.assertTrue(legacy_cache[0][0].shape[-2] == new_cache[0][0].shape[-2] == new_cache.get_seq_length() == 8) + + # Sanity check 3: they must be equal, and both support indexing + for layer_idx in range(10): + for key_value_idx in range(2): + self.assertTrue( + torch.allclose(new_cache[layer_idx][key_value_idx], legacy_cache[layer_idx][key_value_idx]) + ) + + # Test 1: We can convert from legacy to new with no changes + from_legacy = DynamicCache.from_legacy_cache(legacy_cache) + for layer_idx in range(10): + for key_value_idx in range(2): + self.assertTrue( + torch.allclose(from_legacy[layer_idx][key_value_idx], legacy_cache[layer_idx][key_value_idx]) + ) + + # Test 2: We can convert from new to legacy with no changes + to_legacy = new_cache.to_legacy_cache() + for layer_idx in range(10): + for key_value_idx in range(2): + self.assertTrue( + torch.allclose(to_legacy[layer_idx][key_value_idx], new_cache[layer_idx][key_value_idx]) + ) + + def test_reorder_cache_retrocompatibility(self): + """Tests that Cache.reorder_cache is retrocompatible with the legacy code path""" + legacy_reorder_fn = LlamaForCausalLM._reorder_cache # An example of a legacy `_reorder_cache` function + + legacy_cache = () + new_cache = DynamicCache() + + # Creates a new cache with 10 layers in both formats + for layer_idx in range(10): + new_key = torch.rand((4, 4, 8, 16)) + new_value = torch.rand((4, 4, 8, 16)) + new_cache.update(new_key, new_value, layer_idx) + legacy_cache += ((new_key, new_value),) + + # Let's create some dummy beam indices. From the shape above, it is equivalent to the case where num_beams=4 + # and batch_size=1 + beam_idx = torch.randint(low=0, high=4, size=(4,)) + + legacy_cache_reordered = legacy_reorder_fn(legacy_cache, beam_idx) + new_cache.reorder_cache(beam_idx) + + # Let's check that the results are the same + for layer_idx in range(10): + for key_value_idx in range(2): + self.assertTrue( + torch.allclose( + new_cache[layer_idx][key_value_idx], legacy_cache_reordered[layer_idx][key_value_idx] + ) + ) + + +@require_torch_gpu +@slow +class CacheIntegrationTest(unittest.TestCase): + def test_dynamic_cache_hard(self): + tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", padding_side="left") + model = AutoModelForCausalLM.from_pretrained( + "meta-llama/Llama-2-7b-hf", device_map="auto", torch_dtype=torch.float16 + ) + inputs = tokenizer(["Here's everything I know about cats. Cats"], return_tensors="pt").to(model.device) + + # DynamicCache and the legacy cache format should be equivalent + set_seed(0) + gen_out_legacy = model.generate(**inputs, do_sample=True, max_new_tokens=256) + set_seed(0) + gen_out = model.generate(**inputs, do_sample=True, max_new_tokens=256, past_key_values=DynamicCache()) + self.assertListEqual(gen_out_legacy.tolist(), gen_out.tolist()) + + decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) + expected_text = ( + "Here's everything I know about cats. Cats are mysterious creatures. They can't talk, and they don't like " + "to be held. They don't play fetch, and they don't like to be hugged. But they do like to be petted.\n" + "Cats are also very independent. They don't like to be told what to do, and they don't like to be told " + "what to eat. They are also very territorial. They don't like to share their food or their toys.\nCats " + "are also very curious. They like to explore, and they like to play. They are also very fast. They can " + "run very fast, and they can jump very high.\nCats are also very smart. They can learn tricks, and they " + "can solve problems. They are also very playful. They like to play with toys, and they like to play with " + "other cats.\nCats are also very affectionate. They like to be petted, and they like to be held. They " + "also like to be scratched.\nCats are also very clean. They like to groom themselves, and they like to " + "clean their litter box.\nCats are also very independent. They don't" + ) + self.assertEqual(decoded[0], expected_text) + + def test_dynamic_cache_batched(self): + tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", padding_side="left") + tokenizer.pad_token = tokenizer.eos_token + model = AutoModelForCausalLM.from_pretrained( + "meta-llama/Llama-2-7b-hf", device_map="auto", torch_dtype=torch.float16 + ) + inputs = tokenizer(["A sequence: 1, 2, 3, 4, 5", "A sequence: A, B, C"], padding=True, return_tensors="pt").to( + model.device + ) + + gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10, past_key_values=DynamicCache()) + decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) + expected_text = ["A sequence: 1, 2, 3, 4, 5, 6, 7, 8,", "A sequence: A, B, C, D, E, F, G, H"] + self.assertListEqual(decoded, expected_text) + + def test_dynamic_cache_beam_search(self): + tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", padding_side="left") + model = AutoModelForCausalLM.from_pretrained( + "meta-llama/Llama-2-7b-hf", device_map="auto", torch_dtype=torch.float16 + ) + + inputs = tokenizer(["The best color is"], return_tensors="pt").to(model.device) + gen_out = model.generate( + **inputs, + do_sample=False, + max_new_tokens=20, + num_beams=2, + num_return_sequences=2, + ) + decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) + expected_text = [ + "The best color is the one that makes you feel good.\nThe best color is the one that makes you feel good", + "The best color is the one that suits you.\nThe best color is the one that suits you. The", + ] + self.assertListEqual(decoded, expected_text) + + @require_auto_gptq + def test_sink_cache_hard(self): + tokenizer = AutoTokenizer.from_pretrained("TheBloke/LLaMa-7B-GPTQ") + model = AutoModelForCausalLM.from_pretrained("TheBloke/LLaMa-7B-GPTQ", device_map="auto") + + inputs = tokenizer(["Vaswani et al. (2017) introduced the Transformers"], return_tensors="pt").to(model.device) + + # Set up the SinkCache. Using a small window length to contain computational complexity. If this example is run + # without a SinkCache, the last few tokens are gibberish (ends in "of the of the of a of a of") + cache = SinkCache(window_length=508, num_sink_tokens=4) + gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=3000, past_key_values=cache) + decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) + self.assertTrue(decoded[0].endswith("to perform a variety of tasks. The Transformer is a neural network")) + + def test_sink_cache_iterative_prompts(self): + """Tests that SinkCache supports more than one new token at once, when shifting the cache""" + tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") + model = AutoModelForCausalLM.from_pretrained( + "HuggingFaceH4/zephyr-7b-beta", device_map="auto", torch_dtype=torch.float16 + ) + prompt = ( + "Compose an engaging travel blog post about a recent trip to Hawaii, highlighting cultural experiences " + "and must-see attractions." + ) + + # Prepare generation settings + cache = SinkCache(window_length=256, num_sink_tokens=4) + input_ids = torch.tensor([], device=model.device, dtype=torch.int) + for _ in range(3): + # Tokenize the prompt with the correct chat template + chat = [{"role": "user", "content": prompt}] + tokenized_chat = tokenizer.apply_chat_template(chat, return_tensors="pt", add_generation_prompt=True).to( + model.device + ) + input_ids = torch.cat((input_ids, tokenized_chat), dim=1) + + # Perform the generation + gen_out = model.generate( + input_ids, do_sample=False, max_new_tokens=100, past_key_values=cache, use_cache=True + ) + input_ids = gen_out + + # We went well beyond the cache length + self.assertTrue(input_ids.shape[1] > cache.get_max_length() * 1.5) + + # And it still produces a coherent english + decoded = tokenizer.batch_decode(input_ids, skip_special_tokens=True) + last_output = ( + "<|assistant|>\nAs the sun began to set over the Pacific Ocean, I found myself standing on the shores of " + "Waikiki Beach, my heart filled with awe and wonder. I had just returned from a two-week journey to the " + "beautiful island of Hawaii, and it had been an unforgettable experience filled with cultural experiences " + "and must-see attractions that left me breathless.\n\nOne of the most memorable experiences of my trip " + "was visiting the historic district of Honolulu. Here," + ) + self.assertTrue(decoded[0].endswith(last_output)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_configuration_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_configuration_common.py new file mode 100644 index 0000000000000000000000000000000000000000..57521a3e7c530d7afc75200d569695d7d85b2ca8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_configuration_common.py @@ -0,0 +1,158 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import json +import os +import tempfile + +from transformers import is_torch_available + +from .test_configuration_utils import config_common_kwargs + + +class ConfigTester(object): + def __init__(self, parent, config_class=None, has_text_modality=True, common_properties=None, **kwargs): + self.parent = parent + self.config_class = config_class + self.has_text_modality = has_text_modality + self.inputs_dict = kwargs + self.common_properties = common_properties + + def create_and_test_config_common_properties(self): + config = self.config_class(**self.inputs_dict) + common_properties = ( + ["hidden_size", "num_attention_heads", "num_hidden_layers"] + if self.common_properties is None + else self.common_properties + ) + + # Add common fields for text models + if self.has_text_modality: + common_properties.extend(["vocab_size"]) + + # Test that config has the common properties as getters + for prop in common_properties: + self.parent.assertTrue(hasattr(config, prop), msg=f"`{prop}` does not exist") + + # Test that config has the common properties as setter + for idx, name in enumerate(common_properties): + try: + setattr(config, name, idx) + self.parent.assertEqual( + getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" + ) + except NotImplementedError: + # Some models might not be able to implement setters for common_properties + # In that case, a NotImplementedError is raised + pass + + # Test if config class can be called with Config(prop_name=..) + for idx, name in enumerate(common_properties): + try: + config = self.config_class(**{name: idx}) + self.parent.assertEqual( + getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" + ) + except NotImplementedError: + # Some models might not be able to implement setters for common_properties + # In that case, a NotImplementedError is raised + pass + + def create_and_test_config_to_json_string(self): + config = self.config_class(**self.inputs_dict) + obj = json.loads(config.to_json_string()) + for key, value in self.inputs_dict.items(): + self.parent.assertEqual(obj[key], value) + + def create_and_test_config_to_json_file(self): + config_first = self.config_class(**self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "config.json") + config_first.to_json_file(json_file_path) + config_second = self.config_class.from_json_file(json_file_path) + + self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) + + def create_and_test_config_from_and_save_pretrained(self): + config_first = self.config_class(**self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + config_first.save_pretrained(tmpdirname) + config_second = self.config_class.from_pretrained(tmpdirname) + + self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) + + with self.parent.assertRaises(OSError): + self.config_class.from_pretrained(f".{tmpdirname}") + + def create_and_test_config_from_and_save_pretrained_subfolder(self): + config_first = self.config_class(**self.inputs_dict) + + subfolder = "test" + with tempfile.TemporaryDirectory() as tmpdirname: + sub_tmpdirname = os.path.join(tmpdirname, subfolder) + config_first.save_pretrained(sub_tmpdirname) + config_second = self.config_class.from_pretrained(tmpdirname, subfolder=subfolder) + + self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) + + def create_and_test_config_with_num_labels(self): + config = self.config_class(**self.inputs_dict, num_labels=5) + self.parent.assertEqual(len(config.id2label), 5) + self.parent.assertEqual(len(config.label2id), 5) + + config.num_labels = 3 + self.parent.assertEqual(len(config.id2label), 3) + self.parent.assertEqual(len(config.label2id), 3) + + def check_config_can_be_init_without_params(self): + if self.config_class.is_composition: + with self.parent.assertRaises(ValueError): + config = self.config_class() + else: + config = self.config_class() + self.parent.assertIsNotNone(config) + + def check_config_arguments_init(self): + kwargs = copy.deepcopy(config_common_kwargs) + config = self.config_class(**kwargs) + wrong_values = [] + for key, value in config_common_kwargs.items(): + if key == "torch_dtype": + if not is_torch_available(): + continue + else: + import torch + + if config.torch_dtype != torch.float16: + wrong_values.append(("torch_dtype", config.torch_dtype, torch.float16)) + elif getattr(config, key) != value: + wrong_values.append((key, getattr(config, key), value)) + + if len(wrong_values) > 0: + errors = "\n".join([f"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values]) + raise ValueError(f"The following keys were not properly set in the config:\n{errors}") + + def run_common_tests(self): + self.create_and_test_config_common_properties() + self.create_and_test_config_to_json_string() + self.create_and_test_config_to_json_file() + self.create_and_test_config_from_and_save_pretrained() + self.create_and_test_config_from_and_save_pretrained_subfolder() + self.create_and_test_config_with_num_labels() + self.check_config_can_be_init_without_params() + self.check_config_arguments_init() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_configuration_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_configuration_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2ceb1695fa96cc1ef7115f1c456acb07f44f10b7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_configuration_utils.py @@ -0,0 +1,298 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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 shutil +import sys +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from huggingface_hub import HfFolder, delete_repo +from requests.exceptions import HTTPError + +from transformers import AutoConfig, BertConfig, GPT2Config +from transformers.configuration_utils import PretrainedConfig +from transformers.testing_utils import TOKEN, USER, is_staging_test + + +sys.path.append(str(Path(__file__).parent.parent / "utils")) + +from test_module.custom_configuration import CustomConfig # noqa E402 + + +config_common_kwargs = { + "return_dict": False, + "output_hidden_states": True, + "output_attentions": True, + "torchscript": True, + "torch_dtype": "float16", + "use_bfloat16": True, + "tf_legacy_loss": True, + "pruned_heads": {"a": 1}, + "tie_word_embeddings": False, + "is_decoder": True, + "cross_attention_hidden_size": 128, + "add_cross_attention": True, + "tie_encoder_decoder": True, + "max_length": 50, + "min_length": 3, + "do_sample": True, + "early_stopping": True, + "num_beams": 3, + "num_beam_groups": 3, + "diversity_penalty": 0.5, + "temperature": 2.0, + "top_k": 10, + "top_p": 0.7, + "typical_p": 0.2, + "repetition_penalty": 0.8, + "length_penalty": 0.8, + "no_repeat_ngram_size": 5, + "encoder_no_repeat_ngram_size": 5, + "bad_words_ids": [1, 2, 3], + "num_return_sequences": 3, + "chunk_size_feed_forward": 5, + "output_scores": True, + "return_dict_in_generate": True, + "forced_bos_token_id": 2, + "forced_eos_token_id": 3, + "remove_invalid_values": True, + "architectures": ["BertModel"], + "finetuning_task": "translation", + "id2label": {0: "label"}, + "label2id": {"label": "0"}, + "tokenizer_class": "BertTokenizerFast", + "prefix": "prefix", + "bos_token_id": 6, + "pad_token_id": 7, + "eos_token_id": 8, + "sep_token_id": 9, + "decoder_start_token_id": 10, + "exponential_decay_length_penalty": (5, 1.01), + "suppress_tokens": [0, 1], + "begin_suppress_tokens": 2, + "task_specific_params": {"translation": "some_params"}, + "problem_type": "regression", +} + + +@is_staging_test +class ConfigPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + try: + delete_repo(token=cls._token, repo_id="test-config") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="valid_org/test-config-org") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="test-dynamic-config") + except HTTPError: + pass + + def test_push_to_hub(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + config.push_to_hub("test-config", token=self._token) + + new_config = BertConfig.from_pretrained(f"{USER}/test-config") + for k, v in config.to_dict().items(): + if k != "transformers_version": + self.assertEqual(v, getattr(new_config, k)) + + # Reset repo + delete_repo(token=self._token, repo_id="test-config") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + config.save_pretrained(tmp_dir, repo_id="test-config", push_to_hub=True, token=self._token) + + new_config = BertConfig.from_pretrained(f"{USER}/test-config") + for k, v in config.to_dict().items(): + if k != "transformers_version": + self.assertEqual(v, getattr(new_config, k)) + + def test_push_to_hub_in_organization(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + config.push_to_hub("valid_org/test-config-org", token=self._token) + + new_config = BertConfig.from_pretrained("valid_org/test-config-org") + for k, v in config.to_dict().items(): + if k != "transformers_version": + self.assertEqual(v, getattr(new_config, k)) + + # Reset repo + delete_repo(token=self._token, repo_id="valid_org/test-config-org") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + config.save_pretrained(tmp_dir, repo_id="valid_org/test-config-org", push_to_hub=True, token=self._token) + + new_config = BertConfig.from_pretrained("valid_org/test-config-org") + for k, v in config.to_dict().items(): + if k != "transformers_version": + self.assertEqual(v, getattr(new_config, k)) + + def test_push_to_hub_dynamic_config(self): + CustomConfig.register_for_auto_class() + config = CustomConfig(attribute=42) + + config.push_to_hub("test-dynamic-config", token=self._token) + + # This has added the proper auto_map field to the config + self.assertDictEqual(config.auto_map, {"AutoConfig": "custom_configuration.CustomConfig"}) + + new_config = AutoConfig.from_pretrained(f"{USER}/test-dynamic-config", trust_remote_code=True) + # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module + self.assertEqual(new_config.__class__.__name__, "CustomConfig") + self.assertEqual(new_config.attribute, 42) + + +class ConfigTestUtils(unittest.TestCase): + def test_config_from_string(self): + c = GPT2Config() + + # attempt to modify each of int/float/bool/str config records and verify they were updated + n_embd = c.n_embd + 1 # int + resid_pdrop = c.resid_pdrop + 1.0 # float + scale_attn_weights = not c.scale_attn_weights # bool + summary_type = c.summary_type + "foo" # str + c.update_from_string( + f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}" + ) + self.assertEqual(n_embd, c.n_embd, "mismatch for key: n_embd") + self.assertEqual(resid_pdrop, c.resid_pdrop, "mismatch for key: resid_pdrop") + self.assertEqual(scale_attn_weights, c.scale_attn_weights, "mismatch for key: scale_attn_weights") + self.assertEqual(summary_type, c.summary_type, "mismatch for key: summary_type") + + def test_config_common_kwargs_is_complete(self): + base_config = PretrainedConfig() + missing_keys = [key for key in base_config.__dict__ if key not in config_common_kwargs] + # If this part of the test fails, you have arguments to addin config_common_kwargs above. + self.assertListEqual( + missing_keys, + [ + "is_encoder_decoder", + "_name_or_path", + "_commit_hash", + "_attn_implementation_internal", + "transformers_version", + ], + ) + keys_with_defaults = [key for key, value in config_common_kwargs.items() if value == getattr(base_config, key)] + if len(keys_with_defaults) > 0: + raise ValueError( + "The following keys are set with the default values in" + " `test_configuration_common.config_common_kwargs` pick another value for them:" + f" {', '.join(keys_with_defaults)}." + ) + + def test_nested_config_load_from_dict(self): + config = AutoConfig.from_pretrained( + "hf-internal-testing/tiny-random-CLIPModel", text_config={"num_hidden_layers": 2} + ) + self.assertNotIsInstance(config.text_config, dict) + self.assertEqual(config.text_config.__class__.__name__, "CLIPTextConfig") + + def test_from_pretrained_subfolder(self): + with self.assertRaises(OSError): + # config is in subfolder, the following should not work without specifying the subfolder + _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder") + + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder", subfolder="bert") + + self.assertIsNotNone(config) + + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + # This check we did call the fake head request + mock_head.assert_called() + + def test_legacy_load_from_url(self): + # This test is for deprecated behavior and can be removed in v5 + _ = BertConfig.from_pretrained( + "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" + ) + + def test_local_versioning(self): + configuration = AutoConfig.from_pretrained("bert-base-cased") + configuration.configuration_files = ["config.4.0.0.json"] + + with tempfile.TemporaryDirectory() as tmp_dir: + configuration.save_pretrained(tmp_dir) + configuration.hidden_size = 2 + json.dump(configuration.to_dict(), open(os.path.join(tmp_dir, "config.4.0.0.json"), "w")) + + # This should pick the new configuration file as the version of Transformers is > 4.0.0 + new_configuration = AutoConfig.from_pretrained(tmp_dir) + self.assertEqual(new_configuration.hidden_size, 2) + + # Will need to be adjusted if we reach v42 and this test is still here. + # Should pick the old configuration file as the version of Transformers is < 4.42.0 + configuration.configuration_files = ["config.42.0.0.json"] + configuration.hidden_size = 768 + configuration.save_pretrained(tmp_dir) + shutil.move(os.path.join(tmp_dir, "config.4.0.0.json"), os.path.join(tmp_dir, "config.42.0.0.json")) + new_configuration = AutoConfig.from_pretrained(tmp_dir) + self.assertEqual(new_configuration.hidden_size, 768) + + def test_repo_versioning_before(self): + # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. + repo = "hf-internal-testing/test-two-configs" + + import transformers as new_transformers + + new_transformers.configuration_utils.__version__ = "v4.0.0" + new_configuration, kwargs = new_transformers.models.auto.AutoConfig.from_pretrained( + repo, return_unused_kwargs=True + ) + self.assertEqual(new_configuration.hidden_size, 2) + # This checks `_configuration_file` ia not kept in the kwargs by mistake. + self.assertDictEqual(kwargs, {}) + + # Testing an older version by monkey-patching the version in the module it's used. + import transformers as old_transformers + + old_transformers.configuration_utils.__version__ = "v3.0.0" + old_configuration = old_transformers.models.auto.AutoConfig.from_pretrained(repo) + self.assertEqual(old_configuration.hidden_size, 768) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_feature_extraction_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_feature_extraction_common.py new file mode 100644 index 0000000000000000000000000000000000000000..49937309d0e01ea1f92e7823e51a88e6040735bd --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_feature_extraction_common.py @@ -0,0 +1,55 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 tempfile + +from transformers.testing_utils import check_json_file_has_correct_format + + +class FeatureExtractionSavingTestMixin: + test_cast_dtype = None + + def test_feat_extract_to_json_string(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + obj = json.loads(feat_extract.to_json_string()) + for key, value in self.feat_extract_dict.items(): + self.assertEqual(obj[key], value) + + def test_feat_extract_to_json_file(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "feat_extract.json") + feat_extract_first.to_json_file(json_file_path) + feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path) + + self.assertEqual(feat_extract_second.to_dict(), feat_extract_first.to_dict()) + + def test_feat_extract_from_and_save_pretrained(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = feat_extract_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname) + + self.assertEqual(feat_extract_second.to_dict(), feat_extract_first.to_dict()) + + def test_init_without_params(self): + feat_extract = self.feature_extraction_class() + self.assertIsNotNone(feat_extract) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_feature_extraction_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_feature_extraction_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7467cac139c472ab49204ad58dc75f06122e391f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_feature_extraction_utils.py @@ -0,0 +1,144 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 sys +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from huggingface_hub import HfFolder, delete_repo +from requests.exceptions import HTTPError + +from transformers import AutoFeatureExtractor, Wav2Vec2FeatureExtractor +from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test + + +sys.path.append(str(Path(__file__).parent.parent / "utils")) + +from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 + + +SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR = get_tests_dir("fixtures") + + +class FeatureExtractorUtilTester(unittest.TestCase): + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = Wav2Vec2FeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2") + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = Wav2Vec2FeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2") + # This check we did call the fake head request + mock_head.assert_called() + + def test_legacy_load_from_url(self): + # This test is for deprecated behavior and can be removed in v5 + _ = Wav2Vec2FeatureExtractor.from_pretrained( + "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json" + ) + + +@is_staging_test +class FeatureExtractorPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + try: + delete_repo(token=cls._token, repo_id="test-feature-extractor") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="valid_org/test-feature-extractor-org") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="test-dynamic-feature-extractor") + except HTTPError: + pass + + def test_push_to_hub(self): + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) + feature_extractor.push_to_hub("test-feature-extractor", token=self._token) + + new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor") + for k, v in feature_extractor.__dict__.items(): + self.assertEqual(v, getattr(new_feature_extractor, k)) + + # Reset repo + delete_repo(token=self._token, repo_id="test-feature-extractor") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + feature_extractor.save_pretrained( + tmp_dir, repo_id="test-feature-extractor", push_to_hub=True, token=self._token + ) + + new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor") + for k, v in feature_extractor.__dict__.items(): + self.assertEqual(v, getattr(new_feature_extractor, k)) + + def test_push_to_hub_in_organization(self): + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) + feature_extractor.push_to_hub("valid_org/test-feature-extractor", token=self._token) + + new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("valid_org/test-feature-extractor") + for k, v in feature_extractor.__dict__.items(): + self.assertEqual(v, getattr(new_feature_extractor, k)) + + # Reset repo + delete_repo(token=self._token, repo_id="valid_org/test-feature-extractor") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + feature_extractor.save_pretrained( + tmp_dir, repo_id="valid_org/test-feature-extractor-org", push_to_hub=True, token=self._token + ) + + new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org") + for k, v in feature_extractor.__dict__.items(): + self.assertEqual(v, getattr(new_feature_extractor, k)) + + def test_push_to_hub_dynamic_feature_extractor(self): + CustomFeatureExtractor.register_for_auto_class() + feature_extractor = CustomFeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) + + feature_extractor.push_to_hub("test-dynamic-feature-extractor", token=self._token) + + # This has added the proper auto_map field to the config + self.assertDictEqual( + feature_extractor.auto_map, + {"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"}, + ) + + new_feature_extractor = AutoFeatureExtractor.from_pretrained( + f"{USER}/test-dynamic-feature-extractor", trust_remote_code=True + ) + # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module + self.assertEqual(new_feature_extractor.__class__.__name__, "CustomFeatureExtractor") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_processing_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_processing_common.py new file mode 100644 index 0000000000000000000000000000000000000000..dcbee270f90b6e4a93f685e6cb33c26e016bafa0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_processing_common.py @@ -0,0 +1,368 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 pathlib +import tempfile + +from transformers import BatchFeature +from transformers.image_utils import AnnotationFormat, AnnotionFormat +from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + + +if is_torch_available(): + import numpy as np + import torch + +if is_vision_available(): + from PIL import Image + + +def prepare_image_inputs( + batch_size, + min_resolution, + max_resolution, + num_channels, + size_divisor=None, + equal_resolution=False, + numpify=False, + torchify=False, +): + """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, + or a list of PyTorch tensors if one specifies torchify=True. + + One can specify whether the images are of the same resolution or not. + """ + + assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" + + image_inputs = [] + for i in range(batch_size): + if equal_resolution: + width = height = max_resolution + else: + # To avoid getting image width/height 0 + if size_divisor is not None: + # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor` + min_resolution = max(size_divisor, min_resolution) + width, height = np.random.choice(np.arange(min_resolution, max_resolution), 2) + image_inputs.append(np.random.randint(255, size=(num_channels, width, height), dtype=np.uint8)) + + if not numpify and not torchify: + # PIL expects the channel dimension as last dimension + image_inputs = [Image.fromarray(np.moveaxis(image, 0, -1)) for image in image_inputs] + + if torchify: + image_inputs = [torch.from_numpy(image) for image in image_inputs] + + return image_inputs + + +def prepare_video(num_frames, num_channels, width=10, height=10, numpify=False, torchify=False): + """This function prepares a video as a list of PIL images/NumPy arrays/PyTorch tensors.""" + + video = [] + for i in range(num_frames): + video.append(np.random.randint(255, size=(num_channels, width, height), dtype=np.uint8)) + + if not numpify and not torchify: + # PIL expects the channel dimension as last dimension + video = [Image.fromarray(np.moveaxis(frame, 0, -1)) for frame in video] + + if torchify: + video = [torch.from_numpy(frame) for frame in video] + + return video + + +def prepare_video_inputs( + batch_size, + num_frames, + num_channels, + min_resolution, + max_resolution, + equal_resolution=False, + numpify=False, + torchify=False, +): + """This function prepares a batch of videos: a list of list of PIL images, or a list of list of numpy arrays if + one specifies numpify=True, or a list of list of PyTorch tensors if one specifies torchify=True. + + One can specify whether the videos are of the same resolution or not. + """ + + assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" + + video_inputs = [] + for i in range(batch_size): + if equal_resolution: + width = height = max_resolution + else: + width, height = np.random.choice(np.arange(min_resolution, max_resolution), 2) + video = prepare_video( + num_frames=num_frames, + num_channels=num_channels, + width=width, + height=height, + numpify=numpify, + torchify=torchify, + ) + video_inputs.append(video) + + return video_inputs + + +class ImageProcessingTestMixin: + test_cast_dtype = None + + def test_image_processor_to_json_string(self): + image_processor = self.image_processing_class(**self.image_processor_dict) + obj = json.loads(image_processor.to_json_string()) + for key, value in self.image_processor_dict.items(): + self.assertEqual(obj[key], value) + + def test_image_processor_to_json_file(self): + image_processor_first = self.image_processing_class(**self.image_processor_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "image_processor.json") + image_processor_first.to_json_file(json_file_path) + image_processor_second = self.image_processing_class.from_json_file(json_file_path) + + self.assertEqual(image_processor_second.to_dict(), image_processor_first.to_dict()) + + def test_image_processor_from_and_save_pretrained(self): + image_processor_first = self.image_processing_class(**self.image_processor_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = image_processor_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + image_processor_second = self.image_processing_class.from_pretrained(tmpdirname) + + self.assertEqual(image_processor_second.to_dict(), image_processor_first.to_dict()) + + def test_init_without_params(self): + image_processor = self.image_processing_class() + self.assertIsNotNone(image_processor) + + @require_torch + @require_vision + def test_cast_dtype_device(self): + if self.test_cast_dtype is not None: + # Initialize image_processor + image_processor = self.image_processing_class(**self.image_processor_dict) + + # create random PyTorch tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + + encoding = image_processor(image_inputs, return_tensors="pt") + # for layoutLM compatiblity + self.assertEqual(encoding.pixel_values.device, torch.device("cpu")) + self.assertEqual(encoding.pixel_values.dtype, torch.float32) + + encoding = image_processor(image_inputs, return_tensors="pt").to(torch.float16) + self.assertEqual(encoding.pixel_values.device, torch.device("cpu")) + self.assertEqual(encoding.pixel_values.dtype, torch.float16) + + encoding = image_processor(image_inputs, return_tensors="pt").to("cpu", torch.bfloat16) + self.assertEqual(encoding.pixel_values.device, torch.device("cpu")) + self.assertEqual(encoding.pixel_values.dtype, torch.bfloat16) + + with self.assertRaises(TypeError): + _ = image_processor(image_inputs, return_tensors="pt").to(torch.bfloat16, "cpu") + + # Try with text + image feature + encoding = image_processor(image_inputs, return_tensors="pt") + encoding.update({"input_ids": torch.LongTensor([[1, 2, 3], [4, 5, 6]])}) + encoding = encoding.to(torch.float16) + + self.assertEqual(encoding.pixel_values.device, torch.device("cpu")) + self.assertEqual(encoding.pixel_values.dtype, torch.float16) + self.assertEqual(encoding.input_ids.dtype, torch.long) + + def test_call_pil(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PIL images + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) + for image in image_inputs: + self.assertIsInstance(image, Image.Image) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Test batched + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) + self.assertEqual( + tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) + ) + + def test_call_numpy(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) + for image in image_inputs: + self.assertIsInstance(image, np.ndarray) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Test batched + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) + self.assertEqual( + tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) + ) + + def test_call_pytorch(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Test batched + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + self.assertEqual( + tuple(encoded_images.shape), + (self.image_processor_tester.batch_size, *expected_output_image_shape), + ) + + def test_call_numpy_4_channels(self): + # Test that can process images which have an arbitrary number of channels + # Initialize image_processing + image_processor = self.image_processing_class(**self.image_processor_dict) + + # create random numpy tensors + self.image_processor_tester.num_channels = 4 + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) + + # Test not batched input + encoded_images = image_processor( + image_inputs[0], + return_tensors="pt", + input_data_format="channels_first", + image_mean=0, + image_std=1, + ).pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Test batched + encoded_images = image_processor( + image_inputs, + return_tensors="pt", + input_data_format="channels_first", + image_mean=0, + image_std=1, + ).pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) + self.assertEqual( + tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) + ) + + +class AnnotationFormatTestMixin: + # this mixin adds a test to assert that usages of the + # to-be-deprecated `AnnotionFormat` continue to be + # supported for the time being + + def test_processor_can_use_legacy_annotation_format(self): + image_processor_dict = self.image_processor_tester.prepare_image_processor_dict() + fixtures_path = pathlib.Path(__file__).parent / "fixtures" / "tests_samples" / "COCO" + + with open(fixtures_path / "coco_annotations.txt", "r") as f: + detection_target = json.loads(f.read()) + + detection_annotations = {"image_id": 39769, "annotations": detection_target} + + detection_params = { + "images": Image.open(fixtures_path / "000000039769.png"), + "annotations": detection_annotations, + "return_tensors": "pt", + } + + with open(fixtures_path / "coco_panoptic_annotations.txt", "r") as f: + panoptic_target = json.loads(f.read()) + + panoptic_annotations = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": panoptic_target} + + masks_path = pathlib.Path(fixtures_path / "coco_panoptic") + + panoptic_params = { + "images": Image.open(fixtures_path / "000000039769.png"), + "annotations": panoptic_annotations, + "return_tensors": "pt", + "masks_path": masks_path, + } + + test_cases = [ + ("coco_detection", detection_params), + ("coco_panoptic", panoptic_params), + (AnnotionFormat.COCO_DETECTION, detection_params), + (AnnotionFormat.COCO_PANOPTIC, panoptic_params), + (AnnotationFormat.COCO_DETECTION, detection_params), + (AnnotationFormat.COCO_PANOPTIC, panoptic_params), + ] + + def _compare(a, b) -> None: + if isinstance(a, (dict, BatchFeature)): + self.assertEqual(a.keys(), b.keys()) + for k, v in a.items(): + _compare(v, b[k]) + elif isinstance(a, list): + self.assertEqual(len(a), len(b)) + for idx in range(len(a)): + _compare(a[idx], b[idx]) + elif isinstance(a, torch.Tensor): + self.assertTrue(torch.allclose(a, b, atol=1e-3)) + elif isinstance(a, str): + self.assertEqual(a, b) + + for annotation_format, params in test_cases: + with self.subTest(annotation_format): + image_processor_params = {**image_processor_dict, **{"format": annotation_format}} + image_processor_first = self.image_processing_class(**image_processor_params) + + with tempfile.TemporaryDirectory() as tmpdirname: + image_processor_first.save_pretrained(tmpdirname) + image_processor_second = self.image_processing_class.from_pretrained(tmpdirname) + + # check the 'format' key exists and that the dicts of the + # first and second processors are equal + self.assertIn("format", image_processor_first.to_dict().keys()) + self.assertEqual(image_processor_second.to_dict(), image_processor_first.to_dict()) + + # perform encoding using both processors and compare + # the resulting BatchFeatures + first_encoding = image_processor_first(**params) + second_encoding = image_processor_second(**params) + _compare(first_encoding, second_encoding) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_processing_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_processing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3be8ee3c26dbe0913e8031d1c9d897e341e457dd --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_processing_utils.py @@ -0,0 +1,154 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 sys +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from huggingface_hub import HfFolder, delete_repo +from requests.exceptions import HTTPError + +from transformers import AutoImageProcessor, ViTImageProcessor +from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test + + +sys.path.append(str(Path(__file__).parent.parent / "utils")) + +from test_module.custom_image_processing import CustomImageProcessor # noqa E402 + + +SAMPLE_IMAGE_PROCESSING_CONFIG_DIR = get_tests_dir("fixtures") + + +class ImageProcessorUtilTester(unittest.TestCase): + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit") + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit") + # This check we did call the fake head request + mock_head.assert_called() + + def test_legacy_load_from_url(self): + # This test is for deprecated behavior and can be removed in v5 + _ = ViTImageProcessor.from_pretrained( + "https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json" + ) + + def test_image_processor_from_pretrained_subfolder(self): + with self.assertRaises(OSError): + # config is in subfolder, the following should not work without specifying the subfolder + _ = AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants") + + config = AutoImageProcessor.from_pretrained( + "hf-internal-testing/stable-diffusion-all-variants", subfolder="feature_extractor" + ) + + self.assertIsNotNone(config) + + +@is_staging_test +class ImageProcessorPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + try: + delete_repo(token=cls._token, repo_id="test-image-processor") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="valid_org/test-image-processor-org") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="test-dynamic-image-processor") + except HTTPError: + pass + + def test_push_to_hub(self): + image_processor = ViTImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) + image_processor.push_to_hub("test-image-processor", token=self._token) + + new_image_processor = ViTImageProcessor.from_pretrained(f"{USER}/test-image-processor") + for k, v in image_processor.__dict__.items(): + self.assertEqual(v, getattr(new_image_processor, k)) + + # Reset repo + delete_repo(token=self._token, repo_id="test-image-processor") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + image_processor.save_pretrained( + tmp_dir, repo_id="test-image-processor", push_to_hub=True, token=self._token + ) + + new_image_processor = ViTImageProcessor.from_pretrained(f"{USER}/test-image-processor") + for k, v in image_processor.__dict__.items(): + self.assertEqual(v, getattr(new_image_processor, k)) + + def test_push_to_hub_in_organization(self): + image_processor = ViTImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) + image_processor.push_to_hub("valid_org/test-image-processor", token=self._token) + + new_image_processor = ViTImageProcessor.from_pretrained("valid_org/test-image-processor") + for k, v in image_processor.__dict__.items(): + self.assertEqual(v, getattr(new_image_processor, k)) + + # Reset repo + delete_repo(token=self._token, repo_id="valid_org/test-image-processor") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + image_processor.save_pretrained( + tmp_dir, repo_id="valid_org/test-image-processor-org", push_to_hub=True, token=self._token + ) + + new_image_processor = ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org") + for k, v in image_processor.__dict__.items(): + self.assertEqual(v, getattr(new_image_processor, k)) + + def test_push_to_hub_dynamic_image_processor(self): + CustomImageProcessor.register_for_auto_class() + image_processor = CustomImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) + + image_processor.push_to_hub("test-dynamic-image-processor", token=self._token) + + # This has added the proper auto_map field to the config + self.assertDictEqual( + image_processor.auto_map, + {"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"}, + ) + + new_image_processor = AutoImageProcessor.from_pretrained( + f"{USER}/test-dynamic-image-processor", trust_remote_code=True + ) + # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module + self.assertEqual(new_image_processor.__class__.__name__, "CustomImageProcessor") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_transforms.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..ae86f84def5106100841eae7330a3bd4b9258b4c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_image_transforms.py @@ -0,0 +1,660 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. +# +# 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 unittest + +import numpy as np +from parameterized import parameterized + +from transformers.testing_utils import require_flax, require_tf, require_torch, require_vision +from transformers.utils.import_utils import is_flax_available, is_tf_available, is_torch_available, is_vision_available + + +if is_torch_available(): + import torch + +if is_tf_available(): + import tensorflow as tf + +if is_flax_available(): + import jax + +if is_vision_available(): + import PIL.Image + + from transformers.image_transforms import ( + center_crop, + center_to_corners_format, + convert_to_rgb, + corners_to_center_format, + flip_channel_order, + get_resize_output_image_size, + id_to_rgb, + normalize, + pad, + resize, + rgb_to_id, + to_channel_dimension_format, + to_pil_image, + ) + + +def get_random_image(height, width, num_channels=3, channels_first=True): + shape = (num_channels, height, width) if channels_first else (height, width, num_channels) + random_array = np.random.randint(0, 256, shape, dtype=np.uint8) + return random_array + + +@require_vision +class ImageTransformsTester(unittest.TestCase): + @parameterized.expand( + [ + ("numpy_float_channels_first", (3, 4, 5), np.float32), + ("numpy_float_channels_last", (4, 5, 3), np.float32), + ("numpy_float_channels_first", (3, 4, 5), np.float64), + ("numpy_float_channels_last", (4, 5, 3), np.float64), + ("numpy_int_channels_first", (3, 4, 5), np.int32), + ("numpy_uint_channels_first", (3, 4, 5), np.uint8), + ] + ) + @require_vision + def test_to_pil_image(self, name, image_shape, dtype): + image = np.random.randint(0, 256, image_shape).astype(dtype) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + # make sure image is correctly rescaled + self.assertTrue(np.abs(np.asarray(pil_image)).sum() > 0) + + @parameterized.expand( + [ + ("numpy_float_channels_first", (3, 4, 5), np.float32), + ("numpy_float_channels_first", (3, 4, 5), np.float64), + ("numpy_float_channels_last", (4, 5, 3), np.float32), + ("numpy_float_channels_last", (4, 5, 3), np.float64), + ] + ) + @require_vision + def test_to_pil_image_from_float(self, name, image_shape, dtype): + image = np.random.rand(*image_shape).astype(dtype) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + # make sure image is correctly rescaled + self.assertTrue(np.abs(np.asarray(pil_image)).sum() > 0) + + # Make sure that an exception is raised if image is not in [0, 1] + image = np.random.randn(*image_shape).astype(dtype) + with self.assertRaises(ValueError): + to_pil_image(image) + + @require_vision + def test_to_pil_image_from_mask(self): + # Make sure binary mask remains a binary mask + image = np.random.randint(0, 2, (3, 4, 5)).astype(np.uint8) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + np_img = np.asarray(pil_image) + self.assertTrue(np_img.min() == 0) + self.assertTrue(np_img.max() == 1) + + image = np.random.randint(0, 2, (3, 4, 5)).astype(np.float32) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + np_img = np.asarray(pil_image) + self.assertTrue(np_img.min() == 0) + self.assertTrue(np_img.max() == 1) + + @require_tf + def test_to_pil_image_from_tensorflow(self): + # channels_first + image = tf.random.uniform((3, 4, 5)) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + # channels_last + image = tf.random.uniform((4, 5, 3)) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + @require_torch + def test_to_pil_image_from_torch(self): + # channels first + image = torch.rand((3, 4, 5)) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + # channels last + image = torch.rand((4, 5, 3)) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + @require_flax + def test_to_pil_image_from_jax(self): + key = jax.random.PRNGKey(0) + # channel first + image = jax.random.uniform(key, (3, 4, 5)) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + # channel last + image = jax.random.uniform(key, (4, 5, 3)) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + def test_to_channel_dimension_format(self): + # Test that function doesn't reorder if channel dim matches the input. + image = np.random.rand(3, 4, 5) + image = to_channel_dimension_format(image, "channels_first") + self.assertEqual(image.shape, (3, 4, 5)) + + image = np.random.rand(4, 5, 3) + image = to_channel_dimension_format(image, "channels_last") + self.assertEqual(image.shape, (4, 5, 3)) + + # Test that function reorders if channel dim doesn't match the input. + image = np.random.rand(3, 4, 5) + image = to_channel_dimension_format(image, "channels_last") + self.assertEqual(image.shape, (4, 5, 3)) + + image = np.random.rand(4, 5, 3) + image = to_channel_dimension_format(image, "channels_first") + self.assertEqual(image.shape, (3, 4, 5)) + + # Can pass in input_data_format and works if data format is ambiguous or unknown. + image = np.random.rand(4, 5, 6) + image = to_channel_dimension_format(image, "channels_first", input_channel_dim="channels_last") + self.assertEqual(image.shape, (6, 4, 5)) + + def test_get_resize_output_image_size(self): + image = np.random.randint(0, 256, (3, 224, 224)) + + # Test the output size defaults to (x, x) if an int is given. + self.assertEqual(get_resize_output_image_size(image, 10), (10, 10)) + self.assertEqual(get_resize_output_image_size(image, [10]), (10, 10)) + self.assertEqual(get_resize_output_image_size(image, (10,)), (10, 10)) + + # Test the output size is the same as the input if a two element tuple/list is given. + self.assertEqual(get_resize_output_image_size(image, (10, 20)), (10, 20)) + self.assertEqual(get_resize_output_image_size(image, [10, 20]), (10, 20)) + self.assertEqual(get_resize_output_image_size(image, (10, 20), default_to_square=True), (10, 20)) + # To match pytorch behaviour, max_size is only relevant if size is an int + self.assertEqual(get_resize_output_image_size(image, (10, 20), max_size=5), (10, 20)) + + # Test output size = (int(size * height / width), size) if size is an int and height > width + image = np.random.randint(0, 256, (3, 50, 40)) + self.assertEqual(get_resize_output_image_size(image, 20, default_to_square=False), (25, 20)) + + # Test output size = (size, int(size * width / height)) if size is an int and width <= height + image = np.random.randint(0, 256, (3, 40, 50)) + self.assertEqual(get_resize_output_image_size(image, 20, default_to_square=False), (20, 25)) + + # Test size is resized if longer size > max_size + image = np.random.randint(0, 256, (3, 50, 40)) + self.assertEqual(get_resize_output_image_size(image, 20, default_to_square=False, max_size=22), (22, 17)) + + # Test output size = (int(size * height / width), size) if size is an int and height > width and + # input has 4 channels + image = np.random.randint(0, 256, (4, 50, 40)) + self.assertEqual( + get_resize_output_image_size(image, 20, default_to_square=False, input_data_format="channels_first"), + (25, 20), + ) + + # Test correct channel dimension is returned if output size if height == 3 + # Defaults to input format - channels first + image = np.random.randint(0, 256, (3, 18, 97)) + resized_image = resize(image, (3, 20)) + self.assertEqual(resized_image.shape, (3, 3, 20)) + + # Defaults to input format - channels last + image = np.random.randint(0, 256, (18, 97, 3)) + resized_image = resize(image, (3, 20)) + self.assertEqual(resized_image.shape, (3, 20, 3)) + + image = np.random.randint(0, 256, (3, 18, 97)) + resized_image = resize(image, (3, 20), data_format="channels_last") + self.assertEqual(resized_image.shape, (3, 20, 3)) + + image = np.random.randint(0, 256, (18, 97, 3)) + resized_image = resize(image, (3, 20), data_format="channels_first") + self.assertEqual(resized_image.shape, (3, 3, 20)) + + def test_resize(self): + image = np.random.randint(0, 256, (3, 224, 224)) + + # Check the channel order is the same by default + resized_image = resize(image, (30, 40)) + self.assertIsInstance(resized_image, np.ndarray) + self.assertEqual(resized_image.shape, (3, 30, 40)) + + # Check channel order is changed if specified + resized_image = resize(image, (30, 40), data_format="channels_last") + self.assertIsInstance(resized_image, np.ndarray) + self.assertEqual(resized_image.shape, (30, 40, 3)) + + # Check PIL.Image.Image is returned if return_numpy=False + resized_image = resize(image, (30, 40), return_numpy=False) + self.assertIsInstance(resized_image, PIL.Image.Image) + # PIL size is in (width, height) order + self.assertEqual(resized_image.size, (40, 30)) + + # Check an image with float values between 0-1 is returned with values in this range + image = np.random.rand(3, 224, 224) + resized_image = resize(image, (30, 40)) + self.assertIsInstance(resized_image, np.ndarray) + self.assertEqual(resized_image.shape, (3, 30, 40)) + self.assertTrue(np.all(resized_image >= 0)) + self.assertTrue(np.all(resized_image <= 1)) + + # Check that an image with 4 channels is resized correctly + image = np.random.randint(0, 256, (4, 224, 224)) + resized_image = resize(image, (30, 40), input_data_format="channels_first") + self.assertIsInstance(resized_image, np.ndarray) + self.assertEqual(resized_image.shape, (4, 30, 40)) + + def test_normalize(self): + image = np.random.randint(0, 256, (224, 224, 3)) / 255 + + # Test that exception is raised if inputs are incorrect + # Not a numpy array image + with self.assertRaises(ValueError): + normalize(5, 5, 5) + + # Number of mean values != number of channels + with self.assertRaises(ValueError): + normalize(image, mean=(0.5, 0.6), std=1) + + # Number of std values != number of channels + with self.assertRaises(ValueError): + normalize(image, mean=1, std=(0.5, 0.6)) + + # Test result is correct - output data format is channels_first and normalization + # correctly computed + mean = (0.5, 0.6, 0.7) + std = (0.1, 0.2, 0.3) + expected_image = ((image - mean) / std).transpose((2, 0, 1)) + + normalized_image = normalize(image, mean=mean, std=std, data_format="channels_first") + self.assertIsInstance(normalized_image, np.ndarray) + self.assertEqual(normalized_image.shape, (3, 224, 224)) + self.assertTrue(np.allclose(normalized_image, expected_image, atol=1e-6)) + + # Test image with 4 channels is normalized correctly + image = np.random.randint(0, 256, (224, 224, 4)) / 255 + mean = (0.5, 0.6, 0.7, 0.8) + std = (0.1, 0.2, 0.3, 0.4) + expected_image = (image - mean) / std + self.assertTrue( + np.allclose( + normalize(image, mean=mean, std=std, input_data_format="channels_last"), expected_image, atol=1e-6 + ) + ) + + # Test float32 image input keeps float32 dtype + image = np.random.randint(0, 256, (224, 224, 3)).astype(np.float32) / 255 + mean = (0.5, 0.6, 0.7) + std = (0.1, 0.2, 0.3) + expected_image = ((image - mean) / std).astype(np.float32) + normalized_image = normalize(image, mean=mean, std=std) + self.assertEqual(normalized_image.dtype, np.float32) + self.assertTrue(np.allclose(normalized_image, expected_image, atol=1e-6)) + + # Test float16 image input keeps float16 dtype + image = np.random.randint(0, 256, (224, 224, 3)).astype(np.float16) / 255 + mean = (0.5, 0.6, 0.7) + std = (0.1, 0.2, 0.3) + + # The mean and std are cast to match the dtype of the input image + cast_mean = np.array(mean, dtype=np.float16) + cast_std = np.array(std, dtype=np.float16) + expected_image = (image - cast_mean) / cast_std + normalized_image = normalize(image, mean=mean, std=std) + self.assertEqual(normalized_image.dtype, np.float16) + self.assertTrue(np.allclose(normalized_image, expected_image, atol=1e-6)) + + # Test int image input is converted to float32 + image = np.random.randint(0, 2, (224, 224, 3), dtype=np.uint8) + mean = (0.5, 0.6, 0.7) + std = (0.1, 0.2, 0.3) + expected_image = (image.astype(np.float32) - mean) / std + normalized_image = normalize(image, mean=mean, std=std) + self.assertEqual(normalized_image.dtype, np.float32) + self.assertTrue(np.allclose(normalized_image, expected_image, atol=1e-6)) + + def test_center_crop(self): + image = np.random.randint(0, 256, (3, 224, 224)) + + # Test that exception is raised if inputs are incorrect + with self.assertRaises(ValueError): + center_crop(image, 10) + + # Test result is correct - output data format is channels_first and center crop + # correctly computed + expected_image = image[:, 52:172, 82:142].transpose(1, 2, 0) + cropped_image = center_crop(image, (120, 60), data_format="channels_last") + self.assertIsInstance(cropped_image, np.ndarray) + self.assertEqual(cropped_image.shape, (120, 60, 3)) + self.assertTrue(np.allclose(cropped_image, expected_image)) + + # Test that image is padded with zeros if crop size is larger than image size + expected_image = np.zeros((300, 260, 3)) + expected_image[38:262, 18:242, :] = image.transpose((1, 2, 0)) + cropped_image = center_crop(image, (300, 260), data_format="channels_last") + self.assertIsInstance(cropped_image, np.ndarray) + self.assertEqual(cropped_image.shape, (300, 260, 3)) + self.assertTrue(np.allclose(cropped_image, expected_image)) + + # Test image with 4 channels is cropped correctly + image = np.random.randint(0, 256, (224, 224, 4)) + expected_image = image[52:172, 82:142, :] + self.assertTrue(np.allclose(center_crop(image, (120, 60), input_data_format="channels_last"), expected_image)) + + def test_center_to_corners_format(self): + bbox_center = np.array([[10, 20, 4, 8], [15, 16, 3, 4]]) + expected = np.array([[8, 16, 12, 24], [13.5, 14, 16.5, 18]]) + self.assertTrue(np.allclose(center_to_corners_format(bbox_center), expected)) + + # Check that the function and inverse function are inverse of each other + self.assertTrue(np.allclose(corners_to_center_format(center_to_corners_format(bbox_center)), bbox_center)) + + def test_corners_to_center_format(self): + bbox_corners = np.array([[8, 16, 12, 24], [13.5, 14, 16.5, 18]]) + expected = np.array([[10, 20, 4, 8], [15, 16, 3, 4]]) + self.assertTrue(np.allclose(corners_to_center_format(bbox_corners), expected)) + + # Check that the function and inverse function are inverse of each other + self.assertTrue(np.allclose(center_to_corners_format(corners_to_center_format(bbox_corners)), bbox_corners)) + + def test_rgb_to_id(self): + # test list input + rgb = [125, 4, 255] + self.assertEqual(rgb_to_id(rgb), 16712829) + + # test numpy array input + color = np.array( + [ + [ + [213, 54, 165], + [88, 207, 39], + [156, 108, 128], + ], + [ + [183, 194, 46], + [137, 58, 88], + [114, 131, 233], + ], + ] + ) + expected = np.array([[10827477, 2608984, 8416412], [3064503, 5782153, 15303538]]) + self.assertTrue(np.allclose(rgb_to_id(color), expected)) + + def test_id_to_rgb(self): + # test int input + self.assertEqual(id_to_rgb(16712829), [125, 4, 255]) + + # test array input + id_array = np.array([[10827477, 2608984, 8416412], [3064503, 5782153, 15303538]]) + color = np.array( + [ + [ + [213, 54, 165], + [88, 207, 39], + [156, 108, 128], + ], + [ + [183, 194, 46], + [137, 58, 88], + [114, 131, 233], + ], + ] + ) + self.assertTrue(np.allclose(id_to_rgb(id_array), color)) + + def test_pad(self): + # fmt: off + image = np.array([[ + [0, 1], + [2, 3], + ]]) + # fmt: on + + # Test that exception is raised if unknown padding mode is specified + with self.assertRaises(ValueError): + pad(image, 10, mode="unknown") + + # Test that exception is raised if invalid padding is specified + with self.assertRaises(ValueError): + # Cannot pad on channel dimension + pad(image, (5, 10, 10)) + + # Test image is padded equally on all sides is padding is an int + # fmt: off + expected_image = np.array([ + [[0, 0, 0, 0], + [0, 0, 1, 0], + [0, 2, 3, 0], + [0, 0, 0, 0]], + ]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, 1))) + + # Test the left and right of each axis is padded (pad_left, pad_right) + # fmt: off + expected_image = np.array( + [[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 2, 3, 0], + [0, 0, 0, 0, 0]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, (2, 1)))) + + # Test only one axis is padded (pad_left, pad_right) + # fmt: off + expected_image = np.array([[ + [9, 9], + [9, 9], + [0, 1], + [2, 3], + [9, 9] + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((2, 1), (0, 0)), constant_values=9))) + + # Test padding with a constant value + # fmt: off + expected_image = np.array([[ + [8, 8, 0, 1, 9], + [8, 8, 2, 3, 9], + [8, 8, 7, 7, 9], + [8, 8, 7, 7, 9] + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), constant_values=((6, 7), (8, 9))))) + + # fmt: off + image = np.array([[ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8], + ]]) + # fmt: on + + # Test padding with PaddingMode.REFLECT + # fmt: off + expected_image = np.array([[ + [2, 1, 0, 1, 2, 1], + [5, 4, 3, 4, 5, 4], + [8, 7, 6, 7, 8, 7], + [5, 4, 3, 4, 5, 4], + [2, 1, 0, 1, 2, 1], + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), mode="reflect"))) + + # Test padding with PaddingMode.REPLICATE + # fmt: off + expected_image = np.array([[ + [0, 0, 0, 1, 2, 2], + [3, 3, 3, 4, 5, 5], + [6, 6, 6, 7, 8, 8], + [6, 6, 6, 7, 8, 8], + [6, 6, 6, 7, 8, 8], + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), mode="replicate"))) + + # Test padding with PaddingMode.SYMMETRIC + # fmt: off + expected_image = np.array([[ + [1, 0, 0, 1, 2, 2], + [4, 3, 3, 4, 5, 5], + [7, 6, 6, 7, 8, 8], + [7, 6, 6, 7, 8, 8], + [4, 3, 3, 4, 5, 5], + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), mode="symmetric"))) + + # Test we can specify the output data format + # Test padding with PaddingMode.REFLECT + # fmt: off + image = np.array([[ + [0, 1], + [2, 3], + ]]) + expected_image = np.array([ + [[0], [1], [0], [1], [0]], + [[2], [3], [2], [3], [2]], + [[0], [1], [0], [1], [0]], + [[2], [3], [2], [3], [2]] + ]) + # fmt: on + self.assertTrue( + np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), mode="reflect", data_format="channels_last")) + ) + + # Test we can pad on an image with 2 channels + # fmt: off + image = np.array([ + [[0, 1], [2, 3]], + ]) + expected_image = np.array([ + [[0, 0], [0, 1], [2, 3]], + [[0, 0], [0, 0], [0, 0]], + ]) + # fmt: on + self.assertTrue( + np.allclose( + expected_image, pad(image, ((0, 1), (1, 0)), mode="constant", input_data_format="channels_last") + ) + ) + + @require_vision + def test_convert_to_rgb(self): + # Test that an RGBA image is converted to RGB + image = np.array([[[1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.uint8) + pil_image = PIL.Image.fromarray(image) + self.assertEqual(pil_image.mode, "RGBA") + self.assertEqual(pil_image.size, (2, 1)) + + # For the moment, numpy images are returned as is + rgb_image = convert_to_rgb(image) + self.assertEqual(rgb_image.shape, (1, 2, 4)) + self.assertTrue(np.allclose(rgb_image, image)) + + # And PIL images are converted + rgb_image = convert_to_rgb(pil_image) + self.assertEqual(rgb_image.mode, "RGB") + self.assertEqual(rgb_image.size, (2, 1)) + self.assertTrue(np.allclose(np.array(rgb_image), np.array([[[1, 2, 3], [5, 6, 7]]], dtype=np.uint8))) + + # Test that a grayscale image is converted to RGB + image = np.array([[0, 255]], dtype=np.uint8) + pil_image = PIL.Image.fromarray(image) + self.assertEqual(pil_image.mode, "L") + self.assertEqual(pil_image.size, (2, 1)) + rgb_image = convert_to_rgb(pil_image) + self.assertEqual(rgb_image.mode, "RGB") + self.assertEqual(rgb_image.size, (2, 1)) + self.assertTrue(np.allclose(np.array(rgb_image), np.array([[[0, 0, 0], [255, 255, 255]]], dtype=np.uint8))) + + def test_flip_channel_order(self): + # fmt: off + img_channels_first = np.array([ + [[ 0, 1, 2, 3], + [ 4, 5, 6, 7]], + + [[ 8, 9, 10, 11], + [12, 13, 14, 15]], + + [[16, 17, 18, 19], + [20, 21, 22, 23]], + ]) + # fmt: on + img_channels_last = np.moveaxis(img_channels_first, 0, -1) + # fmt: off + flipped_img_channels_first = np.array([ + [[16, 17, 18, 19], + [20, 21, 22, 23]], + + [[ 8, 9, 10, 11], + [12, 13, 14, 15]], + + [[ 0, 1, 2, 3], + [ 4, 5, 6, 7]], + ]) + # fmt: on + flipped_img_channels_last = np.moveaxis(flipped_img_channels_first, 0, -1) + + self.assertTrue(np.allclose(flip_channel_order(img_channels_first), flipped_img_channels_first)) + self.assertTrue( + np.allclose(flip_channel_order(img_channels_first, "channels_last"), flipped_img_channels_last) + ) + + self.assertTrue(np.allclose(flip_channel_order(img_channels_last), flipped_img_channels_last)) + self.assertTrue( + np.allclose(flip_channel_order(img_channels_last, "channels_first"), flipped_img_channels_first) + ) + + # Can flip when the image has 2 channels + # fmt: off + img_channels_first = np.array([ + [[ 0, 1, 2, 3], + [ 4, 5, 6, 7]], + + [[ 8, 9, 10, 11], + [12, 13, 14, 15]], + ]) + # fmt: on + flipped_img_channels_first = img_channels_first[::-1, :, :] + self.assertTrue( + np.allclose( + flip_channel_order(img_channels_first, input_data_format="channels_first"), flipped_img_channels_first + ) + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_common.py new file mode 100644 index 0000000000000000000000000000000000000000..85e69300516164efd63f6365b823e98468fa33f9 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_common.py @@ -0,0 +1,3750 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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 collections +import copy +import gc +import inspect +import os +import os.path +import pickle +import random +import re +import tempfile +import warnings +from collections import defaultdict +from typing import Dict, List, Tuple + +import numpy as np +from parameterized import parameterized +from pytest import mark + +import transformers +from transformers import ( + AutoModel, + AutoModelForCausalLM, + AutoModelForSequenceClassification, + PretrainedConfig, + PreTrainedModel, + is_torch_available, + logging, + set_seed, +) +from transformers.models.auto import get_values +from transformers.models.auto.modeling_auto import ( + MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, + MODEL_FOR_BACKBONE_MAPPING_NAMES, + MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES, + MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, + MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES, + MODEL_FOR_MASKED_LM_MAPPING_NAMES, + MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, + MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES, + MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, + MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, + MODEL_MAPPING_NAMES, +) +from transformers.testing_utils import ( + CaptureLogger, + is_pt_flax_cross_test, + is_pt_tf_cross_test, + require_accelerate, + require_bitsandbytes, + require_flash_attn, + require_safetensors, + require_torch, + require_torch_gpu, + require_torch_multi_gpu, + require_torch_sdpa, + slow, + torch_device, +) +from transformers.utils import ( + CONFIG_NAME, + GENERATION_CONFIG_NAME, + SAFE_WEIGHTS_NAME, + is_accelerate_available, + is_flax_available, + is_tf_available, + is_torch_fx_available, + is_torch_sdpa_available, +) +from transformers.utils.generic import ContextManagers, ModelOutput + + +if is_accelerate_available(): + from accelerate.utils import compute_module_sizes + + +if is_torch_available(): + import torch + from safetensors.torch import load_file as safe_load_file + from safetensors.torch import save_file as safe_save_file + from torch import nn + + from transformers import MODEL_MAPPING, AdaptiveEmbedding + from transformers.modeling_utils import no_init_weights + from transformers.pytorch_utils import id_tensor_storage + + +if is_tf_available(): + import tensorflow as tf + +if is_flax_available(): + import jax.numpy as jnp + + from tests.test_modeling_flax_utils import check_models_equal + from transformers.modeling_flax_pytorch_utils import ( + convert_pytorch_state_dict_to_flax, + load_flax_weights_in_pytorch_model, + ) + +if is_torch_fx_available(): + from transformers.utils.fx import symbolic_trace + + +def _config_zero_init(config): + configs_no_init = copy.deepcopy(config) + for key in configs_no_init.__dict__.keys(): + if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: + setattr(configs_no_init, key, 1e-10) + if isinstance(getattr(configs_no_init, key, None), PretrainedConfig): + no_init_subconfig = _config_zero_init(getattr(configs_no_init, key)) + setattr(configs_no_init, key, no_init_subconfig) + return configs_no_init + + +def _mock_init_weights(self, module): + for name, param in module.named_parameters(recurse=False): + # Use the first letter of the name to get a value and go from a <> -13 to z <> 12 + value = ord(name[0].lower()) - 110 + param.data.fill_(value) + + +def _mock_all_init_weights(self): + # Prune heads if needed + if self.config.pruned_heads: + self.prune_heads(self.config.pruned_heads) + + import transformers.modeling_utils + + if transformers.modeling_utils._init_weights: + for module in self.modules(): + module._is_hf_initialized = False + # Initialize weights + self.apply(self._initialize_weights) + + # Tie weights should be skipped when not initializing all weights + # since from_pretrained(...) calls tie weights anyways + self.tie_weights() + + +@require_torch +class ModelTesterMixin: + model_tester = None + all_model_classes = () + all_generative_model_classes = () + fx_compatible = False + test_torchscript = True + test_pruning = True + test_resize_embeddings = True + test_resize_position_embeddings = False + test_head_masking = True + test_mismatched_shapes = True + test_missing_keys = True + test_model_parallel = False + is_encoder_decoder = False + has_attentions = True + model_split_percents = [0.5, 0.7, 0.9] + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = copy.deepcopy(inputs_dict) + if model_class.__name__ in get_values(MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES): + inputs_dict = { + k: v.unsqueeze(1).expand(-1, self.model_tester.num_choices, -1).contiguous() + if isinstance(v, torch.Tensor) and v.ndim > 1 + else v + for k, v in inputs_dict.items() + } + elif model_class.__name__ in get_values(MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES): + inputs_dict.pop("attention_mask") + + if return_labels: + if model_class.__name__ in get_values(MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES): + inputs_dict["labels"] = torch.ones(self.model_tester.batch_size, dtype=torch.long, device=torch_device) + elif model_class.__name__ in [ + *get_values(MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES), + *get_values(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES), + ]: + inputs_dict["start_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + inputs_dict["end_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + elif model_class.__name__ in [ + *get_values(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES), + *get_values(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES), + ]: + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + elif model_class.__name__ in [ + *get_values(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_CAUSAL_LM_MAPPING_NAMES), + *get_values(MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES), + *get_values(MODEL_FOR_MASKED_LM_MAPPING_NAMES), + *get_values(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES), + ]: + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + elif model_class.__name__ in get_values(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES): + num_patches = self.model_tester.image_size // self.model_tester.patch_size + inputs_dict["bool_masked_pos"] = torch.zeros( + (self.model_tester.batch_size, num_patches**2), dtype=torch.long, device=torch_device + ) + elif model_class.__name__ in get_values(MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES): + batch_size, num_channels, height, width = inputs_dict["pixel_values"].shape + inputs_dict["labels"] = torch.zeros( + [self.model_tester.batch_size, height, width], device=torch_device + ).long() + + return inputs_dict + + def test_save_load(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_save_load(out1, out2): + # make sure we don't have nans + out_2 = out2.cpu().numpy() + out_2[np.isnan(out_2)] = 0 + + out_1 = out1.cpu().numpy() + out_1[np.isnan(out_1)] = 0 + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + first = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + # the config file (and the generation config file, if it can generate) should be saved + self.assertTrue(os.path.exists(os.path.join(tmpdirname, CONFIG_NAME))) + self.assertEqual( + model.can_generate(), os.path.exists(os.path.join(tmpdirname, GENERATION_CONFIG_NAME)) + ) + + model = model_class.from_pretrained(tmpdirname) + model.to(torch_device) + with torch.no_grad(): + second = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + if isinstance(first, tuple) and isinstance(second, tuple): + for tensor1, tensor2 in zip(first, second): + check_save_load(tensor1, tensor2) + else: + check_save_load(first, second) + + def test_from_pretrained_no_checkpoint(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model = model_class(config) + state_dict = model.state_dict() + + new_model = model_class.from_pretrained( + pretrained_model_name_or_path=None, config=config, state_dict=state_dict + ) + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + def test_keep_in_fp32_modules(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + if model_class._keep_in_fp32_modules is None: + return + + model = model_class(config) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16) + + for name, param in model.named_parameters(): + if any(n in model_class._keep_in_fp32_modules for n in name.split(".")): + self.assertTrue(param.dtype == torch.float32) + else: + self.assertTrue(param.dtype == torch.float16, name) + + def test_save_load_keys_to_ignore_on_save(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + _keys_to_ignore_on_save = getattr(model, "_keys_to_ignore_on_save", None) + if _keys_to_ignore_on_save is None: + continue + + # check the keys are in the original state_dict + for k in _keys_to_ignore_on_save: + self.assertIn(k, model.state_dict().keys(), "\n".join(model.state_dict().keys())) + + # check that certain keys didn't get saved with the model + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + output_model_file = os.path.join(tmpdirname, SAFE_WEIGHTS_NAME) + state_dict_saved = safe_load_file(output_model_file) + + for k in _keys_to_ignore_on_save: + self.assertNotIn(k, state_dict_saved.keys(), "\n".join(state_dict_saved.keys())) + + # Test we can load the state dict in the model, necessary for the checkpointing API in Trainer. + load_result = model.load_state_dict(state_dict_saved, strict=False) + keys_to_ignore = set(model._keys_to_ignore_on_save) + + if hasattr(model, "_tied_weights_keys"): + keys_to_ignore.update(set(model._tied_weights_keys)) + + self.assertTrue(len(load_result.missing_keys) == 0 or set(load_result.missing_keys) == keys_to_ignore) + self.assertTrue(len(load_result.unexpected_keys) == 0) + + def test_gradient_checkpointing_backward_compatibility(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if not model_class.supports_gradient_checkpointing: + continue + + config.gradient_checkpointing = True + model = model_class(config) + self.assertTrue(model.is_gradient_checkpointing) + + def test_gradient_checkpointing_enable_disable(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if not model_class.supports_gradient_checkpointing: + continue + + # at init model should have gradient checkpointing disabled + model = model_class(config) + self.assertFalse(model.is_gradient_checkpointing) + + # check enable works + model.gradient_checkpointing_enable() + self.assertTrue(model.is_gradient_checkpointing) + + # Loop over all modules and check that relevant modules have gradient_checkpointing set to True + for n, m in model.named_modules(): + if hasattr(m, "gradient_checkpointing"): + self.assertTrue( + m.gradient_checkpointing, f"Module {n} does not have gradient_checkpointing set to True" + ) + + # check disable works + model.gradient_checkpointing_disable() + self.assertFalse(model.is_gradient_checkpointing) + + # Loop over all modules and check that relevant modules have gradient_checkpointing set to False + for n, m in model.named_modules(): + if hasattr(m, "gradient_checkpointing"): + self.assertFalse( + m.gradient_checkpointing, f"Module {n} does not have gradient_checkpointing set to False" + ) + + def test_save_load_fast_init_from_base(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if config.__class__ not in MODEL_MAPPING: + return + base_class = MODEL_MAPPING[config.__class__] + + if isinstance(base_class, tuple): + base_class = base_class[0] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + # make a copy of model class to not break future tests + # from https://stackoverflow.com/questions/9541025/how-to-copy-a-python-class + class CopyClass(model_class): + pass + + model_class_copy = CopyClass + + # make sure that all keys are expected for test + model_class_copy._keys_to_ignore_on_load_missing = [] + + # make init deterministic, but make sure that + # non-initialized weights throw errors nevertheless + model_class_copy._init_weights = _mock_init_weights + model_class_copy.init_weights = _mock_all_init_weights + + model = base_class(config) + state_dict = model.state_dict() + + # this will often delete a single weight of a multi-weight module + # to test an edge case + random_key_to_del = random.choice(list(state_dict.keys())) + del state_dict[random_key_to_del] + + # check that certain keys didn't get saved with the model + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + torch.save(state_dict, os.path.join(tmpdirname, "pytorch_model.bin")) + + model_fast_init = model_class_copy.from_pretrained(tmpdirname) + model_slow_init = model_class_copy.from_pretrained(tmpdirname, _fast_init=False) + # Before we test anything + + for key in model_fast_init.state_dict().keys(): + if isinstance(model_slow_init.state_dict()[key], torch.BoolTensor): + max_diff = (model_slow_init.state_dict()[key] ^ model_fast_init.state_dict()[key]).sum().item() + else: + max_diff = (model_slow_init.state_dict()[key] - model_fast_init.state_dict()[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + def test_fast_init_context_manager(self): + # 1. Create a dummy class. Should have buffers as well? To make sure we test __init__ + class MyClass(PreTrainedModel): + config_class = PretrainedConfig + + def __init__(self, config=None): + super().__init__(config if config is not None else PretrainedConfig()) + self.linear = nn.Linear(10, 10, bias=True) + self.embedding = nn.Embedding(10, 10) + self.std = 1 + + def _init_weights(self, module): + if isinstance(module, nn.Linear): + module.weight.data = nn.init.kaiming_uniform_(module.weight.data, np.sqrt(5)) + if module.bias is not None: + module.bias.data.normal_(mean=0.0, std=self.std) + + # 2. Make sure a linear layer's reset params is properly skipped: + with ContextManagers([no_init_weights(True)]): + no_init_instance = MyClass() + + set_seed(0) + expected_bias = torch.tensor( + ([0.2975, 0.2131, -0.1379, -0.0796, -0.3012, -0.0057, -0.2381, -0.2439, -0.0174, 0.0475]) + ) + init_instance = MyClass() + torch.testing.assert_allclose(init_instance.linear.bias, expected_bias, rtol=1e-3, atol=1e-4) + + set_seed(0) + torch.testing.assert_allclose( + init_instance.linear.weight, nn.init.kaiming_uniform_(no_init_instance.linear.weight, np.sqrt(5)) + ) + + # 3. Make sure weights that are not present use init_weight_ and get expected values + with tempfile.TemporaryDirectory() as tmpdirname: + state_dict = init_instance.state_dict() + del state_dict["linear.weight"] + + init_instance.config.save_pretrained(tmpdirname) + torch.save(state_dict, os.path.join(tmpdirname, "pytorch_model.bin")) + set_seed(0) + model_fast_init = MyClass.from_pretrained(tmpdirname) + + set_seed(0) + model_slow_init = MyClass.from_pretrained(tmpdirname, _fast_init=False) + + for key in model_fast_init.state_dict().keys(): + max_diff = torch.max(torch.abs(model_slow_init.state_dict()[key] - model_fast_init.state_dict()[key])) + self.assertLessEqual(max_diff.item(), 1e-3, msg=f"{key} not identical") + + def test_save_load_fast_init_to_base(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if config.__class__ not in MODEL_MAPPING: + return + base_class = MODEL_MAPPING[config.__class__] + + if isinstance(base_class, tuple): + base_class = base_class[0] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + # make a copy of model class to not break future tests + # from https://stackoverflow.com/questions/9541025/how-to-copy-a-python-class + class CopyClass(base_class): + pass + + base_class_copy = CopyClass + + # make sure that all keys are expected for test + base_class_copy._keys_to_ignore_on_load_missing = [] + + # make init deterministic, but make sure that + # non-initialized weights throw errors nevertheless + base_class_copy._init_weights = _mock_init_weights + base_class_copy.init_weights = _mock_all_init_weights + + model = model_class(config) + state_dict = model.state_dict() + + # this will often delete a single weight of a multi-weight module + # to test an edge case + random_key_to_del = random.choice(list(state_dict.keys())) + del state_dict[random_key_to_del] + + # check that certain keys didn't get saved with the model + with tempfile.TemporaryDirectory() as tmpdirname: + model.config.save_pretrained(tmpdirname) + torch.save(state_dict, os.path.join(tmpdirname, "pytorch_model.bin")) + + model_fast_init = base_class_copy.from_pretrained(tmpdirname) + model_slow_init = base_class_copy.from_pretrained(tmpdirname, _fast_init=False) + + for key in model_fast_init.state_dict().keys(): + if isinstance(model_slow_init.state_dict()[key], torch.BoolTensor): + max_diff = torch.max( + model_slow_init.state_dict()[key] ^ model_fast_init.state_dict()[key] + ).item() + else: + max_diff = torch.max( + torch.abs(model_slow_init.state_dict()[key] - model_fast_init.state_dict()[key]) + ).item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + for name, param in model.named_parameters(): + if param.requires_grad: + self.assertIn( + ((param.data.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def test_determinism(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_determinism(first, second): + out_1 = first.cpu().numpy() + out_2 = second.cpu().numpy() + out_1 = out_1[~np.isnan(out_1)] + out_2 = out_2[~np.isnan(out_2)] + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + first = model(**self._prepare_for_class(inputs_dict, model_class))[0] + second = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + if isinstance(first, tuple) and isinstance(second, tuple): + for tensor1, tensor2 in zip(first, second): + check_determinism(tensor1, tensor2) + else: + check_determinism(first, second) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + if model.config.is_encoder_decoder: + expected_arg_names = [ + "input_ids", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + ] + expected_arg_names.extend( + ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"] + if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + elif model_class.__name__ in [*get_values(MODEL_FOR_BACKBONE_MAPPING_NAMES)] and self.has_attentions: + expected_arg_names = ["pixel_values", "output_hidden_states", "output_attentions", "return_dict"] + self.assertListEqual(arg_names, expected_arg_names) + elif model_class.__name__ in [*get_values(MODEL_FOR_BACKBONE_MAPPING_NAMES)] and not self.has_attentions: + expected_arg_names = ["pixel_values", "output_hidden_states", "return_dict"] + self.assertListEqual(arg_names, expected_arg_names) + else: + expected_arg_names = [model.main_input_name] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def check_training_gradient_checkpointing(self, gradient_checkpointing_kwargs=None): + if not self.model_tester.is_training: + return + + for model_class in self.all_model_classes: + if ( + model_class.__name__ + in [*get_values(MODEL_MAPPING_NAMES), *get_values(MODEL_FOR_BACKBONE_MAPPING_NAMES)] + or not model_class.supports_gradient_checkpointing + ): + continue + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.use_cache = False + config.return_dict = True + model = model_class(config) + + model.to(torch_device) + model.gradient_checkpointing_enable(gradient_checkpointing_kwargs=gradient_checkpointing_kwargs) + model.train() + + # unfreeze additional layers + for p in model.parameters(): + p.requires_grad_(True) + + optimizer = torch.optim.SGD(model.parameters(), lr=0.01) + + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + loss = model(**inputs).loss + loss.backward() + optimizer.step() + + for k, v in model.named_parameters(): + if v.requires_grad: + self.assertTrue(v.grad is not None, f"{k} in {model_class.__name__} has no gradient!") + + def test_training(self): + if not self.model_tester.is_training: + return + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + if model_class.__name__ in [ + *get_values(MODEL_MAPPING_NAMES), + *get_values(MODEL_FOR_BACKBONE_MAPPING_NAMES), + ]: + continue + + model = model_class(config) + model.to(torch_device) + model.train() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + loss = model(**inputs).loss + loss.backward() + + def test_training_gradient_checkpointing(self): + # Scenario - 1 default behaviour + self.check_training_gradient_checkpointing() + + def test_training_gradient_checkpointing_use_reentrant(self): + # Scenario - 2 with `use_reentrant=True` - this is the default value that is used in pytorch's + # torch.utils.checkpoint.checkpoint + self.check_training_gradient_checkpointing(gradient_checkpointing_kwargs={"use_reentrant": True}) + + def test_training_gradient_checkpointing_use_reentrant_false(self): + # Scenario - 3 with `use_reentrant=False` pytorch suggests users to use this value for + # future releases: https://pytorch.org/docs/stable/checkpoint.html + self.check_training_gradient_checkpointing(gradient_checkpointing_kwargs={"use_reentrant": False}) + + def test_attention_outputs(self): + if not self.has_attentions: + self.skipTest(reason="Model does not output attentions") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + chunk_length = getattr(self.model_tester, "chunk_length", None) + if chunk_length is not None and hasattr(self.model_tester, "num_hashes"): + encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + if chunk_length is not None: + self.assertListEqual( + list(attentions[0].shape[-4:]), + [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length], + ) + else: + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + out_len = len(outputs) + + if self.is_encoder_decoder: + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + # Question Answering model returns start_logits and end_logits + if model_class.__name__ in [ + *get_values(MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES), + *get_values(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES), + ]: + correct_outlen += 1 # start_logits and end_logits instead of only 1 output + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + elif self.is_encoder_decoder: + added_hidden_states = 2 + else: + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + if chunk_length is not None: + self.assertListEqual( + list(self_attentions[0].shape[-4:]), + [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length], + ) + else: + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + @slow + def test_torchscript_simple(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + self._create_and_check_torchscript(config, inputs_dict) + + @slow + def test_torchscript_output_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_attentions = True + self._create_and_check_torchscript(config, inputs_dict) + + @slow + def test_torchscript_output_hidden_state(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + self._create_and_check_torchscript(config, inputs_dict) + + # This is copied from `torch/testing/_internal/jit_utils.py::clear_class_registry` + def clear_torch_jit_class_registry(self): + torch._C._jit_clear_class_registry() + torch.jit._recursive.concrete_type_store = torch.jit._recursive.ConcreteTypeStore() + # torch 1.8 has no `_clear_class_state` in `torch.jit._state` + if hasattr(torch.jit._state, "_clear_class_state"): + torch.jit._state._clear_class_state() + + def _create_and_check_torchscript(self, config, inputs_dict): + if not self.test_torchscript: + return + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.torchscript = True + for model_class in self.all_model_classes: + for attn_implementation in ["eager", "sdpa"]: + if attn_implementation == "sdpa" and (not model_class._supports_sdpa or not is_torch_sdpa_available()): + continue + + configs_no_init._attn_implementation = attn_implementation + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class) + + main_input_name = model_class.main_input_name + + try: + if model.config.is_encoder_decoder: + model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward + main_input = inputs[main_input_name] + attention_mask = inputs["attention_mask"] + decoder_input_ids = inputs["decoder_input_ids"] + decoder_attention_mask = inputs["decoder_attention_mask"] + model(main_input, attention_mask, decoder_input_ids, decoder_attention_mask) + traced_model = torch.jit.trace( + model, (main_input, attention_mask, decoder_input_ids, decoder_attention_mask) + ) + elif "bbox" in inputs and "image" in inputs: # LayoutLMv2 requires additional inputs + input_ids = inputs["input_ids"] + bbox = inputs["bbox"] + image = inputs["image"].tensor + model(input_ids, bbox, image) + traced_model = torch.jit.trace( + model, (input_ids, bbox, image), check_trace=False + ) # when traced model is checked, an error is produced due to name mangling + elif "bbox" in inputs: # Bros requires additional inputs (bbox) + input_ids = inputs["input_ids"] + bbox = inputs["bbox"] + model(input_ids, bbox) + traced_model = torch.jit.trace( + model, (input_ids, bbox), check_trace=False + ) # when traced model is checked, an error is produced due to name mangling + else: + main_input = inputs[main_input_name] + + if model.config._attn_implementation == "sdpa": + trace_input = {main_input_name: main_input} + + if "attention_mask" in inputs: + trace_input["attention_mask"] = inputs["attention_mask"] + else: + self.skipTest("testing SDPA without attention_mask is not supported") + + model(main_input, attention_mask=inputs["attention_mask"]) + # example_kwarg_inputs was introduced in torch==2.0, but it is fine here since SDPA has a requirement on torch>=2.1. + traced_model = torch.jit.trace(model, example_kwarg_inputs=trace_input) + else: + model(main_input) + traced_model = torch.jit.trace(model, (main_input,)) + except RuntimeError: + self.fail("Couldn't trace module.") + + with tempfile.TemporaryDirectory() as tmp_dir_name: + pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt") + + try: + torch.jit.save(traced_model, pt_file_name) + except Exception: + self.fail("Couldn't save module.") + + try: + loaded_model = torch.jit.load(pt_file_name) + except Exception: + self.fail("Couldn't load module.") + + model.to(torch_device) + model.eval() + + loaded_model.to(torch_device) + loaded_model.eval() + + model_state_dict = model.state_dict() + loaded_model_state_dict = loaded_model.state_dict() + + non_persistent_buffers = {} + for key in loaded_model_state_dict.keys(): + if key not in model_state_dict.keys(): + non_persistent_buffers[key] = loaded_model_state_dict[key] + + loaded_model_state_dict = { + key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers + } + + self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys())) + + model_buffers = list(model.buffers()) + for non_persistent_buffer in non_persistent_buffers.values(): + found_buffer = False + for i, model_buffer in enumerate(model_buffers): + if torch.equal(non_persistent_buffer, model_buffer): + found_buffer = True + break + + self.assertTrue(found_buffer) + model_buffers.pop(i) + + models_equal = True + for layer_name, p1 in model_state_dict.items(): + if layer_name in loaded_model_state_dict: + p2 = loaded_model_state_dict[layer_name] + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + # Avoid memory leak. Without this, each call increase RAM usage by ~20MB. + # (Even with this call, there are still memory leak by ~0.04MB) + self.clear_torch_jit_class_registry() + + def test_torch_fx(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + self._create_and_check_torch_fx_tracing(config, inputs_dict) + + def test_torch_fx_output_loss(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + self._create_and_check_torch_fx_tracing(config, inputs_dict, output_loss=True) + + def _create_and_check_torch_fx_tracing(self, config, inputs_dict, output_loss=False): + if not is_torch_fx_available() or not self.fx_compatible: + return + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.return_dict = False + + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=output_loss) + + try: + if model.config.is_encoder_decoder: + model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward + labels = inputs.get("labels", None) + input_names = [ + "attention_mask", + "decoder_attention_mask", + "decoder_input_ids", + "input_features", + "input_ids", + "input_values", + ] + if labels is not None: + input_names.append("labels") + + filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names} + input_names = list(filtered_inputs.keys()) + + model_output = model(**filtered_inputs) + + traced_model = symbolic_trace(model, input_names) + traced_output = traced_model(**filtered_inputs) + else: + input_names = [ + "attention_mask", + "bbox", + "input_features", + "input_ids", + "input_values", + "pixel_values", + "token_type_ids", + "visual_feats", + "visual_pos", + ] + + labels = inputs.get("labels", None) + start_positions = inputs.get("start_positions", None) + end_positions = inputs.get("end_positions", None) + if labels is not None: + input_names.append("labels") + if start_positions is not None: + input_names.append("start_positions") + if end_positions is not None: + input_names.append("end_positions") + + filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names} + input_names = list(filtered_inputs.keys()) + + if model.__class__.__name__ in set(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values()) and ( + not hasattr(model.config, "problem_type") or model.config.problem_type is None + ): + model.config.problem_type = "single_label_classification" + + traced_model = symbolic_trace(model, input_names) + traced_output = traced_model(**filtered_inputs) + model_output = model(**filtered_inputs) + + except Exception as e: + self.fail(f"Couldn't trace module: {e}") + + def flatten_output(output): + flatten = [] + for x in output: + if isinstance(x, (tuple, list)): + flatten += flatten_output(x) + elif not isinstance(x, torch.Tensor): + continue + else: + flatten.append(x) + return flatten + + model_output = flatten_output(model_output) + traced_output = flatten_output(traced_output) + num_outputs = len(model_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], traced_output[i]), + f"traced {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Test that the model can be serialized and restored properly + with tempfile.TemporaryDirectory() as tmp_dir_name: + pkl_file_name = os.path.join(tmp_dir_name, "model.pkl") + try: + with open(pkl_file_name, "wb") as f: + pickle.dump(traced_model, f) + with open(pkl_file_name, "rb") as f: + loaded = pickle.load(f) + except Exception as e: + self.fail(f"Couldn't serialize / deserialize the traced model: {e}") + + loaded_output = loaded(**filtered_inputs) + loaded_output = flatten_output(loaded_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], loaded_output[i]), + f"serialized model {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Avoid memory leak. Without this, each call increase RAM usage by ~20MB. + # (Even with this call, there are still memory leak by ~0.04MB) + self.clear_torch_jit_class_registry() + + def test_headmasking(self): + if not self.test_head_masking: + return + + global_rng.seed(42) + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + global_rng.seed() + + inputs_dict["output_attentions"] = True + config.output_hidden_states = True + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + + # Prepare head_mask + # Set require_grad after having prepared the tensor to avoid error (leaf variable has been moved into the graph interior) + head_mask = torch.ones( + self.model_tester.num_hidden_layers, + self.model_tester.num_attention_heads, + device=torch_device, + ) + head_mask[0, 0] = 0 + head_mask[-1, :-1] = 0 + head_mask.requires_grad_(requires_grad=True) + inputs = self._prepare_for_class(inputs_dict, model_class).copy() + inputs["head_mask"] = head_mask + if model.config.is_encoder_decoder: + signature = inspect.signature(model.forward) + arg_names = [*signature.parameters.keys()] + if "decoder_head_mask" in arg_names: # necessary diferentiation because of T5 model + inputs["decoder_head_mask"] = head_mask + if "cross_attn_head_mask" in arg_names: + inputs["cross_attn_head_mask"] = head_mask + outputs = model(**inputs, return_dict=True) + + # Test that we can get a gradient back for importance score computation + output = sum(t.sum() for t in outputs[0]) + output = output.sum() + output.backward() + multihead_outputs = head_mask.grad + + self.assertIsNotNone(multihead_outputs) + self.assertEqual(len(multihead_outputs), self.model_tester.num_hidden_layers) + + def check_attentions_validity(attentions): + # Remove Nan + for t in attentions: + self.assertLess( + torch.sum(torch.isnan(t)), t.numel() / 4 + ) # Check we don't have more than 25% nans (arbitrary) + attentions = [ + t.masked_fill(torch.isnan(t), 0.0) for t in attentions + ] # remove them (the test is less complete) + + self.assertAlmostEqual(attentions[0][..., 0, :, :].flatten().sum().item(), 0.0) + self.assertNotEqual(attentions[0][..., -1, :, :].flatten().sum().item(), 0.0) + if len(attentions) > 2: # encoder-decoder models have only 2 layers in each module + self.assertNotEqual(attentions[1][..., 0, :, :].flatten().sum().item(), 0.0) + self.assertAlmostEqual(attentions[-1][..., -2, :, :].flatten().sum().item(), 0.0) + self.assertNotEqual(attentions[-1][..., -1, :, :].flatten().sum().item(), 0.0) + + if model.config.is_encoder_decoder: + check_attentions_validity(outputs.encoder_attentions) + check_attentions_validity(outputs.decoder_attentions) + check_attentions_validity(outputs.cross_attentions) + else: + check_attentions_validity(outputs.attentions) + + def test_head_pruning(self): + if not self.test_pruning: + return + + for model_class in self.all_model_classes: + ( + config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + model = model_class(config=config) + model.to(torch_device) + model.eval() + heads_to_prune = { + 0: list(range(1, self.model_tester.num_attention_heads)), + -1: [0], + } + model.prune_heads(heads_to_prune) + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], 1) + # TODO: To have this check, we will need at least 3 layers. Do we really need it? + # self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads) + self.assertEqual(attentions[-1].shape[-3], self.model_tester.num_attention_heads - 1) + + def test_head_pruning_save_load_from_pretrained(self): + if not self.test_pruning: + return + + for model_class in self.all_model_classes: + ( + config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + model = model_class(config=config) + model.to(torch_device) + model.eval() + heads_to_prune = { + 0: list(range(1, self.model_tester.num_attention_heads)), + -1: [0], + } + model.prune_heads(heads_to_prune) + + with tempfile.TemporaryDirectory() as temp_dir_name: + model.save_pretrained(temp_dir_name) + model = model_class.from_pretrained(temp_dir_name) + model.to(torch_device) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + self.assertEqual(attentions[0].shape[-3], 1) + # TODO: To have this check, we will need at least 3 layers. Do we really need it? + # self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads) + self.assertEqual(attentions[-1].shape[-3], self.model_tester.num_attention_heads - 1) + + def test_head_pruning_save_load_from_config_init(self): + if not self.test_pruning: + return + + for model_class in self.all_model_classes: + ( + config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + + heads_to_prune = { + 0: list(range(1, self.model_tester.num_attention_heads)), + -1: [0], + } + config.pruned_heads = heads_to_prune + + model = model_class(config=config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], 1) + # TODO: To have this check, we will need at least 3 layers. Do we really need it? + # self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads) + self.assertEqual(attentions[-1].shape[-3], self.model_tester.num_attention_heads - 1) + + def test_head_pruning_integration(self): + if not self.test_pruning: + return + + for model_class in self.all_model_classes: + ( + config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + + heads_to_prune = {1: [1, 2]} + config.pruned_heads = heads_to_prune + + model = model_class(config=config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], self.model_tester.num_attention_heads - 0) + self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads - 2) + + with tempfile.TemporaryDirectory() as temp_dir_name: + model.save_pretrained(temp_dir_name) + model = model_class.from_pretrained(temp_dir_name) + model.to(torch_device) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], self.model_tester.num_attention_heads - 0) + self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads - 2) + + heads_to_prune = {0: [0], 1: [1, 2]} + model.prune_heads(heads_to_prune) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], self.model_tester.num_attention_heads - 1) + self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads - 2) + + self.assertDictEqual(model.config.pruned_heads, {0: [0], 1: [1, 2]}) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + if hasattr(self.model_tester, "chunk_length") and self.model_tester.chunk_length > 1: + seq_length = seq_length * self.model_tester.chunk_length + else: + seq_length = self.model_tester.seq_length + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class(config) + model.to(torch_device) + + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs = model(**inputs) + + output = outputs[0] + + if config.is_encoder_decoder: + # Seq2Seq models + encoder_hidden_states = outputs.encoder_hidden_states[0] + encoder_hidden_states.retain_grad() + + decoder_hidden_states = outputs.decoder_hidden_states[0] + decoder_hidden_states.retain_grad() + + if self.has_attentions: + encoder_attentions = outputs.encoder_attentions[0] + encoder_attentions.retain_grad() + + decoder_attentions = outputs.decoder_attentions[0] + decoder_attentions.retain_grad() + + cross_attentions = outputs.cross_attentions[0] + cross_attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(encoder_hidden_states.grad) + self.assertIsNotNone(decoder_hidden_states.grad) + + if self.has_attentions: + self.assertIsNotNone(encoder_attentions.grad) + self.assertIsNotNone(decoder_attentions.grad) + self.assertIsNotNone(cross_attentions.grad) + else: + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + hidden_states.retain_grad() + + if self.has_attentions: + attentions = outputs.attentions[0] + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + + if self.has_attentions: + self.assertIsNotNone(attentions.grad) + + def test_feed_forward_chunking(self): + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + torch.manual_seed(0) + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + model.eval() + + hidden_states_no_chunk = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + torch.manual_seed(0) + config.chunk_size_feed_forward = 1 + model = model_class(config) + model.to(torch_device) + model.eval() + + hidden_states_with_chunk = model(**self._prepare_for_class(inputs_dict, model_class))[0] + self.assertTrue(torch.allclose(hidden_states_no_chunk, hidden_states_with_chunk, atol=1e-3)) + + def test_resize_position_vector_embeddings(self): + if not self.test_resize_position_embeddings: + return + + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + + if self.model_tester.is_training is False: + model.eval() + + max_position_embeddings = config.max_position_embeddings + + # Retrieve the embeddings and clone theme + if model.config.is_encoder_decoder: + encoder_model_embed, decoder_model_embed = model.get_position_embeddings() + encoder_cloned_embeddings = encoder_model_embed.weight.clone() + decoder_cloned_embeddings = decoder_model_embed.weight.clone() + else: + model_embed = model.get_position_embeddings() + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the position embeddings with a larger max_position_embeddings increases + # the model's postion embeddings size + model.resize_position_embeddings(max_position_embeddings + 10) + self.assertEqual(model.config.max_position_embeddings, max_position_embeddings + 10) + + # Check that it actually resizes the embeddings matrix + if model.config.is_encoder_decoder: + encoder_model_embed, decoder_model_embed = model.get_position_embeddings() + self.assertEqual(encoder_model_embed.weight.shape[0], encoder_cloned_embeddings.shape[0] + 10) + self.assertEqual(decoder_model_embed.weight.shape[0], decoder_cloned_embeddings.shape[0] + 10) + else: + model_embed = model.get_position_embeddings() + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the position embeddings with a smaller max_position_embeddings decreases + # the model's max_position_embeddings + model.resize_position_embeddings(max_position_embeddings - 5) + self.assertEqual(model.config.max_position_embeddings, max_position_embeddings - 5) + + # Check that it actually resizes the embeddings matrix + if model.config.is_encoder_decoder: + encoder_model_embed, decoder_model_embed = model.get_position_embeddings() + self.assertEqual(encoder_model_embed.weight.shape[0], encoder_cloned_embeddings.shape[0] - 5) + self.assertEqual(decoder_model_embed.weight.shape[0], decoder_cloned_embeddings.shape[0] - 5) + else: + model_embed = model.get_position_embeddings() + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 5) + + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that adding and removing tokens has not modified the first part of the embedding matrix. + models_equal = True + + if model.config.is_encoder_decoder: + for p1, p2 in zip(encoder_cloned_embeddings, encoder_model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + for p1, p2 in zip(decoder_cloned_embeddings, decoder_model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + else: + for p1, p2 in zip(cloned_embeddings, model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + def test_resize_tokens_embeddings(self): + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + return + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + + if self.model_tester.is_training is False: + model.eval() + + model_vocab_size = config.vocab_size + # Retrieve the embeddings and clone theme + model_embed = model.resize_token_embeddings(model_vocab_size) + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.vocab_size, model_vocab_size + 10) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15) + + # Check that the model can still do a forward pass successfully (every parameter should be resized) + # Input ids should be clamped to the maximum size of the vocabulary + inputs_dict["input_ids"].clamp_(max=model_vocab_size - 15 - 1) + + # make sure that decoder_input_ids are resized as well + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that adding and removing tokens has not modified the first part of the embedding matrix. + models_equal = True + for p1, p2 in zip(cloned_embeddings, model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + + model_vocab_size = config.vocab_size + model.resize_token_embeddings(model_vocab_size + 10, pad_to_multiple_of=1) + self.assertTrue(model.config.vocab_size + 10, model_vocab_size) + + model_embed = model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=64) + self.assertTrue(model_embed.weight.shape[0] // 64, 0) + + self.assertTrue(model_embed.weight.shape[0], model.config.vocab_size) + self.assertTrue(model.config.vocab_size, model.vocab_size) + + model_embed = model.resize_token_embeddings(model_vocab_size + 13, pad_to_multiple_of=64) + self.assertTrue(model_embed.weight.shape[0] // 64, 0) + + # Check that resizing a model to a multiple of pad_to_multiple leads to a model of exactly that size + target_dimension = 128 + model_embed = model.resize_token_embeddings(target_dimension, pad_to_multiple_of=64) + self.assertTrue(model_embed.weight.shape[0], target_dimension) + + with self.assertRaisesRegex( + ValueError, + "Asking to pad the embedding matrix to a multiple of `1.3`, which is not and integer. Please make sure to pass an integer", + ): + model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=1.3) + + def test_resize_embeddings_untied(self): + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + return + + original_config.tie_word_embeddings = False + + # if model cannot untied embeddings -> leave test + if original_config.tie_word_embeddings: + return + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config).to(torch_device) + + # if no output embeddings -> leave test + if model.get_output_embeddings() is None: + continue + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_vocab_size = config.vocab_size + model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.vocab_size, model_vocab_size + 10) + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size + 10) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size - 15) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size - 15) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + # Input ids should be clamped to the maximum size of the vocabulary + inputs_dict["input_ids"].clamp_(max=model_vocab_size - 15 - 1) + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + def test_model_common_attributes(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Embedding, AdaptiveEmbedding)) + model.set_input_embeddings(nn.Embedding(10, 10)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model_main_input_name(self): + for model_class in self.all_model_classes: + model_signature = inspect.signature(getattr(model_class, "forward")) + # The main input is the name of the argument after `self` + observed_main_input_name = list(model_signature.parameters.keys())[1] + self.assertEqual(model_class.main_input_name, observed_main_input_name) + + def test_correct_missing_keys(self): + if not self.test_missing_keys: + return + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + base_model_prefix = model.base_model_prefix + + if hasattr(model, base_model_prefix): + extra_params = {k: v for k, v in model.named_parameters() if not k.startswith(base_model_prefix)} + extra_params.update({k: v for k, v in model.named_buffers() if not k.startswith(base_model_prefix)}) + # Some models define this as None + if model._keys_to_ignore_on_load_missing: + for key in model._keys_to_ignore_on_load_missing: + extra_params.pop(key, None) + + if not extra_params: + # In that case, we *are* on a head model, but every + # single key is not actual parameters and this is + # tested in `test_tied_model_weights_key_ignore` test. + continue + + with tempfile.TemporaryDirectory() as temp_dir_name: + model.base_model.save_pretrained(temp_dir_name) + model, loading_info = model_class.from_pretrained(temp_dir_name, output_loading_info=True) + self.assertGreater(len(loading_info["missing_keys"]), 0, model.__class__.__name__) + + def test_tie_model_weights(self): + if not self.test_torchscript: + return + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_same_values(layer_1, layer_2): + equal = True + for p1, p2 in zip(layer_1.weight, layer_2.weight): + if p1.data.ne(p2.data).sum() > 0: + equal = False + return equal + + for model_class in self.all_model_classes: + config.torchscript = True + model_not_tied = model_class(config) + if model_not_tied.get_output_embeddings() is None: + continue + + config_tied = copy.deepcopy(config) + config_tied.torchscript = False + model_tied = model_class(config_tied) + params_tied = list(model_tied.parameters()) + # Check that the embedding layer and decoding layer are the same in size and in value + # self.assertTrue(check_same_values(embeddings, decoding)) + + # # Check that after modification, they remain the same. + # embeddings.weight.data.div_(2) + # # Check that the embedding layer and decoding layer are the same in size and in value + # self.assertTrue(embeddings.weight.shape, decoding.weight.shape) + # self.assertTrue(check_same_values(embeddings, decoding)) + + # # Check that after modification, they remain the same. + # decoding.weight.data.div_(4) + # # Check that the embedding layer and decoding layer are the same in size and in value + # self.assertTrue(embeddings.weight.shape, decoding.weight.shape) + # self.assertTrue(check_same_values(embeddings, decoding)) + + # Check that after resize they remain tied. + model_tied.resize_token_embeddings(config.vocab_size + 10) + params_tied_2 = list(model_tied.parameters()) + self.assertEqual(len(params_tied_2), len(params_tied)) + + # decoding.weight.data.mul_(20) + # # Check that the embedding layer and decoding layer are the same in size and in value + # self.assertTrue(model.transformer.wte.weight.shape, model.lm_head.weight.shape) + # self.assertTrue(check_same_values(model.transformer.wte, model.lm_head)) + + @require_safetensors + def test_can_use_safetensors(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model_tied = model_class(config) + with tempfile.TemporaryDirectory() as d: + try: + model_tied.save_pretrained(d, safe_serialization=True) + except Exception as e: + raise Exception(f"Class {model_class.__name__} cannot be saved using safetensors: {e}") + + model_reloaded, infos = model_class.from_pretrained(d, output_loading_info=True) + # Checking the state dicts are correct + reloaded_state = model_reloaded.state_dict() + for k, v in model_tied.state_dict().items(): + self.assertIn(k, reloaded_state, f"Key {k} is missing from reloaded") + torch.testing.assert_close( + v, reloaded_state[k], msg=lambda x: f"{model_class.__name__}: Tensor {k}: {x}" + ) + # Checking there was no complain of missing weights + self.assertEqual(infos["missing_keys"], []) + + # Checking the tensor sharing are correct + ptrs = defaultdict(list) + for k, v in model_tied.state_dict().items(): + ptrs[v.data_ptr()].append(k) + + shared_ptrs = {k: v for k, v in ptrs.items() if len(v) > 1} + + for _, shared_names in shared_ptrs.items(): + reloaded_ptrs = {reloaded_state[k].data_ptr() for k in shared_names} + self.assertEqual( + len(reloaded_ptrs), + 1, + f"The shared pointers are incorrect, found different pointers for keys {shared_names}", + ) + + def test_load_save_without_tied_weights(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + config.tie_word_embeddings = False + for model_class in self.all_model_classes: + model = model_class(config) + with tempfile.TemporaryDirectory() as d: + model.save_pretrained(d) + + model_reloaded, infos = model_class.from_pretrained(d, output_loading_info=True) + # Checking the state dicts are correct + reloaded_state = model_reloaded.state_dict() + for k, v in model.state_dict().items(): + self.assertIn(k, reloaded_state, f"Key {k} is missing from reloaded") + torch.testing.assert_close( + v, reloaded_state[k], msg=lambda x: f"{model_class.__name__}: Tensor {k}: {x}" + ) + # Checking there was no complain of missing weights + self.assertEqual(infos["missing_keys"], []) + + def test_tied_weights_keys(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + config.tie_word_embeddings = True + for model_class in self.all_model_classes: + model_tied = model_class(config) + + ptrs = collections.defaultdict(list) + for name, tensor in model_tied.state_dict().items(): + ptrs[id_tensor_storage(tensor)].append(name) + + # These are all the pointers of shared tensors. + tied_params = [names for _, names in ptrs.items() if len(names) > 1] + + tied_weight_keys = model_tied._tied_weights_keys if model_tied._tied_weights_keys is not None else [] + # Detect we get a hit for each key + for key in tied_weight_keys: + if not any(re.search(key, p) for group in tied_params for p in group): + raise ValueError(f"{key} is not a tied weight key for {model_class}.") + + # Removed tied weights found from tied params -> there should only be one left after + for key in tied_weight_keys: + for i in range(len(tied_params)): + tied_params[i] = [p for p in tied_params[i] if re.search(key, p) is None] + + tied_params = [group for group in tied_params if len(group) > 1] + self.assertListEqual( + tied_params, + [], + f"Missing `_tied_weights_keys` for {model_class}: add all of {tied_params} except one.", + ) + + def test_model_weights_reload_no_missing_tied_weights(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model = model_class(config) + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + # We are nuking ALL weights on file, so every parameter should + # yell on load. We're going to detect if we yell too much, or too little. + placeholder_dict = {"tensor": torch.tensor([1, 2])} + safe_save_file(placeholder_dict, os.path.join(tmp_dir, "model.safetensors"), metadata={"format": "pt"}) + model_reloaded, infos = model_class.from_pretrained(tmp_dir, output_loading_info=True) + + prefix = f"{model_reloaded.base_model_prefix}." + params = dict(model_reloaded.named_parameters()) + params.update(dict(model_reloaded.named_buffers())) + param_names = {k[len(prefix) :] if k.startswith(prefix) else k for k in params.keys()} + + missing_keys = set(infos["missing_keys"]) + + extra_missing = missing_keys - param_names + # Remove tied weights from extra missing: they are normally not warned as missing if their tied + # counterpart is present but here there are no weights at all so we do get the warning. + ptrs = collections.defaultdict(list) + for name, tensor in model_reloaded.state_dict().items(): + ptrs[id_tensor_storage(tensor)].append(name) + tied_params = [names for _, names in ptrs.items() if len(names) > 1] + for group in tied_params: + group = {k[len(prefix) :] if k.startswith(prefix) else k for k in group} + # We remove the group from extra_missing if not all weights from group are in it + if len(group - extra_missing) > 0: + extra_missing = extra_missing - set(group) + + self.assertEqual( + extra_missing, + set(), + f"This model {model_class.__name__} might be missing some `keys_to_ignore`: {extra_missing}. " + f"For debugging, tied parameters are {tied_params}", + ) + + missed_missing = param_names - missing_keys + # Remove nonpersistent buffers from missed_missing + buffers = [n for n, _ in model_reloaded.named_buffers()] + nonpersistent_buffers = {n for n in buffers if n not in model_reloaded.state_dict()} + nonpersistent_buffers = { + k[len(prefix) :] if k.startswith(prefix) else k for k in nonpersistent_buffers + } + missed_missing = missed_missing - nonpersistent_buffers + + if model_reloaded._keys_to_ignore_on_load_missing is None: + expected_missing = set() + else: + expected_missing = set(model_reloaded._keys_to_ignore_on_load_missing) + self.assertEqual( + missed_missing, + expected_missing, + f"This model {model_class.__name__} ignores keys {missed_missing} but they look like real" + " parameters. If they are non persistent buffers make sure to instantiate them with" + " `persistent=False`", + ) + + def test_model_outputs_equivalence(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def set_nan_tensor_to_zero(t): + t[t != t] = 0 + return t + + def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): + with torch.no_grad(): + tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs) + dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple() + + def recursive_check(tuple_object, dict_object): + if isinstance(tuple_object, (List, Tuple)): + for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif isinstance(tuple_object, Dict): + for tuple_iterable_value, dict_iterable_value in zip( + tuple_object.values(), dict_object.values() + ): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif tuple_object is None: + return + else: + self.assertTrue( + torch.allclose( + set_nan_tensor_to_zero(tuple_object), set_nan_tensor_to_zero(dict_object), atol=1e-5 + ), + msg=( + "Tuple and dict output are not equal. Difference:" + f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:" + f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has" + f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}." + ), + ) + + recursive_check(tuple_output, dict_output) + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + if self.has_attentions: + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence( + model, tuple_inputs, dict_inputs, {"output_hidden_states": True, "output_attentions": True} + ) + + # Don't copy this method to model specific test file! + # TODO: remove this method once the issues are all fixed! + def _make_attention_mask_non_null(self, inputs_dict): + """Make sure no sequence has all zeros as attention mask""" + + for k in ["attention_mask", "encoder_attention_mask", "decoder_attention_mask"]: + if k in inputs_dict: + attention_mask = inputs_dict[k] + + # Make sure no all 0s attention masks - to avoid failure at this moment. + # Put `1` at the beginning of sequences to make it still work when combining causal attention masks. + # TODO: remove this line once a fix regarding large negative values for attention mask is done. + attention_mask = torch.cat( + [torch.ones_like(attention_mask[:, :1], dtype=attention_mask.dtype), attention_mask[:, 1:]], dim=-1 + ) + + # Here we make the first sequence with all 0s as attention mask. + # Currently, this will fail for `TFWav2Vec2Model`. This is caused by the different large negative + # values, like `1e-4`, `1e-9`, `1e-30` and `-inf` for attention mask across models/frameworks. + # TODO: enable this block once the large negative values thing is cleaned up. + # (see https://github.com/huggingface/transformers/issues/14859) + # attention_mask = torch.cat( + # [torch.zeros_like(attention_mask[:1], dtype=attention_mask.dtype), attention_mask[1:]], + # dim=0 + # ) + + inputs_dict[k] = attention_mask + + # Don't copy this method to model specific test file! + # TODO: remove this method once the issues are all fixed! + def _postprocessing_to_ignore_test_cases(self, tf_outputs, pt_outputs, model_class): + """For temporarily ignoring some failed test cases (issues to be fixed)""" + + tf_keys = {k for k, v in tf_outputs.items() if v is not None} + pt_keys = {k for k, v in pt_outputs.items() if v is not None} + + key_differences = tf_keys.symmetric_difference(pt_keys) + + if model_class.__name__ in [ + "FlaubertWithLMHeadModel", + "FunnelForPreTraining", + "ElectraForPreTraining", + "XLMWithLMHeadModel", + ]: + for k in key_differences: + if k in ["loss", "losses"]: + tf_keys.discard(k) + pt_keys.discard(k) + elif model_class.__name__.startswith("GPT2"): + # `TFGPT2` has `past_key_values` as a tensor while `GPT2` has it as a tuple. + tf_keys.discard("past_key_values") + pt_keys.discard("past_key_values") + + # create new outputs from the remaining fields + new_tf_outputs = type(tf_outputs)(**{k: tf_outputs[k] for k in tf_keys}) + new_pt_outputs = type(pt_outputs)(**{k: pt_outputs[k] for k in pt_keys}) + + return new_tf_outputs, new_pt_outputs + + # Copied from tests.test_modeling_tf_common.TFModelTesterMixin.check_pt_tf_outputs + def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None): + """Check the outputs from PyTorch and TensorFlow models are close enough. Checks are done in a recursive way. + + Args: + model_class: The class of the model that is currently testing. For example, `TFBertModel`, + TFBertForMaskedLM`, `TFBertForSequenceClassification`, etc. Mainly used for providing more informative + error messages. + name (`str`): The name of the output. For example, `output.hidden_states`, `output.attentions`, etc. + attributes (`Tuple[str]`): The names of the output's element if the output is a tuple/list with each element + being a named field in the output. + """ + + self.assertEqual(type(name), str) + if attributes is not None: + self.assertEqual(type(attributes), tuple, f"{name}: The argument `attributes` should be a `tuple`") + + # Allow `ModelOutput` (e.g. `CLIPOutput` has `text_model_output` and `vision_model_output`). + if isinstance(tf_outputs, ModelOutput): + self.assertTrue( + isinstance(pt_outputs, ModelOutput), + f"{name}: `pt_outputs` should an instance of `ModelOutput` when `tf_outputs` is", + ) + + # Don't copy this block to model specific test file! + # TODO: remove this method and this line after issues are fixed + tf_outputs, pt_outputs = self._postprocessing_to_ignore_test_cases(tf_outputs, pt_outputs, model_class) + + tf_keys = [k for k, v in tf_outputs.items() if v is not None] + pt_keys = [k for k, v in pt_outputs.items() if v is not None] + + self.assertEqual(tf_keys, pt_keys, f"{name}: Output keys differ between TF and PyTorch") + + # convert to the case of `tuple` + # appending each key to the current (string) `name` + attributes = tuple([f"{name}.{k}" for k in tf_keys]) + self.check_pt_tf_outputs( + tf_outputs.to_tuple(), pt_outputs.to_tuple(), model_class, tol=tol, name=name, attributes=attributes + ) + + # Allow `list` (e.g. `TransfoXLModelOutput.mems` is a list of tensors.) + elif type(tf_outputs) in [tuple, list]: + self.assertEqual(type(tf_outputs), type(pt_outputs), f"{name}: Output types differ between TF and PyTorch") + self.assertEqual(len(tf_outputs), len(pt_outputs), f"{name}: Output lengths differ between TF and PyTorch") + + if attributes is not None: + # case 1: each output has assigned name (e.g. a tuple form of a `ModelOutput`) + self.assertEqual( + len(attributes), + len(tf_outputs), + f"{name}: The tuple `attributes` should have the same length as `tf_outputs`", + ) + else: + # case 2: each output has no assigned name (e.g. hidden states of each layer) -> add an index to `name` + attributes = tuple([f"{name}_{idx}" for idx in range(len(tf_outputs))]) + + for tf_output, pt_output, attr in zip(tf_outputs, pt_outputs, attributes): + self.check_pt_tf_outputs(tf_output, pt_output, model_class, tol=tol, name=attr) + + elif isinstance(tf_outputs, tf.Tensor): + self.assertTrue( + isinstance(pt_outputs, torch.Tensor), f"{name}: `pt_outputs` should a tensor when `tf_outputs` is" + ) + + tf_outputs = tf_outputs.numpy() + pt_outputs = pt_outputs.detach().to("cpu").numpy() + + self.assertEqual( + tf_outputs.shape, pt_outputs.shape, f"{name}: Output shapes differ between TF and PyTorch" + ) + + # deal with NumPy's scalars to make replacing nan values by 0 work. + if np.isscalar(tf_outputs): + tf_outputs = np.array([tf_outputs]) + pt_outputs = np.array([pt_outputs]) + + tf_nans = np.isnan(tf_outputs) + pt_nans = np.isnan(pt_outputs) + + pt_outputs[tf_nans] = 0 + tf_outputs[tf_nans] = 0 + pt_outputs[pt_nans] = 0 + tf_outputs[pt_nans] = 0 + + max_diff = np.amax(np.abs(tf_outputs - pt_outputs)) + self.assertLessEqual(max_diff, tol, f"{name}: Difference between PyTorch and TF is {max_diff} (>= {tol}).") + else: + raise ValueError( + "`tf_outputs` should be an instance of `ModelOutput`, a `tuple`, or an instance of `tf.Tensor`. Got" + f" {type(tf_outputs)} instead." + ) + + def prepare_tf_inputs_from_pt_inputs(self, pt_inputs_dict): + tf_inputs_dict = {} + for key, tensor in pt_inputs_dict.items(): + # skip key that does not exist in tf + if isinstance(tensor, bool): + tf_inputs_dict[key] = tensor + elif key == "input_values": + tf_inputs_dict[key] = tf.convert_to_tensor(tensor.cpu().numpy(), dtype=tf.float32) + elif key == "pixel_values": + tf_inputs_dict[key] = tf.convert_to_tensor(tensor.cpu().numpy(), dtype=tf.float32) + elif key == "input_features": + tf_inputs_dict[key] = tf.convert_to_tensor(tensor.cpu().numpy(), dtype=tf.float32) + # other general float inputs + elif tensor.is_floating_point(): + tf_inputs_dict[key] = tf.convert_to_tensor(tensor.cpu().numpy(), dtype=tf.float32) + else: + tf_inputs_dict[key] = tf.convert_to_tensor(tensor.cpu().numpy(), dtype=tf.int32) + + return tf_inputs_dict + + def check_pt_tf_models(self, tf_model, pt_model, pt_inputs_dict): + tf_inputs_dict = self.prepare_tf_inputs_from_pt_inputs(pt_inputs_dict) + + # send pytorch inputs to the correct device + pt_inputs_dict = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs_dict.items() + } + + # send pytorch model to the correct device + pt_model.to(torch_device) + + # Check predictions on first output (logits/hidden-states) are close enough given low-level computational differences + pt_model.eval() + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs_dict) + tf_outputs = tf_model(tf_inputs_dict) + + # tf models returned loss is usually a tensor rather than a scalar. + # (see `hf_compute_loss`: it uses `tf.keras.losses.Reduction.NONE`) + # Change it here to a scalar to match PyTorch models' loss + tf_loss = getattr(tf_outputs, "loss", None) + if tf_loss is not None: + tf_outputs.loss = tf.math.reduce_mean(tf_loss) + + self.check_pt_tf_outputs(tf_outputs, pt_outputs, type(pt_model)) + + @is_pt_tf_cross_test + def test_pt_tf_model_equivalence(self, allow_missing_keys=False): + import transformers + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + tf_model_class_name = "TF" + model_class.__name__ # Add the "TF" at the beginning + if not hasattr(transformers, tf_model_class_name): + # transformers does not have this model in TF version yet + return + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # Make sure no sequence has all zeros as attention mask, otherwise some tests fail due to the inconsistency + # of the usage `1e-4`, `1e-9`, `1e-30`, `-inf`. + # TODO: Use a uniform value for all models, make sure all tests pass without this processing, and remove it. + self._make_attention_mask_non_null(inputs_dict) + + tf_model_class = getattr(transformers, tf_model_class_name) + + pt_model = model_class(config) + tf_model = tf_model_class(config) + + pt_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + pt_inputs_dict_with_labels = self._prepare_for_class( + inputs_dict, + model_class, + # Not all models accept "labels" in the forward pass (yet :) ) + return_labels=True if "labels" in inspect.signature(model_class.forward).parameters.keys() else False, + ) + + # make sure only tf inputs are forward that actually exist in function args + tf_input_keys = set(inspect.signature(tf_model.call).parameters.keys()) + + # remove all head masks + tf_input_keys.discard("head_mask") + tf_input_keys.discard("cross_attn_head_mask") + tf_input_keys.discard("decoder_head_mask") + + pt_inputs_dict = {k: v for k, v in pt_inputs_dict.items() if k in tf_input_keys} + pt_inputs_dict_with_labels = {k: v for k, v in pt_inputs_dict_with_labels.items() if k in tf_input_keys} + + # For some models (e.g. base models), there is no label returned. + # Set the input dict to `None` to avoid check outputs twice for the same input dicts. + if not set(pt_inputs_dict_with_labels.keys()).symmetric_difference(pt_inputs_dict.keys()): + pt_inputs_dict_with_labels = None + + # Check we can load pt model in tf and vice-versa with model => model functions + # Here requires `tf_inputs_dict` to build `tf_model` + tf_inputs_dict = self.prepare_tf_inputs_from_pt_inputs(pt_inputs_dict) + tf_model = transformers.load_pytorch_model_in_tf2_model( + tf_model, pt_model, tf_inputs=tf_inputs_dict, allow_missing_keys=allow_missing_keys + ) + pt_model = transformers.load_tf2_model_in_pytorch_model( + pt_model, tf_model, allow_missing_keys=allow_missing_keys + ) + + # Original test: check without `labels` + self.check_pt_tf_models(tf_model, pt_model, pt_inputs_dict) + # check with `labels` + if pt_inputs_dict_with_labels: + self.check_pt_tf_models(tf_model, pt_model, pt_inputs_dict_with_labels) + + # Check we can load pt model in tf and vice-versa with checkpoint => model functions + with tempfile.TemporaryDirectory() as tmpdirname: + pt_checkpoint_path = os.path.join(tmpdirname, "pt_model.bin") + torch.save(pt_model.state_dict(), pt_checkpoint_path) + tf_model = transformers.load_pytorch_checkpoint_in_tf2_model( + tf_model, pt_checkpoint_path, allow_missing_keys=allow_missing_keys + ) + + tf_checkpoint_path = os.path.join(tmpdirname, "tf_model.h5") + tf_model.save_weights(tf_checkpoint_path) + pt_model = transformers.load_tf2_checkpoint_in_pytorch_model( + pt_model, tf_checkpoint_path, allow_missing_keys=allow_missing_keys + ) + + # Original test: check without `labels` + self.check_pt_tf_models(tf_model, pt_model, pt_inputs_dict) + # check with `labels` + if pt_inputs_dict_with_labels: + self.check_pt_tf_models(tf_model, pt_model, pt_inputs_dict_with_labels) + + def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): + diff = np.abs((a - b)).max() + self.assertLessEqual(diff, tol, f"Difference between torch and flax is {diff} (>= {tol}).") + + def check_pt_flax_outputs(self, fx_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None): + """ + Args: + model_class: The class of the model that is currently testing. For example, ..., etc. + Currently unused, but it could make debugging easier and faster. + + names: A string, or a list of strings. These specify what fx_outputs/pt_outputs represent in the model outputs. + Currently unused, but in the future, we could use this information to make the error message clearer + by giving the name(s) of the output tensor(s) with large difference(s) between PT and Flax. + """ + + self.assertEqual(type(name), str) + if attributes is not None: + self.assertEqual(type(attributes), tuple, f"{name}: The argument `attributes` should be a `tuple`") + + # Allow `ModelOutput` (e.g. `CLIPOutput` has `text_model_output` and `vision_model_output`). + if isinstance(fx_outputs, ModelOutput): + self.assertTrue( + isinstance(pt_outputs, ModelOutput), + f"{name}: `pt_outputs` should an instance of `ModelOutput` when `fx_outputs` is", + ) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys, f"{name}: Output keys differ between Flax and PyTorch") + + # convert to the case of `tuple` + # appending each key to the current (string) `name` + attributes = tuple([f"{name}.{k}" for k in fx_keys]) + self.check_pt_flax_outputs( + fx_outputs.to_tuple(), pt_outputs.to_tuple(), model_class, tol=tol, name=name, attributes=attributes + ) + + # Allow `list` (e.g. `TransfoXLModelOutput.mems` is a list of tensors.) + elif type(fx_outputs) in [tuple, list]: + self.assertEqual( + type(fx_outputs), type(pt_outputs), f"{name}: Output types differ between Flax and PyTorch" + ) + self.assertEqual( + len(fx_outputs), len(pt_outputs), f"{name}: Output lengths differ between Flax and PyTorch" + ) + + if attributes is not None: + # case 1: each output has assigned name (e.g. a tuple form of a `ModelOutput`) + self.assertEqual( + len(attributes), + len(fx_outputs), + f"{name}: The tuple `attributes` should have the same length as `fx_outputs`", + ) + else: + # case 2: each output has no assigned name (e.g. hidden states of each layer) -> add an index to `name` + attributes = tuple([f"{name}_{idx}" for idx in range(len(fx_outputs))]) + + for fx_output, pt_output, attr in zip(fx_outputs, pt_outputs, attributes): + self.check_pt_flax_outputs(fx_output, pt_output, model_class, tol=tol, name=attr) + + elif isinstance(fx_outputs, jnp.ndarray): + self.assertTrue( + isinstance(pt_outputs, torch.Tensor), f"{name}: `pt_outputs` should a tensor when `fx_outputs` is" + ) + + # Using `np.asarray` gives `ValueError: assignment destination is read-only` at the line `fx_outputs[fx_nans] = 0`. + fx_outputs = np.array(fx_outputs) + pt_outputs = pt_outputs.detach().to("cpu").numpy() + + self.assertEqual( + fx_outputs.shape, pt_outputs.shape, f"{name}: Output shapes differ between Flax and PyTorch" + ) + + # deal with NumPy's scalars to make replacing nan values by 0 work. + if np.isscalar(fx_outputs): + fx_outputs = np.array([fx_outputs]) + pt_outputs = np.array([pt_outputs]) + + fx_nans = np.isnan(fx_outputs) + pt_nans = np.isnan(pt_outputs) + + pt_outputs[fx_nans] = 0 + fx_outputs[fx_nans] = 0 + pt_outputs[pt_nans] = 0 + fx_outputs[pt_nans] = 0 + + max_diff = np.amax(np.abs(fx_outputs - pt_outputs)) + self.assertLessEqual( + max_diff, tol, f"{name}: Difference between PyTorch and Flax is {max_diff} (>= {tol})." + ) + else: + raise ValueError( + "`fx_outputs` should be an instance of `ModelOutput`, a `tuple`, or an instance of `jnp.ndarray`. Got" + f" {type(fx_outputs)} instead." + ) + + @is_pt_flax_cross_test + def test_equivalence_pt_to_flax(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + fx_model_class_name = "Flax" + model_class.__name__ + + if not hasattr(transformers, fx_model_class_name): + # no flax model exists for this class + return + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + fx_model_class = getattr(transformers, fx_model_class_name) + + # load PyTorch class + pt_model = model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + + # load Flax class + fx_model = fx_model_class(config, dtype=jnp.float32) + + # make sure only flax inputs are forward that actually exist in function args + fx_input_keys = inspect.signature(fx_model.__call__).parameters.keys() + + # prepare inputs + pt_inputs = self._prepare_for_class(inputs_dict, model_class) + + # remove function args that don't exist in Flax + pt_inputs = {k: v for k, v in pt_inputs.items() if k in fx_input_keys} + + # send pytorch inputs to the correct device + pt_inputs = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs.items() + } + + # convert inputs to Flax + fx_inputs = {k: np.array(v.to("cpu")) for k, v in pt_inputs.items() if torch.is_tensor(v)} + + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + # send pytorch model to the correct device + pt_model.to(torch_device) + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + fx_outputs = fx_model(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs, model_class) + + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = fx_model_class.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs_loaded.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs_loaded, pt_outputs, model_class) + + @is_pt_flax_cross_test + def test_equivalence_flax_to_pt(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + fx_model_class_name = "Flax" + model_class.__name__ + + if not hasattr(transformers, fx_model_class_name): + # no flax model exists for this class + return + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + fx_model_class = getattr(transformers, fx_model_class_name) + + # load PyTorch class + pt_model = model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + + # load Flax class + fx_model = fx_model_class(config, dtype=jnp.float32) + + # make sure only flax inputs are forward that actually exist in function args + fx_input_keys = inspect.signature(fx_model.__call__).parameters.keys() + + # prepare inputs + pt_inputs = self._prepare_for_class(inputs_dict, model_class) + + # remove function args that don't exist in Flax + pt_inputs = {k: v for k, v in pt_inputs.items() if k in fx_input_keys} + + # send pytorch inputs to the correct device + pt_inputs = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs.items() + } + + # convert inputs to Flax + fx_inputs = {k: np.array(v.to("cpu")) for k, v in pt_inputs.items() if torch.is_tensor(v)} + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + + # make sure weights are tied in PyTorch + pt_model.tie_weights() + + # send pytorch model to the correct device + pt_model.to(torch_device) + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + fx_outputs = fx_model(**fx_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs, model_class) + + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = model_class.from_pretrained(tmpdirname, from_flax=True) + + # send pytorch model to the correct device + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs_loaded.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs_loaded, model_class) + + def test_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + del inputs["input_ids"] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + + wte = model.get_input_embeddings() + if not self.is_encoder_decoder: + inputs["inputs_embeds"] = wte(input_ids) + else: + inputs["inputs_embeds"] = wte(encoder_input_ids) + inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) + + with torch.no_grad(): + model(**inputs)[0] + + @require_torch_multi_gpu + def test_multi_gpu_data_parallel_forward(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # some params shouldn't be scattered by nn.DataParallel + # so just remove them if they are present. + blacklist_non_batched_params = ["head_mask", "decoder_head_mask", "cross_attn_head_mask"] + for k in blacklist_non_batched_params: + inputs_dict.pop(k, None) + + # move input tensors to cuda:O + for k, v in inputs_dict.items(): + if torch.is_tensor(v): + inputs_dict[k] = v.to(0) + + for model_class in self.all_model_classes: + model = model_class(config=config) + model.to(0) + model.eval() + + # Wrap model in nn.DataParallel + model = nn.DataParallel(model) + with torch.no_grad(): + _ = model(**self._prepare_for_class(inputs_dict, model_class)) + + @require_torch_multi_gpu + def test_model_parallelization(self): + if not self.test_model_parallel: + return + + # a candidate for testing_utils + def get_current_gpu_memory_use(): + """returns a list of cuda memory allocations per GPU in MBs""" + + per_device_memory = [] + for id in range(torch.cuda.device_count()): + with torch.cuda.device(id): + per_device_memory.append(torch.cuda.memory_allocated() >> 20) + + return per_device_memory + + # Needs a large model to see the difference. + config = self.model_tester.get_large_model_config() + + for model_class in self.all_parallelizable_model_classes: + torch.cuda.empty_cache() + + # 1. single gpu memory load + unload + memory measurements + # Retrieve initial memory usage (can easily be ~0.6-1.5GB if cuda-kernels have been preloaded by previous tests) + memory_at_start = get_current_gpu_memory_use() + + # Put model on device 0 and take a memory snapshot + model = model_class(config) + model.to("cuda:0") + memory_after_model_load = get_current_gpu_memory_use() + + # The memory use on device 0 should be higher than it was initially. + self.assertGreater(memory_after_model_load[0], memory_at_start[0]) + + del model + gc.collect() + torch.cuda.empty_cache() + + # 2. MP test + # it's essential to re-calibrate the usage before the next stage + memory_at_start = get_current_gpu_memory_use() + + # Spread model layers over multiple devices + model = model_class(config) + model.parallelize() + memory_after_parallelization = get_current_gpu_memory_use() + + # Assert that the memory use on all devices is higher than it was when loaded only on CPU + for n in range(len(model.device_map.keys())): + self.assertGreater(memory_after_parallelization[n], memory_at_start[n]) + + # Assert that the memory use of device 0 is lower than it was when the entire model was loaded on it + self.assertLess(memory_after_parallelization[0], memory_after_model_load[0]) + + # Assert that the memory use of device 1 is higher than it was when the entire model was loaded + # on device 0 and device 1 wasn't used at all + self.assertGreater(memory_after_parallelization[1], memory_after_model_load[1]) + + del model + gc.collect() + torch.cuda.empty_cache() + + @require_torch_multi_gpu + def test_model_parallel_equal_results(self): + if not self.test_model_parallel: + return + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_parallelizable_model_classes: + inputs_dict = self._prepare_for_class(inputs_dict, model_class) + + def cast_to_device(dictionary, device): + output = {} + for k, v in dictionary.items(): + if isinstance(v, torch.Tensor): + output[k] = v.to(device) + else: + output[k] = v + + return output + + model = model_class(config) + output = model(**cast_to_device(inputs_dict, "cpu")) + + model.parallelize() + + parallel_output = model(**cast_to_device(inputs_dict, "cuda:0")) + + for value, parallel_value in zip(output, parallel_output): + if isinstance(value, torch.Tensor): + self.assertTrue(torch.allclose(value, parallel_value.to("cpu"), atol=1e-7)) + elif isinstance(value, (Tuple, List)): + for value_, parallel_value_ in zip(value, parallel_value): + self.assertTrue(torch.allclose(value_, parallel_value_.to("cpu"), atol=1e-7)) + + def check_device_map_is_respected(self, model, device_map): + for param_name, param in model.named_parameters(): + # Find device in device_map + while len(param_name) > 0 and param_name not in device_map: + param_name = ".".join(param_name.split(".")[:-1]) + if param_name not in device_map: + raise ValueError("device map is incomplete, it does not contain any device for `param_name`.") + + param_device = device_map[param_name] + if param_device in ["cpu", "disk"]: + self.assertEqual(param.device, torch.device("meta")) + else: + self.assertEqual(param.device, torch.device(param_device)) + + @require_accelerate + @mark.accelerate_tests + @require_torch_gpu + def test_disk_offload_bin(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class._no_split_modules is None: + continue + + inputs_dict_class = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config).eval() + model = model.to(torch_device) + torch.manual_seed(0) + base_output = model(**inputs_dict_class) + + model_size = compute_module_sizes(model)[""] + with tempfile.TemporaryDirectory() as tmp_dir: + model.cpu().save_pretrained(tmp_dir, safe_serialization=False) + + with self.assertRaises(ValueError): + max_size = int(self.model_split_percents[0] * model_size) + max_memory = {0: max_size, "cpu": max_size} + # This errors out cause it's missing an offload folder + new_model = model_class.from_pretrained(tmp_dir, device_map="auto", max_memory=max_memory) + + max_size = int(self.model_split_percents[1] * model_size) + max_memory = {0: max_size, "cpu": max_size} + new_model = model_class.from_pretrained( + tmp_dir, device_map="auto", max_memory=max_memory, offload_folder=tmp_dir + ) + + self.check_device_map_is_respected(new_model, new_model.hf_device_map) + torch.manual_seed(0) + new_output = new_model(**inputs_dict_class) + + self.assertTrue(torch.allclose(base_output[0], new_output[0], atol=1e-5)) + + @require_accelerate + @mark.accelerate_tests + @require_torch_gpu + def test_disk_offload_safetensors(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class._no_split_modules is None: + continue + + inputs_dict_class = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config).eval() + model = model.to(torch_device) + torch.manual_seed(0) + base_output = model(**inputs_dict_class) + + model_size = compute_module_sizes(model)[""] + with tempfile.TemporaryDirectory() as tmp_dir: + model.cpu().save_pretrained(tmp_dir) + + max_size = int(self.model_split_percents[1] * model_size) + max_memory = {0: max_size, "cpu": max_size} + + # This doesn't error out as it's in safetensors and doesn't need an offload folder + new_model = model_class.from_pretrained(tmp_dir, device_map="auto", max_memory=max_memory) + + self.check_device_map_is_respected(new_model, new_model.hf_device_map) + torch.manual_seed(0) + new_output = new_model(**inputs_dict_class) + + self.assertTrue(torch.allclose(base_output[0], new_output[0], atol=1e-5)) + + @require_accelerate + @mark.accelerate_tests + @require_torch_gpu + def test_cpu_offload(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class._no_split_modules is None: + continue + + inputs_dict_class = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config).eval() + model = model.to(torch_device) + + torch.manual_seed(0) + base_output = model(**inputs_dict_class) + + model_size = compute_module_sizes(model)[""] + # We test several splits of sizes to make sure it works. + max_gpu_sizes = [int(p * model_size) for p in self.model_split_percents[1:]] + with tempfile.TemporaryDirectory() as tmp_dir: + model.cpu().save_pretrained(tmp_dir) + + for max_size in max_gpu_sizes: + max_memory = {0: max_size, "cpu": model_size * 2} + new_model = model_class.from_pretrained(tmp_dir, device_map="auto", max_memory=max_memory) + # Making sure part of the model will actually end up offloaded + self.assertSetEqual(set(new_model.hf_device_map.values()), {0, "cpu"}) + + self.check_device_map_is_respected(new_model, new_model.hf_device_map) + + torch.manual_seed(0) + new_output = new_model(**inputs_dict_class) + + self.assertTrue(torch.allclose(base_output[0], new_output[0], atol=1e-5)) + + @require_accelerate + @mark.accelerate_tests + @require_torch_multi_gpu + def test_model_parallelism(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class._no_split_modules is None: + continue + + inputs_dict_class = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config).eval() + model = model.to(torch_device) + + torch.manual_seed(0) + base_output = model(**inputs_dict_class) + + model_size = compute_module_sizes(model)[""] + # We test several splits of sizes to make sure it works. + max_gpu_sizes = [int(p * model_size) for p in self.model_split_percents[1:]] + with tempfile.TemporaryDirectory() as tmp_dir: + model.cpu().save_pretrained(tmp_dir) + + for max_size in max_gpu_sizes: + max_memory = {0: max_size, 1: model_size * 2, "cpu": model_size * 2} + new_model = model_class.from_pretrained(tmp_dir, device_map="auto", max_memory=max_memory) + # Making sure part of the model will actually end up offloaded + self.assertSetEqual(set(new_model.hf_device_map.values()), {0, 1}) + + self.check_device_map_is_respected(new_model, new_model.hf_device_map) + + torch.manual_seed(0) + new_output = new_model(**inputs_dict_class) + + self.assertTrue(torch.allclose(base_output[0], new_output[0], atol=1e-5)) + + def test_problem_types(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + problem_types = [ + {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, + {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, + {"title": "regression", "num_labels": 1, "dtype": torch.float}, + ] + + for model_class in self.all_model_classes: + if model_class.__name__ not in [ + *get_values(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES), + ]: + continue + + for problem_type in problem_types: + with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}"): + config.problem_type = problem_type["title"] + config.num_labels = problem_type["num_labels"] + + model = model_class(config) + model.to(torch_device) + model.train() + + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + + if problem_type["num_labels"] > 1: + inputs["labels"] = inputs["labels"].unsqueeze(1).repeat(1, problem_type["num_labels"]) + + inputs["labels"] = inputs["labels"].to(problem_type["dtype"]) + + # This tests that we do not trigger the warning form PyTorch "Using a target size that is different + # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure + # they have the same size." which is a symptom something in wrong for the regression problem. + # See https://github.com/huggingface/transformers/issues/11780 + with warnings.catch_warnings(record=True) as warning_list: + loss = model(**inputs).loss + for w in warning_list: + if "Using a target size that is different to the input size" in str(w.message): + raise ValueError( + f"Something is going wrong in the regression problem: intercepted {w.message}" + ) + + loss.backward() + + def test_load_with_mismatched_shapes(self): + if not self.test_mismatched_shapes: + return + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class.__name__ not in get_values(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES): + continue + + with self.subTest(msg=f"Testing {model_class}"): + with tempfile.TemporaryDirectory() as tmp_dir: + model = model_class(config) + model.save_pretrained(tmp_dir) + + # Fails when we don't set ignore_mismatched_sizes=True + with self.assertRaises(RuntimeError): + new_model = AutoModelForSequenceClassification.from_pretrained(tmp_dir, num_labels=42) + with self.assertRaises(RuntimeError): + new_model_without_prefix = AutoModel.from_pretrained(tmp_dir, vocab_size=10) + + logger = logging.get_logger("transformers.modeling_utils") + + with CaptureLogger(logger) as cl: + new_model = AutoModelForSequenceClassification.from_pretrained( + tmp_dir, num_labels=42, ignore_mismatched_sizes=True + ) + self.assertIn("the shapes did not match", cl.out) + new_model.to(torch_device) + inputs = self._prepare_for_class(inputs_dict, model_class) + logits = new_model(**inputs).logits + self.assertEqual(logits.shape[1], 42) + + with CaptureLogger(logger) as cl: + new_model_without_prefix = AutoModel.from_pretrained( + tmp_dir, vocab_size=10, ignore_mismatched_sizes=True + ) + self.assertIn("the shapes did not match", cl.out) + input_ids = ids_tensor((2, 8), 10) + new_model_without_prefix.to(torch_device) + if self.is_encoder_decoder: + new_model_without_prefix(input_ids, decoder_input_ids=input_ids) + else: + new_model_without_prefix(input_ids) + + def test_model_is_small(self): + # Just a consistency check to make sure we are not running tests on 80M parameter models. + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + num_params = model.num_parameters() + assert ( + num_params < 1000000 + ), f"{model_class} is too big for the common tests ({num_params})! It should have 1M max." + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attn_2_conversion(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if not model_class._supports_flash_attn_2: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained( + tmpdirname, torch_dtype=torch.float16, attn_implementation="flash_attention_2" + ).to(torch_device) + + for _, module in model.named_modules(): + if "FlashAttention" in module.__class__.__name__: + return + + self.assertTrue(False, "FlashAttention2 modules not found in model") + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attn_2_inference(self): + for model_class in self.all_model_classes: + if not model_class._supports_flash_attn_2: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_fa = model_class.from_pretrained( + tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2" + ) + model_fa.to(torch_device) + + model = model_class.from_pretrained( + tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2" + ) + model.to(torch_device) + + dummy_input = inputs_dict[model.main_input_name][:1] + if dummy_input.dtype in [torch.float32, torch.float16]: + dummy_input = dummy_input.to(torch.bfloat16) + + dummy_attention_mask = inputs_dict.get("attention_mask", None) + + if dummy_attention_mask is not None: + dummy_attention_mask = dummy_attention_mask[:1] + dummy_attention_mask[:, 1:] = 1 + dummy_attention_mask[:, :1] = 0 + + if model.config.is_encoder_decoder: + decoder_input_ids = inputs_dict.get("decoder_input_ids", dummy_input)[:1] + + outputs = model(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + outputs_fa = model_fa(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + else: + outputs = model(dummy_input, output_hidden_states=True) + outputs_fa = model_fa(dummy_input, output_hidden_states=True) + + logits = ( + outputs.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs.decoder_hidden_states[-1] + ) + logits_fa = ( + outputs_fa.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs_fa.decoder_hidden_states[-1] + ) + + assert torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2) + + if model.config.is_encoder_decoder: + other_inputs = { + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": dummy_attention_mask, + "output_hidden_states": True, + } + if dummy_attention_mask is not None: + other_inputs["attention_mask"] = dummy_attention_mask + + outputs = model(dummy_input, **other_inputs) + outputs_fa = model_fa(dummy_input, **other_inputs) + else: + other_inputs = { + "output_hidden_states": True, + } + if dummy_attention_mask is not None: + other_inputs["attention_mask"] = dummy_attention_mask + + outputs = model(dummy_input, **other_inputs) + outputs_fa = model_fa(dummy_input, **other_inputs) + + logits = ( + outputs.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs.decoder_hidden_states[-1] + ) + logits_fa = ( + outputs_fa.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs_fa.decoder_hidden_states[-1] + ) + + assert torch.allclose(logits_fa[1:], logits[1:], atol=4e-2, rtol=4e-2) + + # check with inference + dropout + model.train() + _ = model_fa(dummy_input, **other_inputs) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attn_2_inference_padding_right(self): + for model_class in self.all_model_classes: + if not model_class._supports_flash_attn_2: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_fa = model_class.from_pretrained( + tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2" + ) + model_fa.to(torch_device) + + model = model_class.from_pretrained( + tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2" + ) + model.to(torch_device) + + dummy_input = inputs_dict[model.main_input_name][:1] + if dummy_input.dtype in [torch.float32, torch.float16]: + dummy_input = dummy_input.to(torch.bfloat16) + + dummy_attention_mask = inputs_dict.get("attention_mask", None) + + if dummy_attention_mask is not None: + dummy_attention_mask = dummy_attention_mask[:1] + dummy_attention_mask[:, :-1] = 1 + dummy_attention_mask[:, -1:] = 0 + + if model.config.is_encoder_decoder: + decoder_input_ids = inputs_dict.get("decoder_input_ids", dummy_input)[:1] + + outputs = model(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + outputs_fa = model_fa(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + else: + outputs = model(dummy_input, output_hidden_states=True) + outputs_fa = model_fa(dummy_input, output_hidden_states=True) + + logits = ( + outputs.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs.decoder_hidden_states[-1] + ) + logits_fa = ( + outputs_fa.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs_fa.decoder_hidden_states[-1] + ) + + assert torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2) + + if model.config.is_encoder_decoder: + other_inputs = { + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": dummy_attention_mask, + "output_hidden_states": True, + } + if dummy_attention_mask is not None: + other_inputs["attention_mask"] = dummy_attention_mask + + outputs = model(dummy_input, **other_inputs) + outputs_fa = model_fa(dummy_input, **other_inputs) + else: + other_inputs = { + "output_hidden_states": True, + } + if dummy_attention_mask is not None: + other_inputs["attention_mask"] = dummy_attention_mask + + outputs = model(dummy_input, **other_inputs) + outputs_fa = model_fa(dummy_input, **other_inputs) + + logits = ( + outputs.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs.decoder_hidden_states[-1] + ) + logits_fa = ( + outputs_fa.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs_fa.decoder_hidden_states[-1] + ) + + assert torch.allclose(logits_fa[:-1], logits[:-1], atol=4e-2, rtol=4e-2) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attn_2_generate_left_padding(self): + for model_class in self.all_generative_model_classes: + if not model_class._supports_flash_attn_2: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16, low_cpu_mem_usage=True).to( + torch_device + ) + + dummy_input = inputs_dict[model.main_input_name] + if dummy_input.dtype in [torch.float32, torch.bfloat16]: + dummy_input = dummy_input.to(torch.float16) + + dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input)) + # make sure we do left padding + dummy_attention_mask[:, :-1] = 0 + dummy_attention_mask[:, -1:] = 1 + + out = model.generate( + dummy_input, attention_mask=dummy_attention_mask, max_new_tokens=1, do_sample=False + ) + + model = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.float16, + attn_implementation="flash_attention_2", + low_cpu_mem_usage=True, + ).to(torch_device) + + out_fa = model.generate( + dummy_input, attention_mask=dummy_attention_mask, max_new_tokens=1, do_sample=False + ) + + self.assertTrue(torch.allclose(out, out_fa)) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attn_2_generate_padding_right(self): + for model_class in self.all_generative_model_classes: + if not model_class._supports_flash_attn_2: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16, low_cpu_mem_usage=True).to( + torch_device + ) + + dummy_input = inputs_dict[model.main_input_name] + if dummy_input.dtype in [torch.float32, torch.bfloat16]: + dummy_input = dummy_input.to(torch.float16) + + dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input)) + # make sure we do right padding + dummy_attention_mask[:, :-1] = 1 + dummy_attention_mask[:, -1:] = 0 + + out = model.generate( + dummy_input, attention_mask=dummy_attention_mask, max_new_tokens=1, do_sample=False + ) + + model = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.float16, + attn_implementation="flash_attention_2", + low_cpu_mem_usage=True, + ).to(torch_device) + + out_fa = model.generate( + dummy_input, attention_mask=dummy_attention_mask, max_new_tokens=1, do_sample=False + ) + + self.assertTrue(torch.allclose(out, out_fa)) + + @parameterized.expand([("float16",), ("bfloat16",), ("float32",)]) + @require_torch_sdpa + @slow + def test_eager_matches_sdpa_inference(self, torch_dtype: str): + if not self.all_model_classes[0]._supports_sdpa: + self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA") + + if torch_device == "cpu" and torch_dtype == "float16": + self.skipTest("float16 not supported on cpu") + + # Not sure whether it's fine to put torch.XXX in a decorator if torch is not available so hacking it here instead. + if torch_dtype == "float16": + torch_dtype = torch.float16 + elif torch_dtype == "bfloat16": + torch_dtype = torch.bfloat16 + elif torch_dtype == "float32": + torch_dtype = torch.float32 + + atols = { + ("cpu", False, torch.float32): 1e-6, + ("cpu", False, torch.bfloat16): 1e-2, + ("cpu", True, torch.float32): 1e-6, + ("cpu", True, torch.bfloat16): 1e-2, + ("cuda", False, torch.float32): 1e-6, + ("cuda", False, torch.bfloat16): 1e-2, + ("cuda", False, torch.float16): 1e-3, + ("cuda", True, torch.float32): 1e-6, + ("cuda", True, torch.bfloat16): 1e-2, + ("cuda", True, torch.float16): 5e-3, + } + rtols = { + ("cpu", False, torch.float32): 1e-4, + ("cpu", False, torch.bfloat16): 1e-2, + ("cpu", True, torch.float32): 1e-4, + ("cpu", True, torch.bfloat16): 1e-2, + ("cuda", False, torch.float32): 1e-4, + ("cuda", False, torch.bfloat16): 1e-2, + ("cuda", False, torch.float16): 1e-3, + ("cuda", True, torch.float32): 1e-4, + ("cuda", True, torch.bfloat16): 3e-2, + ("cuda", True, torch.float16): 5e-3, + } + + def get_mean_reldiff(failcase, x, ref, atol, rtol): + return f"{failcase}: mean relative difference: {((x - ref).abs() / (ref.abs() + 1e-12)).mean():.3e}, torch atol = {atol}, torch rtol = {rtol}" + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + is_encoder_decoder = model.config.is_encoder_decoder + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_sdpa = model_class.from_pretrained(tmpdirname, torch_dtype=torch_dtype) + model_sdpa = model_sdpa.eval().to(torch_device) + + self.assertTrue(model_sdpa.config._attn_implementation == "sdpa") + + model_eager = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch_dtype, + attn_implementation="eager", + ) + model_eager = model_eager.eval().to(torch_device) + + self.assertTrue(model_eager.config._attn_implementation == "eager") + + for name, submodule in model_eager.named_modules(): + if "SdpaAttention" in submodule.__class__.__name__: + raise ValueError("The eager model should not have SDPA attention layers") + + has_sdpa = False + for name, submodule in model_sdpa.named_modules(): + if "SdpaAttention" in submodule.__class__.__name__: + has_sdpa = True + break + if not has_sdpa and model_sdpa.config.model_type != "falcon": + raise ValueError("The SDPA model should have SDPA attention layers") + + # We use these for loops instead of parameterized.expand just for the interest of avoiding loading/saving 8 times the model, + # but it would be nicer to have an efficient way to use parameterized.expand + fail_cases = [] + for padding_side in ["left", "right"]: + for use_mask in [False, True]: + for batch_size in [1, 5]: + dummy_input = inputs_dict[model.main_input_name] + + if dummy_input.dtype in [torch.float32, torch.bfloat16, torch.float16]: + dummy_input = dummy_input.to(torch_dtype) + + dummy_input = dummy_input[:batch_size] + if dummy_input.shape[0] != batch_size: + if dummy_input.dtype in [torch.float32, torch.bfloat16, torch.float16]: + extension = torch.rand( + batch_size - dummy_input.shape[0], + *dummy_input.shape[1:], + dtype=torch_dtype, + device=torch_device, + ) + dummy_input = torch.cat((dummy_input, extension), dim=0).to(torch_device) + else: + extension = torch.randint( + high=5, + size=(batch_size - dummy_input.shape[0], *dummy_input.shape[1:]), + dtype=dummy_input.dtype, + device=torch_device, + ) + dummy_input = torch.cat((dummy_input, extension), dim=0).to(torch_device) + + if not use_mask: + dummy_attention_mask = None + else: + dummy_attention_mask = inputs_dict.get("attention_mask", None) + if dummy_attention_mask is None: + if is_encoder_decoder: + seqlen = inputs_dict.get("decoder_input_ids", dummy_input).shape[-1] + else: + seqlen = dummy_input.shape[-1] + dummy_attention_mask = ( + torch.ones(batch_size, seqlen).to(torch.int64).to(torch_device) + ) + + dummy_attention_mask = dummy_attention_mask[:batch_size] + if dummy_attention_mask.shape[0] != batch_size: + extension = torch.ones( + batch_size - dummy_attention_mask.shape[0], + *dummy_attention_mask.shape[1:], + dtype=dummy_attention_mask.dtype, + device=torch_device, + ) + dummy_attention_mask = torch.cat((dummy_attention_mask, extension), dim=0) + dummy_attention_mask = dummy_attention_mask.to(torch_device) + + dummy_attention_mask[:] = 1 + if padding_side == "left": + dummy_attention_mask[-1, :-1] = 1 + dummy_attention_mask[-1, -4:] = 0 + elif padding_side == "right": + dummy_attention_mask[-1, 1:] = 1 + dummy_attention_mask[-1, :3] = 0 + + for enable_kernels in [False, True]: + failcase = f"padding_side={padding_side}, use_mask={use_mask}, batch_size={batch_size}, enable_kernels={enable_kernels}" + if is_encoder_decoder: + decoder_input_ids = inputs_dict.get("decoder_input_ids", dummy_input)[:batch_size] + if decoder_input_ids.shape[0] != batch_size: + extension = torch.ones( + batch_size - decoder_input_ids.shape[0], + *decoder_input_ids.shape[1:], + dtype=decoder_input_ids.dtype, + device=torch_device, + ) + decoder_input_ids = torch.cat((decoder_input_ids, extension), dim=0) + decoder_input_ids = decoder_input_ids.to(torch_device) + + # TODO: never an `attention_mask` arg here? + other_inputs = { + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": dummy_attention_mask, + "output_hidden_states": True, + } + else: + other_inputs = { + "output_hidden_states": True, + } + + # Otherwise fails for e.g. WhisperEncoderModel + if "attention_mask" in inspect.signature(model_eager.forward).parameters: + other_inputs["attention_mask"] = dummy_attention_mask + + # TODO: test gradients as well (& for FA2 as well!) + with torch.no_grad(): + with torch.backends.cuda.sdp_kernel( + enable_flash=enable_kernels, + enable_math=True, + enable_mem_efficient=enable_kernels, + ): + outputs_eager = model_eager(dummy_input, **other_inputs) + outputs_sdpa = model_sdpa(dummy_input, **other_inputs) + + logits_eager = ( + outputs_eager.hidden_states[-1] + if not is_encoder_decoder + else outputs_eager.decoder_hidden_states[-1] + ) + logits_sdpa = ( + outputs_sdpa.hidden_states[-1] + if not is_encoder_decoder + else outputs_sdpa.decoder_hidden_states[-1] + ) + + if torch_device in ["cpu", "cuda"]: + atol = atols[torch_device, enable_kernels, torch_dtype] + rtol = rtols[torch_device, enable_kernels, torch_dtype] + else: + atol = 1e-7 + rtol = 1e-4 + + # Masked tokens output slightly deviates - we don't mind that. + if use_mask: + if padding_side == "left": + sub_sdpa = logits_sdpa[:-1] + sub_eager = logits_eager[:-1] + if not torch.allclose(sub_sdpa, sub_eager, atol=atol, rtol=rtol): + fail_cases.append( + get_mean_reldiff(failcase, sub_sdpa, sub_eager, atol, rtol) + ) + + sub_sdpa = logits_sdpa[-1, :-4] + sub_eager = logits_eager[-1, :-4] + if not torch.allclose(sub_sdpa, sub_eager, atol=atol, rtol=rtol): + fail_cases.append( + get_mean_reldiff(failcase, sub_sdpa, sub_eager, atol, rtol) + ) + + # Testing the padding tokens is not really meaningful but anyway + # sub_sdpa = logits_sdpa[-1, -4:] + # sub_eager = logits_eager[-1, -4:] + # if not torch.allclose(sub_sdpa, sub_eager, atol=atol, rtol=rtol): + # fail_cases.append(get_mean_reldiff(failcase, sub_sdpa, sub_eager, 4e-2, 4e-2)) + elif padding_side == "right": + sub_sdpa = logits_sdpa[:-1] + sub_eager = logits_eager[:-1] + if not torch.allclose(sub_sdpa, sub_eager, atol=atol, rtol=rtol): + fail_cases.append( + get_mean_reldiff(failcase, sub_sdpa, sub_eager, atol, rtol) + ) + + sub_sdpa = logits_sdpa[-1, 3:] + sub_eager = logits_eager[-1, 3:] + if not torch.allclose(sub_sdpa, sub_eager, atol=atol, rtol=rtol): + fail_cases.append( + get_mean_reldiff(failcase, sub_sdpa, sub_eager, atol, rtol) + ) + + # Testing the padding tokens is not really meaningful but anyway + # sub_sdpa = logits_sdpa[-1, :3] + # sub_eager = logits_eager[-1, :3] + # if not torch.allclose(sub_sdpa, sub_eager, atol=atol, rtol=rtol): + # fail_cases.append(get_mean_reldiff(failcase, sub_sdpa, sub_eager, 4e-2, 4e-2)) + + else: + if not torch.allclose(logits_sdpa, logits_eager, atol=atol, rtol=rtol): + fail_cases.append( + get_mean_reldiff(failcase, logits_sdpa, logits_eager, atol, rtol) + ) + + self.assertTrue(len(fail_cases) == 0, "\n".join(fail_cases)) + + @require_torch_sdpa + @slow + def test_eager_matches_sdpa_generate(self): + max_new_tokens = 30 + + if len(self.all_generative_model_classes) == 0: + self.skipTest(f"{self.__class__.__name__} tests a model that does support generate: skipping this test") + + for model_class in self.all_generative_model_classes: + if not model_class._supports_sdpa: + self.skipTest(f"{model_class.__name__} does not support SDPA") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + dummy_input = inputs_dict[model_class.main_input_name] + if dummy_input.dtype in [torch.float32, torch.bfloat16]: + dummy_input = dummy_input.to(torch.float16) + + # make sure that all models have enough positions for generation + if hasattr(config, "max_position_embeddings"): + config.max_position_embeddings = max_new_tokens + dummy_input.shape[1] + 1 + + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input)) + + model_sdpa = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.float16, + low_cpu_mem_usage=True, + ).to(torch_device) + + self.assertTrue(model_sdpa.config._attn_implementation == "sdpa") + + model_eager = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.float16, + low_cpu_mem_usage=True, + attn_implementation="eager", + ).to(torch_device) + + self.assertTrue(model_eager.config._attn_implementation == "eager") + + for name, submodule in model_eager.named_modules(): + if "SdpaAttention" in submodule.__class__.__name__: + raise ValueError("The eager model should not have SDPA attention layers") + + has_sdpa = False + for name, submodule in model_sdpa.named_modules(): + if "SdpaAttention" in submodule.__class__.__name__: + has_sdpa = True + break + if not has_sdpa: + raise ValueError("The SDPA model should have SDPA attention layers") + + # Just test that a large cache works as expected + res_eager = model_eager.generate( + dummy_input, attention_mask=dummy_attention_mask, max_new_tokens=max_new_tokens, do_sample=False + ) + + res_sdpa = model_sdpa.generate( + dummy_input, attention_mask=dummy_attention_mask, max_new_tokens=max_new_tokens, do_sample=False + ) + + self.assertTrue(torch.allclose(res_eager, res_sdpa)) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attn_2_generate_use_cache(self): + max_new_tokens = 30 + + for model_class in self.all_generative_model_classes: + if not model_class._supports_flash_attn_2: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + dummy_input = inputs_dict[model_class.main_input_name] + if dummy_input.dtype in [torch.float32, torch.bfloat16]: + dummy_input = dummy_input.to(torch.float16) + + # make sure that all models have enough positions for generation + if hasattr(config, "max_position_embeddings"): + config.max_position_embeddings = max_new_tokens + dummy_input.shape[1] + 1 + + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input)) + + model = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.float16, + attn_implementation="flash_attention_2", + low_cpu_mem_usage=True, + ).to(torch_device) + + # Just test that a large cache works as expected + _ = model.generate( + dummy_input, + attention_mask=dummy_attention_mask, + max_new_tokens=max_new_tokens, + do_sample=False, + use_cache=True, + ) + + @require_flash_attn + @require_torch_gpu + @require_bitsandbytes + @mark.flash_attn_test + @slow + def test_flash_attn_2_fp32_ln(self): + for model_class in self.all_generative_model_classes: + if not model_class._supports_flash_attn_2: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + dummy_input = inputs_dict[model.main_input_name] + dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input)) + + if model.config.is_encoder_decoder: + dummy_decoder_input_ids = inputs_dict["decoder_input_ids"] + dummy_decoder_attention_mask = inputs_dict["decoder_attention_mask"] + + model = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.float16, + attn_implementation="flash_attention_2", + low_cpu_mem_usage=True, + load_in_4bit=True, + ) + + for _, param in model.named_parameters(): + # upcast only layer norms + if (param.dtype == torch.float16) or (param.dtype == torch.bfloat16): + param.data = param.data.to(torch.float32) + + if model.config.is_encoder_decoder: + _ = model(dummy_input, decoder_input_ids=dummy_decoder_input_ids) + # with attention mask + _ = model( + dummy_input, + attention_mask=dummy_attention_mask, + decoder_input_ids=dummy_decoder_input_ids, + decoder_attention_mask=dummy_decoder_attention_mask, + ) + else: + _ = model(dummy_input) + # with attention mask + _ = model(dummy_input, attention_mask=dummy_attention_mask) + + @is_pt_tf_cross_test + def test_tf_from_pt_safetensors(self): + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + tf_model_class_name = "TF" + model_class.__name__ # Add the "TF" at the beginning + if not hasattr(transformers, tf_model_class_name): + # transformers does not have this model in TF version yet + return + + tf_model_class = getattr(transformers, tf_model_class_name) + + pt_model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname, safe_serialization=True) + tf_model_1 = tf_model_class.from_pretrained(tmpdirname, from_pt=True) + + pt_model.save_pretrained(tmpdirname, safe_serialization=False) + tf_model_2 = tf_model_class.from_pretrained(tmpdirname, from_pt=True) + + # Check models are equal + for p1, p2 in zip(tf_model_1.weights, tf_model_2.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @is_pt_flax_cross_test + def test_flax_from_pt_safetensors(self): + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + flax_model_class_name = "Flax" + model_class.__name__ # Add the "Flax at the beginning + if not hasattr(transformers, flax_model_class_name): + # transformers does not have this model in Flax version yet + return + + flax_model_class = getattr(transformers, flax_model_class_name) + + pt_model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname, safe_serialization=True) + flax_model_1 = flax_model_class.from_pretrained(tmpdirname, from_pt=True) + + pt_model.save_pretrained(tmpdirname, safe_serialization=False) + flax_model_2 = flax_model_class.from_pretrained(tmpdirname, from_pt=True) + + # Check models are equal + self.assertTrue(check_models_equal(flax_model_1, flax_model_2)) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attn_2_from_config(self): + for model_class in self.all_generative_model_classes: + if not model_class._supports_flash_attn_2: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + # TODO: to change it in the future with other relevant auto classes + fa2_model = AutoModelForCausalLM.from_config( + config, attn_implementation="flash_attention_2", torch_dtype=torch.bfloat16 + ).to(torch_device) + + dummy_input = torch.LongTensor([[0, 2, 3, 4], [0, 2, 3, 4]]).to(torch_device) + dummy_attention_mask = torch.LongTensor([[1, 1, 1, 1], [0, 1, 1, 1]]).to(torch_device) + + fa2_correctly_converted = False + + for _, module in fa2_model.named_modules(): + if "FlashAttention" in module.__class__.__name__: + fa2_correctly_converted = True + break + + self.assertTrue(fa2_correctly_converted) + + _ = fa2_model(input_ids=dummy_input, attention_mask=dummy_attention_mask) + + with tempfile.TemporaryDirectory() as tmpdirname: + fa2_model.save_pretrained(tmpdirname) + + model_from_pretrained = AutoModelForCausalLM.from_pretrained(tmpdirname) + + self.assertTrue(model_from_pretrained.config._attn_implementation != "flash_attention_2") + + fa2_correctly_converted = False + + for _, module in model_from_pretrained.named_modules(): + if "FlashAttention" in module.__class__.__name__: + fa2_correctly_converted = True + break + + self.assertFalse(fa2_correctly_converted) + + +global_rng = random.Random() + + +def ids_tensor(shape, vocab_size, rng=None, name=None): + # Creates a random int32 tensor of the shape within the vocab size + if rng is None: + rng = global_rng + + total_dims = 1 + for dim in shape: + total_dims *= dim + + values = [] + for _ in range(total_dims): + values.append(rng.randint(0, vocab_size - 1)) + + return torch.tensor(data=values, dtype=torch.long, device=torch_device).view(shape).contiguous() + + +def random_attention_mask(shape, rng=None, name=None): + attn_mask = ids_tensor(shape, vocab_size=2, rng=None, name=None) + # make sure that at least one token is attended to for each batch + # we choose the 1st token so this property of `at least one being non-zero` still holds after applying causal mask + attn_mask[:, 0] = 1 + return attn_mask + + +def floats_tensor(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + total_dims = 1 + for dim in shape: + total_dims *= dim + + values = [] + for _ in range(total_dims): + values.append(rng.random() * scale) + + return torch.tensor(data=values, dtype=torch.float, device=torch_device).view(shape).contiguous() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_flax_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_flax_common.py new file mode 100644 index 0000000000000000000000000000000000000000..58ada0226a51bc5a7aa453646cfb7fcfacda4616 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_flax_common.py @@ -0,0 +1,1147 @@ +# 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 copy +import inspect +import json +import random +import tempfile +from typing import List, Tuple + +import numpy as np + +import transformers +from transformers import is_flax_available, is_torch_available +from transformers.models.auto import get_values +from transformers.testing_utils import CaptureLogger, is_pt_flax_cross_test, require_flax, torch_device +from transformers.utils import CONFIG_NAME, GENERATION_CONFIG_NAME, logging +from transformers.utils.generic import ModelOutput + + +if is_flax_available(): + import os + + import jax + import jax.numpy as jnp + from flax.core.frozen_dict import FrozenDict, freeze, unfreeze + from flax.serialization import from_bytes + from flax.traverse_util import flatten_dict, unflatten_dict + + from transformers import ( + FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING, + FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + FLAX_MODEL_MAPPING, + FlaxAutoModel, + FlaxAutoModelForSequenceClassification, + FlaxBertModel, + ) + from transformers.modeling_flax_pytorch_utils import ( + convert_pytorch_state_dict_to_flax, + load_flax_weights_in_pytorch_model, + ) + from transformers.modeling_flax_utils import FLAX_WEIGHTS_INDEX_NAME, FLAX_WEIGHTS_NAME + + os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.12" # assumed parallelism: 8 + +if is_torch_available(): + import torch + + +def ids_tensor(shape, vocab_size, rng=None): + """Creates a random int32 tensor of the shape within the vocab size.""" + if rng is None: + rng = random.Random() + + total_dims = 1 + for dim in shape: + total_dims *= dim + + values = [] + for _ in range(total_dims): + values.append(rng.randint(0, vocab_size - 1)) + + output = np.array(values, dtype=jnp.int32).reshape(shape) + + return output + + +def floats_tensor(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = random.Random() + + total_dims = 1 + for dim in shape: + total_dims *= dim + + values = [] + for _ in range(total_dims): + values.append(rng.random() * scale) + + return np.array(values, dtype=jnp.float32).reshape(shape) + + +def random_attention_mask(shape, rng=None): + attn_mask = ids_tensor(shape, vocab_size=2, rng=rng) + # make sure that at least one token is attended to for each batch + attn_mask[:, -1] = 1 + return attn_mask + + +def get_params(params, from_head_prefix=None): + """Function extracts relevant parameters into flatten dict from model params, + appends batch normalization statistics if present""" + + # If Both parameters and batch normalization statistics are present + if "batch_stats" in params: + # Extract only parameters for the specified head prefix (if specified) and add batch statistics + if from_head_prefix is not None: + extracted_params = flatten_dict(unfreeze(params["params"][from_head_prefix])) + extracted_params.update(flatten_dict(params["batch_stats"][from_head_prefix])) + else: + extracted_params = flatten_dict(unfreeze(params["params"])) + extracted_params.update(flatten_dict(params["batch_stats"])) + + # Only parameters are present + else: + if from_head_prefix is not None: + extracted_params = flatten_dict(unfreeze(params[from_head_prefix])) + else: + extracted_params = flatten_dict(unfreeze(params)) + + return extracted_params + + +@require_flax +class FlaxModelTesterMixin: + model_tester = None + all_model_classes = () + test_mismatched_shapes = True + is_encoder_decoder = False + test_head_masking = False + has_attentions = True + + def _prepare_for_class(self, inputs_dict, model_class): + inputs_dict = copy.deepcopy(inputs_dict) + + # hack for now until we have AutoModel classes + if "ForMultipleChoice" in model_class.__name__: + inputs_dict = { + k: jnp.broadcast_to(v[:, None], (v.shape[0], self.model_tester.num_choices, v.shape[-1])) + if isinstance(v, (jnp.ndarray, np.ndarray)) and k != "indices_prng_key" + else v + for k, v in inputs_dict.items() + } + + return inputs_dict + + def assert_almost_equals(self, a: np.ndarray, b: np.ndarray, tol: float): + diff = np.abs((a - b)).max() + self.assertLessEqual(diff, tol, f"Difference between torch and flax is {diff} (>= {tol}).") + + def test_model_outputs_equivalence(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): + tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs) + dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple() + + def recursive_check(tuple_object, dict_object): + if isinstance(tuple_object, (List, Tuple)): + for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif tuple_object is None: + return + else: + self.assert_almost_equals(jnp.nan_to_num(tuple_object), jnp.nan_to_num(dict_object), 1e-5) + + recursive_check(tuple_output, dict_output) + + for model_class in self.all_model_classes: + model = model_class(config) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + # (Copied from tests.test_modeling_common.ModelTesterMixin.check_pt_flax_outputs) + def check_pt_flax_outputs(self, fx_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None): + """ + Args: + model_class: The class of the model that is currently testing. For example, ..., etc. + Currently unused, but it could make debugging easier and faster. + + names: A string, or a list of strings. These specify what fx_outputs/pt_outputs represent in the model outputs. + Currently unused, but in the future, we could use this information to make the error message clearer + by giving the name(s) of the output tensor(s) with large difference(s) between PT and Flax. + """ + + self.assertEqual(type(name), str) + if attributes is not None: + self.assertEqual(type(attributes), tuple, f"{name}: The argument `attributes` should be a `tuple`") + + # Allow `ModelOutput` (e.g. `CLIPOutput` has `text_model_output` and `vision_model_output`). + if isinstance(fx_outputs, ModelOutput): + self.assertTrue( + isinstance(pt_outputs, ModelOutput), + f"{name}: `pt_outputs` should an instance of `ModelOutput` when `fx_outputs` is", + ) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys, f"{name}: Output keys differ between Flax and PyTorch") + + # convert to the case of `tuple` + # appending each key to the current (string) `name` + attributes = tuple([f"{name}.{k}" for k in fx_keys]) + self.check_pt_flax_outputs( + fx_outputs.to_tuple(), pt_outputs.to_tuple(), model_class, tol=tol, name=name, attributes=attributes + ) + + # Allow `list` (e.g. `TransfoXLModelOutput.mems` is a list of tensors.) + elif type(fx_outputs) in [tuple, list]: + self.assertEqual( + type(fx_outputs), type(pt_outputs), f"{name}: Output types differ between Flax and PyTorch" + ) + self.assertEqual( + len(fx_outputs), len(pt_outputs), f"{name}: Output lengths differ between Flax and PyTorch" + ) + + if attributes is not None: + # case 1: each output has assigned name (e.g. a tuple form of a `ModelOutput`) + self.assertEqual( + len(attributes), + len(fx_outputs), + f"{name}: The tuple `attributes` should have the same length as `fx_outputs`", + ) + else: + # case 2: each output has no assigned name (e.g. hidden states of each layer) -> add an index to `name` + attributes = tuple([f"{name}_{idx}" for idx in range(len(fx_outputs))]) + + for fx_output, pt_output, attr in zip(fx_outputs, pt_outputs, attributes): + self.check_pt_flax_outputs(fx_output, pt_output, model_class, tol=tol, name=attr) + + elif isinstance(fx_outputs, jnp.ndarray): + self.assertTrue( + isinstance(pt_outputs, torch.Tensor), f"{name}: `pt_outputs` should a tensor when `fx_outputs` is" + ) + + # Using `np.asarray` gives `ValueError: assignment destination is read-only` at the line `fx_outputs[fx_nans] = 0`. + fx_outputs = np.array(fx_outputs) + pt_outputs = pt_outputs.detach().to("cpu").numpy() + + self.assertEqual( + fx_outputs.shape, pt_outputs.shape, f"{name}: Output shapes differ between Flax and PyTorch" + ) + + # deal with NumPy's scalars to make replacing nan values by 0 work. + if np.isscalar(fx_outputs): + fx_outputs = np.array([fx_outputs]) + pt_outputs = np.array([pt_outputs]) + + fx_nans = np.isnan(fx_outputs) + pt_nans = np.isnan(pt_outputs) + + pt_outputs[fx_nans] = 0 + fx_outputs[fx_nans] = 0 + pt_outputs[pt_nans] = 0 + fx_outputs[pt_nans] = 0 + + max_diff = np.amax(np.abs(fx_outputs - pt_outputs)) + self.assertLessEqual( + max_diff, tol, f"{name}: Difference between PyTorch and Flax is {max_diff} (>= {tol})." + ) + else: + raise ValueError( + "`fx_outputs` should be an instance of `ModelOutput`, a `tuple`, or an instance of `jnp.ndarray`. Got" + f" {type(fx_outputs)} instead." + ) + + @is_pt_flax_cross_test + def test_equivalence_pt_to_flax(self): + # It might be better to put this inside the for loop below (because we modify the config there). + # But logically, it is fine. + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # prepare inputs + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + pt_inputs = {k: torch.tensor(v.tolist(), device=torch_device) for k, v in prepared_inputs_dict.items()} + + # load corresponding PyTorch class + pt_model_class_name = model_class.__name__[4:] # Skip the "Flax" at the beginning + pt_model_class = getattr(transformers, pt_model_class_name) + + pt_model = pt_model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + fx_model = model_class(config, dtype=jnp.float32) + + fx_state = convert_pytorch_state_dict_to_flax(pt_model.state_dict(), fx_model) + fx_model.params = fx_state + + # send pytorch model to the correct device + pt_model.to(torch_device) + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + fx_outputs = fx_model(**prepared_inputs_dict) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs, model_class) + + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + fx_model_loaded = model_class.from_pretrained(tmpdirname, from_pt=True) + + fx_outputs_loaded = fx_model_loaded(**prepared_inputs_dict) + + fx_keys = tuple([k for k, v in fx_outputs_loaded.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs_loaded, pt_outputs, model_class) + + @is_pt_flax_cross_test + def test_equivalence_flax_to_pt(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # prepare inputs + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + pt_inputs = {k: torch.tensor(v.tolist(), device=torch_device) for k, v in prepared_inputs_dict.items()} + + # load corresponding PyTorch class + pt_model_class_name = model_class.__name__[4:] # Skip the "Flax" at the beginning + pt_model_class = getattr(transformers, pt_model_class_name) + + pt_model = pt_model_class(config).eval() + # Flax models don't use the `use_cache` option and cache is not returned as a default. + # So we disable `use_cache` here for PyTorch model. + pt_model.config.use_cache = False + fx_model = model_class(config, dtype=jnp.float32) + + pt_model = load_flax_weights_in_pytorch_model(pt_model, fx_model.params) + + # make sure weights are tied in PyTorch + pt_model.tie_weights() + + # send pytorch model to the correct device + pt_model.to(torch_device) + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs) + fx_outputs = fx_model(**prepared_inputs_dict) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs, model_class) + + with tempfile.TemporaryDirectory() as tmpdirname: + fx_model.save_pretrained(tmpdirname) + pt_model_loaded = pt_model_class.from_pretrained(tmpdirname, from_flax=True) + + # send pytorch model to the correct device + pt_model_loaded.to(torch_device) + pt_model_loaded.eval() + + with torch.no_grad(): + pt_outputs_loaded = pt_model_loaded(**pt_inputs) + + fx_keys = tuple([k for k, v in fx_outputs.items() if v is not None]) + pt_keys = tuple([k for k, v in pt_outputs_loaded.items() if v is not None]) + + self.assertEqual(fx_keys, pt_keys) + self.check_pt_flax_outputs(fx_outputs, pt_outputs_loaded, model_class) + + def test_from_pretrained_save_pretrained(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + model = model_class(config) + + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + outputs = model(**prepared_inputs_dict).to_tuple() + + # verify that normal save_pretrained works as expected + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + # the config file (and the generation config file, if it can generate) should be saved + self.assertTrue(os.path.exists(os.path.join(tmpdirname, CONFIG_NAME))) + self.assertEqual( + model.can_generate(), os.path.exists(os.path.join(tmpdirname, GENERATION_CONFIG_NAME)) + ) + + model_loaded = model_class.from_pretrained(tmpdirname) + + outputs_loaded = model_loaded(**prepared_inputs_dict).to_tuple() + for output_loaded, output in zip(outputs_loaded, outputs): + self.assert_almost_equals(output_loaded, output, 1e-3) + + # verify that save_pretrained for distributed training + # with `params=params` works as expected + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, params=model.params) + model_loaded = model_class.from_pretrained(tmpdirname) + + outputs_loaded = model_loaded(**prepared_inputs_dict).to_tuple() + for output_loaded, output in zip(outputs_loaded, outputs): + self.assert_almost_equals(output_loaded, output, 1e-3) + + def test_save_load_from_base(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = base_class(config) + base_params = get_params(model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + head_model = model_class.from_pretrained(tmpdirname) + + base_param_from_head = get_params(head_model.params, from_head_prefix=head_model.base_model_prefix) + + for key in base_param_from_head.keys(): + max_diff = (base_params[key] - base_param_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + def test_save_load_to_base(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + base_params_from_head = get_params(model.params, from_head_prefix=model.base_model_prefix) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname) + + base_params = get_params(base_model.params) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + @is_pt_flax_cross_test + def test_save_load_from_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = base_class(config) + base_params = get_params(model.params) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, base_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + # save pt model + pt_model.save_pretrained(tmpdirname) + head_model = model_class.from_pretrained(tmpdirname, from_pt=True) + + base_param_from_head = get_params(head_model.params, from_head_prefix=head_model.base_model_prefix) + + for key in base_param_from_head.keys(): + max_diff = (base_params[key] - base_param_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + @is_pt_flax_cross_test + def test_save_load_to_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + base_params_from_head = get_params(model.params, from_head_prefix=model.base_model_prefix) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname, from_pt=True) + + base_params = get_params(base_model.params) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + @is_pt_flax_cross_test + def test_save_load_bf16_to_base_pt(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + base_class = FLAX_MODEL_MAPPING[config.__class__] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + model = model_class(config) + model.params = model.to_bf16(model.params) + base_params_from_head = get_params(model.params, from_head_prefix=model.base_model_prefix) + + # convert Flax model to PyTorch model + pt_model_class = getattr(transformers, model_class.__name__[4:]) # Skip the "Flax" at the beginning + pt_model = pt_model_class(config).eval() + pt_model = load_flax_weights_in_pytorch_model(pt_model, model.params) + + # check that all base model weights are loaded correctly + with tempfile.TemporaryDirectory() as tmpdirname: + pt_model.save_pretrained(tmpdirname) + base_model = base_class.from_pretrained(tmpdirname, from_pt=True) + + base_params = get_params(base_model.params) + + for key in base_params_from_head.keys(): + max_diff = (base_params[key] - base_params_from_head[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + def test_jit_compilation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @jax.jit + def model_jitted(input_ids, attention_mask=None, **kwargs): + return model(input_ids=input_ids, attention_mask=attention_mask, **kwargs) + + with self.subTest("JIT Enabled"): + jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + with self.subTest("JIT Disabled"): + with jax.disable_jit(): + outputs = model_jitted(**prepared_inputs_dict).to_tuple() + + self.assertEqual(len(outputs), len(jitted_outputs)) + for jitted_output, output in zip(jitted_outputs, outputs): + self.assertEqual(jitted_output.shape, output.shape) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.__call__) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + if model.config.is_encoder_decoder: + expected_arg_names = [ + "input_ids", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + ] + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + else: + expected_arg_names = ["input_ids", "attention_mask"] + self.assertListEqual(arg_names[:2], expected_arg_names) + + def test_naming_convention(self): + for model_class in self.all_model_classes: + model_class_name = model_class.__name__ + module_class_name = ( + model_class_name[:-5] + "Module" if model_class_name[-5:] == "Model" else model_class_name + "Module" + ) + bert_modeling_flax_module = __import__(model_class.__module__, fromlist=[module_class_name]) + module_cls = getattr(bert_modeling_flax_module, module_class_name) + + self.assertIsNotNone(module_cls) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + else: + seq_length = self.model_tester.seq_length + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_attention_outputs(self): + if not self.has_attentions: + self.skipTest(reason="Model does not output attentions") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + seq_length = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_length) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_length) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + out_len = len(outputs) + + if self.is_encoder_decoder: + correct_outlen = 5 + + # Question Answering model returns start_logits and end_logits + if model_class in get_values(FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING): + correct_outlen += 1 # start_logits and end_logits instead of only 1 output + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + elif self.is_encoder_decoder: + added_hidden_states = 2 + else: + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + def test_load_with_mismatched_shapes(self): + if not self.test_mismatched_shapes: + return + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class not in get_values(FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING): + continue + + with self.subTest(msg=f"Testing {model_class}"): + with tempfile.TemporaryDirectory() as tmp_dir: + model = model_class(config) + model.save_pretrained(tmp_dir) + + # Fails when we don't set ignore_mismatched_sizes=True + with self.assertRaises(ValueError): + new_model = FlaxAutoModelForSequenceClassification.from_pretrained(tmp_dir, num_labels=42) + with self.assertRaises(ValueError): + new_model_without_prefix = FlaxAutoModel.from_pretrained(tmp_dir, vocab_size=10) + + logger = logging.get_logger("transformers.modeling_flax_utils") + with CaptureLogger(logger) as cl: + new_model = FlaxAutoModelForSequenceClassification.from_pretrained( + tmp_dir, num_labels=42, ignore_mismatched_sizes=True + ) + self.assertIn("the shapes did not match", cl.out) + + logits = new_model(**inputs_dict)["logits"] + self.assertEqual(logits.shape[1], 42) + + with CaptureLogger(logger) as cl: + new_model_without_prefix = FlaxAutoModel.from_pretrained( + tmp_dir, vocab_size=10, ignore_mismatched_sizes=True + ) + self.assertIn("the shapes did not match", cl.out) + input_ids = ids_tensor((2, 8), 10) + if self.is_encoder_decoder: + new_model_without_prefix(input_ids, decoder_input_ids=input_ids) + else: + new_model_without_prefix(input_ids) + + def test_default_params_dtype(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + # check if all params are still in float32 when dtype of computation is half-precision + model = model_class(config, dtype=jnp.float16) + types = jax.tree_util.tree_map(lambda x: x.dtype, model.params) + types = flatten_dict(types) + + for name, type_ in types.items(): + self.assertEquals(type_, jnp.float32, msg=f"param {name} is not initialized in fp32.") + + def test_to_bf16(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + + # cast all params to bf16 + params = model.to_bf16(model.params) + types = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype, params)) + # test if all params are in bf16 + for name, type_ in types.items(): + self.assertEqual(type_, jnp.bfloat16, msg=f"param {name} is not in bf16.") + + # test masking + flat_params = flatten_dict(params) + key = random.choice(list(flat_params.keys())) # choose a random param + mask = {path: path != key for path in flat_params} # don't cast the key + mask = unflatten_dict(mask) + + params = model.to_bf16(model.params, mask) + types = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype, params)) + # test if all params are in bf16 except key + for name, type_ in types.items(): + if name == key: + self.assertEqual(type_, jnp.float32, msg=f"param {name} should be in fp32.") + else: + self.assertEqual(type_, jnp.bfloat16, msg=f"param {name} is not in bf16.") + + def test_to_fp16(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + + # cast all params to fp16 + params = model.to_fp16(model.params) + types = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype, params)) + # test if all params are in fp16 + for name, type_ in types.items(): + self.assertEqual(type_, jnp.float16, msg=f"param {name} is not in fp16.") + + # test masking + flat_params = flatten_dict(params) + key = random.choice(list(flat_params.keys())) # choose a random param + mask = {path: path != key for path in flat_params} # don't cast the key + mask = unflatten_dict(mask) + + params = model.to_fp16(model.params, mask) + types = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype, params)) + # test if all params are in fp16 except key + for name, type_ in types.items(): + if name == key: + self.assertEqual(type_, jnp.float32, msg=f"param {name} should be in fp32.") + else: + self.assertEqual(type_, jnp.float16, msg=f"param {name} is not in fp16.") + + def test_to_fp32(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + + # cast all params to fp16 and back to fp32 + params = model.to_fp16(model.params) + params = model.to_fp32(params) + + # test if all params are in fp32 + types = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype, params)) + for name, type_ in types.items(): + self.assertEqual(type_, jnp.float32, msg=f"param {name} is not in fp32.") + + # test masking + flat_params = flatten_dict(params) + key = random.choice(list(flat_params.keys())) # choose a random param + mask = {path: path != key for path in flat_params} # don't cast the key + mask = unflatten_dict(mask) + + # cast to fp16 and back to fp32 with mask + params = model.to_fp16(model.params) + params = model.to_fp32(params, mask) + + # test if all params are in fp32 except key + types = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype, params)) + for name, type_ in types.items(): + if name == key: + self.assertEqual(type_, jnp.float16, msg=f"param {name} should be in fp16.") + else: + self.assertEqual(type_, jnp.float32, msg=f"param {name} is not in fp32.") + + def test_save_load_in_fp16(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + + # convert weights to fp16 and save + params = model.to_fp16(model.params) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, params=params) + + # load the weights again and check if they are still in fp16 + model = model_class.from_pretrained(tmpdirname) + types = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype, model.params)) + for name, type_ in types.items(): + self.assertEqual(type_, jnp.float16, msg=f"param {name} is not in fp16.") + + def test_save_load_in_bf16(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + + # convert weights to bf16 and save + params = model.to_bf16(model.params) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, params=params) + + # load the weights again and check if they are still in fp16 + model = model_class.from_pretrained(tmpdirname) + types = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype, model.params)) + for name, type_ in types.items(): + self.assertEqual(type_, jnp.bfloat16, msg=f"param {name} is not in bf16.") + + def test_model_main_input_name(self): + for model_class in self.all_model_classes: + model_signature = inspect.signature(getattr(model_class, "__call__")) + # The main input is the name of the argument after `self` + observed_main_input_name = list(model_signature.parameters.keys())[1] + self.assertEqual(model_class.main_input_name, observed_main_input_name) + + def test_headmasking(self): + if not self.test_head_masking: + return + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + def _prepare_layer_head_mask(i, attention_heads, num_hidden_layers): + if i == 0: + return np.concatenate([np.zeros(1, dtype=jnp.int32), np.ones(attention_heads - 1, dtype=jnp.int32)]) + if i == num_hidden_layers - 1: + return np.concatenate([np.zeros(attention_heads - 1, dtype=jnp.int32), np.ones(1, dtype=jnp.int32)]) + return np.ones(attention_heads, dtype=jnp.int32) + + for model_class in self.all_model_classes: + model = model_class(config) + + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + inputs = self._prepare_for_class(inputs_dict, model_class).copy() + # Prepare head mask + inputs["head_mask"] = np.stack( + [ + _prepare_layer_head_mask(i, config.num_attention_heads, config.num_hidden_layers) + for i in range(config.num_hidden_layers) + ] + ) + outputs = model(**inputs) + + def _check_attentions_validity(attentions): + # Remove NaN + for t in attentions: + # Check we don't have more than 25% nans (arbitrary) + self.assertLess(np.isnan(t).sum(), t.size / 4) + attentions = [np.where(np.isnan(t), 0.0, t) for t in attentions] + + self.assertAlmostEqual(attentions[0][..., 0, :, :].sum(), 0.0) + self.assertNotEqual(attentions[0][..., -1, :, :].sum(), 0.0) + if len(attentions) > 2: # encoder-decodere models have only 2 layers in each modules + self.assertNotEqual(attentions[1][..., 0, :, :].sum(), 0.0) + self.assertAlmostEqual(attentions[-1][..., -2, :, :].sum(), 0.0) + self.assertNotEqual(attentions[-1][..., -1, :, :].sum(), 0.0) + + if model.config.is_encoder_decoder: + raise NotImplementedError("The test has not been implemented for encoder-decoder models yet.") + else: + _check_attentions_validity(outputs.attentions) + + def test_no_automatic_init(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + for model_class in self.all_model_classes: + model = model_class(config, _do_init=False) + + # Check that accesing parmas raises an ValueError when _do_init is False + with self.assertRaises(ValueError): + params = model.params + + # Check if we params can be properly initialized when calling init_weights + params = model.init_weights(model.key, model.input_shape) + self.assertIsInstance(params, FrozenDict) + # Check if all required parmas are initialized + keys = set(flatten_dict(unfreeze(params)).keys()) + self.assertTrue(all(k in keys for k in model.required_params)) + # Check if the shapes match + flat_params = flatten_dict(unfreeze(params)) + for k, v in flatten_dict(unfreeze(model.params_shape_tree)).items(): + self.assertEqual( + v.shape, + flat_params[k].shape, + "Shapes of {} do not match. Expecting {}, got {}.".format(k, v.shape, flat_params[k].shape), + ) + + # Check that setting params raises an ValueError when _do_init is False + with self.assertRaises(ValueError): + model.params = params + + # Check if we can do a forward pass + inputs_dict["output_hidden_states"] = True + inputs = self._prepare_for_class(inputs_dict, model_class).copy() + model(**inputs, params=params) + + def test_from_pretrained_with_no_automatic_init(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + def _assert_all_params_initialised(model, params): + # Check if all required parmas are loaded + keys = set(flatten_dict(unfreeze(params)).keys()) + self.assertTrue(all(k in keys for k in model.required_params)) + # Check if the shapes match + flat_params = flatten_dict(unfreeze(params)) + for k, v in flatten_dict(unfreeze(model.params_shape_tree)).items(): + self.assertEqual( + v.shape, + flat_params[k].shape, + "Shapes of {} do not match. Expecting {}, got {}.".format(k, v.shape, flat_params[k].shape), + ) + + for model_class in self.all_model_classes: + # init the model + model = model_class(config) + + # save the model in the temporary directory + # load the saved model with _do_init=False + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model, params = model_class.from_pretrained(tmpdirname, _do_init=False) + + # Check that accesing parmas raises an ValueError when _do_init is False + with self.assertRaises(ValueError): + params = model.params + + # Check if all required parmas are loaded + _assert_all_params_initialised(model, params) + + # Check that setting params raises an ValueError when _do_init is False + with self.assertRaises(ValueError): + model.params = params + + # Check if init_weights initializes missing keys from from_pretrained + flat_params = flatten_dict(unfreeze(params)) + random_key = random.choice(list(flat_params.keys())) + flat_params.pop(random_key) + params = freeze(unflatten_dict(flat_params)) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, params=params) + model, params = model_class.from_pretrained(tmpdirname, _do_init=False) + + params = model.init_weights(model.key, model.input_shape, params=params) + # Check if all required parmas are loaded + _assert_all_params_initialised(model, params) + + def test_checkpoint_sharding_from_hub(self): + model = FlaxBertModel.from_pretrained("ArthurZ/flax-tiny-random-bert-sharded") + # the model above is the same as the model below, just a sharded version. + ref_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + for p1, p2 in zip(flatten_dict(model.params).values(), flatten_dict(ref_model.params).values()): + assert np.allclose(np.array(p1), np.array(p2)) + + def test_checkpoint_sharding_local(self): + model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + # We use the same folder for various sizes to make sure a new save erases the old checkpoint. + for max_size in ["150kB", "150kiB", "200kB", "200kiB"]: + model.save_pretrained(tmp_dir, max_shard_size=max_size) + + # Get each shard file and its size + shard_to_size = {} + for shard in os.listdir(tmp_dir): + if shard.endswith(".msgpack"): + shard_file = os.path.join(tmp_dir, shard) + shard_to_size[shard_file] = os.path.getsize(shard_file) + + index_file = os.path.join(tmp_dir, FLAX_WEIGHTS_INDEX_NAME) + # Check there is an index but no regular weight file + self.assertTrue(os.path.isfile(index_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, FLAX_WEIGHTS_NAME))) + + # Check a file is bigger than max_size only when it has a single weight + for shard_file, size in shard_to_size.items(): + if max_size.endswith("kiB"): + max_size_int = int(max_size[:-3]) * 2**10 + else: + max_size_int = int(max_size[:-2]) * 10**3 + # Note: pickle adds some junk so the weight of the file can end up being slightly bigger than + # the size asked for (since we count parameters) + if size >= max_size_int + 50000: + with open(shard_file, "rb") as state_f: + state_file = from_bytes(FlaxBertModel, state_f.read()) + self.assertEqual(len(state_file), 1) + + # Check the index and the shard files found match + with open(index_file, "r", encoding="utf-8") as f: + index = json.loads(f.read()) + + all_shards = set(index["weight_map"].values()) + shards_found = {f for f in os.listdir(tmp_dir) if f.endswith(".msgpack")} + self.assertSetEqual(all_shards, shards_found) + + # Finally, check the model can be reloaded + new_model = FlaxBertModel.from_pretrained(tmp_dir) + for p1, p2 in zip(flatten_dict(model.params).values(), flatten_dict(new_model.params).values()): + self.assertTrue(np.allclose(np.array(p1), np.array(p2))) + + @is_pt_flax_cross_test + def test_from_sharded_pt(self): + model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded", from_pt=True) + ref_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-random-bert-fx-only") + for key, ref_val in flatten_dict(ref_model.params).items(): + val = flatten_dict(model.params)[key] + assert np.allclose(np.array(val), np.array(ref_val)) + + def test_gradient_checkpointing(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + # prepare inputs + prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + remat_model = model_class(config) + + try: + remat_model.enable_gradient_checkpointing() + except NotImplementedError: + continue + + outputs = model(**prepared_inputs_dict) + remat_outputs = remat_model(**prepared_inputs_dict) + + # ensure that the dicts of outputs contain the same keys + self.assertEqual(outputs.keys(), remat_outputs.keys()) + + outputs = outputs.to_tuple() + remat_outputs = remat_outputs.to_tuple() + + # ensure that the outputs remain precisely equal + for output, remat_output in zip(outputs, remat_outputs): + self.assertTrue((output == remat_output).all()) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_flax_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_flax_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e668b43532585ac9ebe1e13ed7f453da9979cf55 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_flax_utils.py @@ -0,0 +1,374 @@ +# 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 tempfile +import unittest + +import numpy as np +from huggingface_hub import HfFolder, delete_repo, snapshot_download +from requests.exceptions import HTTPError + +from transformers import BertConfig, BertModel, is_flax_available, is_torch_available +from transformers.testing_utils import ( + TOKEN, + USER, + is_pt_flax_cross_test, + is_staging_test, + require_flax, + require_safetensors, + require_torch, +) +from transformers.utils import FLAX_WEIGHTS_NAME, SAFE_WEIGHTS_NAME + + +if is_flax_available(): + import os + + from flax.core.frozen_dict import unfreeze + from flax.traverse_util import flatten_dict + + from transformers import FlaxBertModel + + os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.12" # assumed parallelism: 8 + + +@require_flax +@is_staging_test +class FlaxModelPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + try: + delete_repo(token=cls._token, repo_id="test-model-flax") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="valid_org/test-model-flax-org") + except HTTPError: + pass + + def test_push_to_hub(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = FlaxBertModel(config) + model.push_to_hub("test-model-flax", token=self._token) + + new_model = FlaxBertModel.from_pretrained(f"{USER}/test-model-flax") + + base_params = flatten_dict(unfreeze(model.params)) + new_params = flatten_dict(unfreeze(new_model.params)) + + for key in base_params.keys(): + max_diff = (base_params[key] - new_params[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # Reset repo + delete_repo(token=self._token, repo_id="test-model-flax") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, repo_id="test-model-flax", push_to_hub=True, token=self._token) + + new_model = FlaxBertModel.from_pretrained(f"{USER}/test-model-flax") + + base_params = flatten_dict(unfreeze(model.params)) + new_params = flatten_dict(unfreeze(new_model.params)) + + for key in base_params.keys(): + max_diff = (base_params[key] - new_params[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + def test_push_to_hub_in_organization(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = FlaxBertModel(config) + model.push_to_hub("valid_org/test-model-flax-org", token=self._token) + + new_model = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org") + + base_params = flatten_dict(unfreeze(model.params)) + new_params = flatten_dict(unfreeze(new_model.params)) + + for key in base_params.keys(): + max_diff = (base_params[key] - new_params[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + # Reset repo + delete_repo(token=self._token, repo_id="valid_org/test-model-flax-org") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained( + tmp_dir, repo_id="valid_org/test-model-flax-org", push_to_hub=True, token=self._token + ) + + new_model = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org") + + base_params = flatten_dict(unfreeze(model.params)) + new_params = flatten_dict(unfreeze(new_model.params)) + + for key in base_params.keys(): + max_diff = (base_params[key] - new_params[key]).sum().item() + self.assertLessEqual(max_diff, 1e-3, msg=f"{key} not identical") + + +def check_models_equal(model1, model2): + models_are_equal = True + flat_params_1 = flatten_dict(model1.params) + flat_params_2 = flatten_dict(model2.params) + for key in flat_params_1.keys(): + if np.sum(np.abs(flat_params_1[key] - flat_params_2[key])) > 1e-4: + models_are_equal = False + + return models_are_equal + + +@require_flax +class FlaxModelUtilsTest(unittest.TestCase): + def test_model_from_pretrained_subfolder(self): + config = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + model = FlaxBertModel(config) + + subfolder = "bert" + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(os.path.join(tmp_dir, subfolder)) + + with self.assertRaises(OSError): + _ = FlaxBertModel.from_pretrained(tmp_dir) + + model_loaded = FlaxBertModel.from_pretrained(tmp_dir, subfolder=subfolder) + + self.assertTrue(check_models_equal(model, model_loaded)) + + def test_model_from_pretrained_subfolder_sharded(self): + config = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + model = FlaxBertModel(config) + + subfolder = "bert" + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(os.path.join(tmp_dir, subfolder), max_shard_size="10KB") + + with self.assertRaises(OSError): + _ = FlaxBertModel.from_pretrained(tmp_dir) + + model_loaded = FlaxBertModel.from_pretrained(tmp_dir, subfolder=subfolder) + + self.assertTrue(check_models_equal(model, model_loaded)) + + def test_model_from_pretrained_hub_subfolder(self): + subfolder = "bert" + model_id = "hf-internal-testing/tiny-random-bert-subfolder" + + with self.assertRaises(OSError): + _ = FlaxBertModel.from_pretrained(model_id) + + model = FlaxBertModel.from_pretrained(model_id, subfolder=subfolder) + + self.assertIsNotNone(model) + + def test_model_from_pretrained_hub_subfolder_sharded(self): + subfolder = "bert" + model_id = "hf-internal-testing/tiny-random-bert-sharded-subfolder" + with self.assertRaises(OSError): + _ = FlaxBertModel.from_pretrained(model_id) + + model = FlaxBertModel.from_pretrained(model_id, subfolder=subfolder) + + self.assertIsNotNone(model) + + @require_safetensors + def test_safetensors_save_and_load(self): + model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + + # No msgpack file, only a model.safetensors + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, FLAX_WEIGHTS_NAME))) + + new_model = FlaxBertModel.from_pretrained(tmp_dir) + + self.assertTrue(check_models_equal(model, new_model)) + + @require_flax + @require_torch + @is_pt_flax_cross_test + def test_safetensors_save_and_load_pt_to_flax(self): + model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-random-bert", from_pt=True) + pt_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + with tempfile.TemporaryDirectory() as tmp_dir: + pt_model.save_pretrained(tmp_dir) + + # Check we have a model.safetensors file + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + + new_model = FlaxBertModel.from_pretrained(tmp_dir) + + # Check models are equal + self.assertTrue(check_models_equal(model, new_model)) + + @require_safetensors + def test_safetensors_load_from_hub(self): + """ + This test checks that we can load safetensors from a checkpoint that only has those on the Hub + """ + flax_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + + # Can load from the Flax-formatted checkpoint + safetensors_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-safetensors-only") + self.assertTrue(check_models_equal(flax_model, safetensors_model)) + + @require_safetensors + def test_safetensors_load_from_local(self): + """ + This test checks that we can load safetensors from a checkpoint that only has those on the Hub + """ + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-flax-only", cache_dir=tmp) + flax_model = FlaxBertModel.from_pretrained(location) + + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-flax-safetensors-only", cache_dir=tmp) + safetensors_model = FlaxBertModel.from_pretrained(location) + + self.assertTrue(check_models_equal(flax_model, safetensors_model)) + + @require_torch + @require_safetensors + @is_pt_flax_cross_test + def test_safetensors_load_from_hub_from_safetensors_pt(self): + """ + This test checks that we can load safetensors from a checkpoint that only has those on the Hub. + saved in the "pt" format. + """ + flax_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-msgpack") + + # Can load from the PyTorch-formatted checkpoint + safetensors_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors") + self.assertTrue(check_models_equal(flax_model, safetensors_model)) + + @require_torch + @require_safetensors + @is_pt_flax_cross_test + def test_safetensors_load_from_local_from_safetensors_pt(self): + """ + This test checks that we can load safetensors from a checkpoint that only has those on the Hub. + saved in the "pt" format. + """ + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-msgpack", cache_dir=tmp) + flax_model = FlaxBertModel.from_pretrained(location) + + # Can load from the PyTorch-formatted checkpoint + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors", cache_dir=tmp) + safetensors_model = FlaxBertModel.from_pretrained(location) + + self.assertTrue(check_models_equal(flax_model, safetensors_model)) + + @require_safetensors + def test_safetensors_load_from_hub_from_safetensors_pt_without_torch_installed(self): + """ + This test checks that we cannot load safetensors from a checkpoint that only has safetensors + saved in the "pt" format if torch isn't installed. + """ + if is_torch_available(): + # This test verifies that a correct error message is shown when loading from a pt safetensors + # PyTorch shouldn't be installed for this to work correctly. + return + + # Cannot load from the PyTorch-formatted checkpoint without PyTorch installed + with self.assertRaises(ModuleNotFoundError): + _ = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors") + + @require_safetensors + def test_safetensors_load_from_local_from_safetensors_pt_without_torch_installed(self): + """ + This test checks that we cannot load safetensors from a checkpoint that only has safetensors + saved in the "pt" format if torch isn't installed. + """ + if is_torch_available(): + # This test verifies that a correct error message is shown when loading from a pt safetensors + # PyTorch shouldn't be installed for this to work correctly. + return + + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors", cache_dir=tmp) + + # Cannot load from the PyTorch-formatted checkpoint without PyTorch installed + with self.assertRaises(ModuleNotFoundError): + _ = FlaxBertModel.from_pretrained(location) + + @require_safetensors + def test_safetensors_load_from_hub_msgpack_before_safetensors(self): + """ + This test checks that we'll first download msgpack weights before safetensors + The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch + """ + FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors-msgpack") + + @require_safetensors + def test_safetensors_load_from_local_msgpack_before_safetensors(self): + """ + This test checks that we'll first download msgpack weights before safetensors + The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch + """ + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors-msgpack", cache_dir=tmp) + FlaxBertModel.from_pretrained(location) + + @require_safetensors + def test_safetensors_flax_from_flax(self): + model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + new_model = FlaxBertModel.from_pretrained(tmp_dir) + + self.assertTrue(check_models_equal(model, new_model)) + + @require_safetensors + @require_torch + def test_safetensors_flax_from_torch(self): + hub_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + new_model = FlaxBertModel.from_pretrained(tmp_dir) + + self.assertTrue(check_models_equal(hub_model, new_model)) + + @require_safetensors + def test_safetensors_flax_from_sharded_msgpack_with_sharded_safetensors_local(self): + with tempfile.TemporaryDirectory() as tmp_dir: + path = snapshot_download( + "hf-internal-testing/tiny-bert-flax-safetensors-msgpack-sharded", cache_dir=tmp_dir + ) + + # This should not raise even if there are two types of sharded weights + FlaxBertModel.from_pretrained(path) + + @require_safetensors + def test_safetensors_flax_from_sharded_msgpack_with_sharded_safetensors_hub(self): + # This should not raise even if there are two types of sharded weights + # This should discard the safetensors weights in favor of the msgpack sharded weights + FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-safetensors-msgpack-sharded") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_tf_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_tf_common.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac744263cc023f7a50ff135507831cf2fd7ea50 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_tf_common.py @@ -0,0 +1,1873 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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. + + +from __future__ import annotations + +import copy +import inspect +import json +import os +import random +import tempfile +import unittest +from importlib import import_module +from math import isnan +from typing import List, Tuple + +from datasets import Dataset + +from transformers import is_tf_available, is_torch_available +from transformers.models.auto import get_values +from transformers.testing_utils import ( # noqa: F401 + CaptureLogger, + _tf_gpu_memory_limit, + is_pt_tf_cross_test, + require_tf, + require_tf2onnx, + slow, + torch_device, +) +from transformers.utils import CONFIG_NAME, GENERATION_CONFIG_NAME, logging +from transformers.utils.generic import ModelOutput + + +logger = logging.get_logger(__name__) + + +if is_tf_available(): + import numpy as np + import tensorflow as tf + + from transformers import ( + TF_MODEL_FOR_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, + TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, + TF_MODEL_FOR_MASKED_LM_MAPPING, + TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, + TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, + TF_MODEL_FOR_PRETRAINING_MAPPING, + TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, + TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING, + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING, + TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + TFAutoModel, + TFAutoModelForSequenceClassification, + TFSharedEmbeddings, + ) + from transformers.generation import ( + TFBeamSampleDecoderOnlyOutput, + TFBeamSampleEncoderDecoderOutput, + TFBeamSearchDecoderOnlyOutput, + TFBeamSearchEncoderDecoderOutput, + TFGreedySearchDecoderOnlyOutput, + TFGreedySearchEncoderDecoderOutput, + TFSampleDecoderOnlyOutput, + TFSampleEncoderDecoderOutput, + ) + + tf.config.experimental.enable_tensor_float_32_execution(False) + + if _tf_gpu_memory_limit is not None: + gpus = tf.config.list_physical_devices("GPU") + for gpu in gpus: + # Restrict TensorFlow to only allocate x GB of memory on the GPUs + try: + tf.config.set_logical_device_configuration( + gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)] + ) + logical_gpus = tf.config.list_logical_devices("GPU") + print("Logical GPUs", logical_gpus) + except RuntimeError as e: + # Virtual devices must be set before GPUs have been initialized + print(e) + +if is_torch_available(): + import torch + + +def _config_zero_init(config): + configs_no_init = copy.deepcopy(config) + for key in configs_no_init.__dict__.keys(): + if "_range" in key or "_std" in key: + setattr(configs_no_init, key, 0.0) + return configs_no_init + + +@require_tf +class TFModelTesterMixin: + model_tester = None + all_model_classes = () + all_generative_model_classes = () + test_mismatched_shapes = True + test_resize_embeddings = True + test_head_masking = True + is_encoder_decoder = False + has_attentions = True + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False) -> dict: + inputs_dict = copy.deepcopy(inputs_dict) + + if model_class in get_values(TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING): + inputs_dict = { + k: tf.tile(tf.expand_dims(v, 1), (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)) + if isinstance(v, tf.Tensor) and v.ndim > 0 + else v + for k, v in inputs_dict.items() + } + + if return_labels: + if model_class in get_values(TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING): + inputs_dict["labels"] = tf.ones(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in [ + *get_values(TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING), + *get_values(TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING), + ]: + inputs_dict["start_positions"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + inputs_dict["end_positions"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in [ + *get_values(TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING), + *get_values(TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING), + ]: + inputs_dict["labels"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in get_values(TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING): + inputs_dict["next_sentence_label"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in [ + *get_values(TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING), + *get_values(TF_MODEL_FOR_CAUSAL_LM_MAPPING), + *get_values(TF_MODEL_FOR_MASKED_LM_MAPPING), + *get_values(TF_MODEL_FOR_PRETRAINING_MAPPING), + *get_values(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING), + *get_values(TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING), + ] and "labels" in dict(inspect.signature(model_class.call).parameters): + inputs_dict["labels"] = tf.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=tf.int32 + ) + elif model_class in get_values(TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING): + num_patches = self.model_tester.image_size // self.model_tester.patch_size + inputs_dict["bool_masked_pos"] = tf.zeros( + (self.model_tester.batch_size, num_patches**2), dtype=tf.int32 + ) + elif model_class in get_values(TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING): + batch_size, num_channels, height, width = inputs_dict["pixel_values"].shape + inputs_dict["labels"] = tf.zeros((self.model_tester.batch_size, height, width), dtype=tf.int32) + elif model_class.__name__.endswith("ForCTC"): + # When we have enough CTC models for an AutoClass, we should use their mapping instead of name checks + inputs_dict["labels"] = tf.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=tf.int32 + ) + + return inputs_dict + + def test_initialization(self): + pass + + def test_save_load(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, saved_model=False) + + # the config file (and the generation config file, if it can generate) should be saved + self.assertTrue(os.path.exists(os.path.join(tmpdirname, CONFIG_NAME))) + self.assertEqual( + model.can_generate(), os.path.exists(os.path.join(tmpdirname, GENERATION_CONFIG_NAME)) + ) + + model = model_class.from_pretrained(tmpdirname) + after_outputs = model(self._prepare_for_class(inputs_dict, model_class)) + + self.assert_outputs_same(after_outputs, outputs) + + def test_save_load_config(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + model_config = model.get_config() + # make sure that returned config is jsonifiable, which is required by keras + json.dumps(model_config) + new_model = model_class.from_config(model.get_config()) + # make sure it also accepts a normal config + _ = model_class.from_config(model.config) + _ = new_model(self._prepare_for_class(inputs_dict, model_class)) # Build model + new_model.set_weights(model.get_weights()) + after_outputs = new_model(self._prepare_for_class(inputs_dict, model_class)) + + self.assert_outputs_same(after_outputs, outputs) + + @slow + def test_saved_model_creation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = False + config.output_attentions = False + + if hasattr(config, "use_cache"): + config.use_cache = False + + model_class = self.all_model_classes[0] + + class_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + model(class_inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, saved_model=True) + saved_model_dir = os.path.join(tmpdirname, "saved_model", "1") + self.assertTrue(os.path.exists(saved_model_dir)) + + def test_prepare_serving_output(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + for model_class in self.all_model_classes: + model = model_class(config) + inputs = self._prepare_for_class(inputs_dict, model_class) + outputs = model(inputs) + serving_outputs = model.serving_output(outputs) + + for k, v in serving_outputs.items(): + # Check that we have one of three possible outputs: None, tuple of tensors or a tensor + if isinstance(v, tuple): + self.assertTrue(all(isinstance(elem, tf.Tensor) for elem in v)) + elif v is not None: + self.assertIsInstance(v, tf.Tensor) + else: + self.assertIsNone(v) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.call) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + if model.config.is_encoder_decoder: + expected_arg_names = [ + "input_ids", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + ] + expected_arg_names.extend(["decoder_position_ids"] if "decoder_position_ids" in arg_names else []) + expected_arg_names.extend( + ["head_mask", "decoder_head_mask"] if "head_mask" and "decoder_head_mask" in arg_names else [] + ) + expected_arg_names.extend( + ["cross_attn_head_mask", "encoder_outputs"] + if "cross_attn_head_mask" in arg_names + else ["encoder_outputs"] + ) + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + else: + expected_arg_names = ["input_ids"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_onnx_compliancy(self): + if not self.test_onnx: + return + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + INTERNAL_OPS = [ + "Assert", + "AssignVariableOp", + "EmptyTensorList", + "ReadVariableOp", + "ResourceGather", + "TruncatedNormal", + "VarHandleOp", + "VarIsInitializedOp", + ] + onnx_ops = [] + + with open(os.path.join(".", "utils", "tf_ops", "onnx.json")) as f: + onnx_opsets = json.load(f)["opsets"] + + for i in range(1, self.onnx_min_opset + 1): + onnx_ops.extend(onnx_opsets[str(i)]) + + for model_class in self.all_model_classes: + model_op_names = set() + + with tf.Graph().as_default() as g: + model = model_class(config) + model.build() + + for op in g.get_operations(): + model_op_names.add(op.node_def.op) + + model_op_names = sorted(model_op_names) + incompatible_ops = [] + + for op in model_op_names: + if op not in onnx_ops and op not in INTERNAL_OPS: + incompatible_ops.append(op) + + self.assertEqual(len(incompatible_ops), 0, incompatible_ops) + + # `tf2onnx` issue page: https://github.com/onnx/tensorflow-onnx/issues/2172 + # TODO: undo skip once a fix is done in `tf2onnx` + @unittest.skip("`tf2onnx` broke with TF 2.13") + @require_tf2onnx + @slow + def test_onnx_runtime_optimize(self): + if not self.test_onnx: + return + + import onnxruntime + import tf2onnx + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes[:2]: + model = model_class(config) + model.build() + + onnx_model_proto, _ = tf2onnx.convert.from_keras(model, opset=self.onnx_min_opset) + + onnxruntime.InferenceSession(onnx_model_proto.SerializeToString()) + + def test_keras_save_load(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + tf_main_layer_classes = { + module_member + for model_class in self.all_model_classes + for module in (import_module(model_class.__module__),) + for module_member_name in dir(module) + if module_member_name.endswith("MainLayer") + # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. + and module_member_name[: -len("MainLayer")] == model_class.__name__[: -len("Model")] + for module_member in (getattr(module, module_member_name),) + if isinstance(module_member, type) + and tf.keras.layers.Layer in module_member.__bases__ + and getattr(module_member, "_keras_serializable", False) + } + for main_layer_class in tf_main_layer_classes: + # T5MainLayer needs an embed_tokens parameter when called without the inputs_embeds parameter + if "T5" in main_layer_class.__name__: + # Take the same values than in TFT5ModelTester for this shared layer + shared = TFSharedEmbeddings(99, 32, name="shared") + config.use_cache = inputs_dict.pop("use_cache", None) + main_layer = main_layer_class(config, embed_tokens=shared) + else: + main_layer = main_layer_class(config) + + symbolic_inputs = { + name: tf.keras.Input(tensor.shape[1:], dtype=tensor.dtype) for name, tensor in inputs_dict.items() + } + + model = tf.keras.Model(symbolic_inputs, outputs=main_layer(symbolic_inputs)) + outputs = model(inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + filepath = os.path.join(tmpdirname, "keras_model.h5") + model.save(filepath) + if "T5" in main_layer_class.__name__: + model = tf.keras.models.load_model( + filepath, + custom_objects={ + main_layer_class.__name__: main_layer_class, + "TFSharedEmbeddings": TFSharedEmbeddings, + }, + ) + else: + model = tf.keras.models.load_model( + filepath, custom_objects={main_layer_class.__name__: main_layer_class} + ) + assert isinstance(model, tf.keras.Model) + after_outputs = model(inputs_dict) + self.assert_outputs_same(after_outputs, outputs) + + def assert_outputs_same(self, after_outputs, outputs): + # Make sure we don't have nans + if isinstance(after_outputs, tf.Tensor): + out_1 = after_outputs.numpy() + elif isinstance(after_outputs, dict): + out_1 = after_outputs[list(after_outputs.keys())[0]].numpy() + else: + out_1 = after_outputs[0].numpy() + out_2 = outputs[0].numpy() + self.assertEqual(out_1.shape, out_2.shape) + out_1 = out_1[~np.isnan(out_1)] + out_2 = out_2[~np.isnan(out_2)] + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + # Don't copy this method to model specific test file! + # TODO: remove this method once the issues are all fixed! + def _make_attention_mask_non_null(self, inputs_dict): + """Make sure no sequence has all zeros as attention mask""" + + for k in ["attention_mask", "encoder_attention_mask", "decoder_attention_mask"]: + if k in inputs_dict: + attention_mask = inputs_dict[k] + + # Make sure no all 0s attention masks - to avoid failure at this moment. + # Put `1` at the beginning of sequences to make it still work when combining causal attention masks. + # TODO: remove this line once a fix regarding large negative values for attention mask is done. + attention_mask = tf.concat( + [tf.ones_like(attention_mask[:, :1], dtype=attention_mask.dtype), attention_mask[:, 1:]], axis=-1 + ) + + # Here we make the first sequence with all 0s as attention mask. + # Currently, this will fail for `TFWav2Vec2Model`. This is caused by the different large negative + # values, like `1e-4`, `1e-9`, `1e-30` and `-inf` for attention mask across models/frameworks. + # TODO: enable this block once the large negative values thing is cleaned up. + # (see https://github.com/huggingface/transformers/issues/14859) + # attention_mask = tf.concat( + # [ + # tf.zeros_like(attention_mask[:1], dtype=tf.int32), + # tf.cast(attention_mask[1:], dtype=tf.int32) + # ], + # axis=0 + # ) + + inputs_dict[k] = attention_mask + + # Don't copy this method to model specific test file! + # TODO: remove this method once the issues are all fixed! + def _postprocessing_to_ignore_test_cases(self, tf_outputs, pt_outputs, model_class): + """For temporarily ignoring some failed test cases (issues to be fixed)""" + + tf_keys = {k for k, v in tf_outputs.items() if v is not None} + pt_keys = {k for k, v in pt_outputs.items() if v is not None} + + key_differences = tf_keys.symmetric_difference(pt_keys) + + if model_class.__name__ in [ + "TFFlaubertWithLMHeadModel", + "TFFunnelForPreTraining", + "TFElectraForPreTraining", + "TFXLMWithLMHeadModel", + ]: + for k in key_differences: + if k in ["loss", "losses"]: + tf_keys.discard(k) + pt_keys.discard(k) + elif model_class.__name__.startswith("TFGPT2"): + # `TFGPT2` has `past_key_values` as a tensor while `GPT2` has it as a tuple. + tf_keys.discard("past_key_values") + pt_keys.discard("past_key_values") + + # create new outputs from the remaining fields + new_tf_outputs = type(tf_outputs)(**{k: tf_outputs[k] for k in tf_keys}) + new_pt_outputs = type(pt_outputs)(**{k: pt_outputs[k] for k in pt_keys}) + + return new_tf_outputs, new_pt_outputs + + def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None): + """Check the outputs from PyTorch and TensorFlow models are close enough. Checks are done in a recursive way. + + Args: + model_class: The class of the model that is currently testing. For example, `TFBertModel`, + TFBertForMaskedLM`, `TFBertForSequenceClassification`, etc. Mainly used for providing more informative + error messages. + name (`str`): The name of the output. For example, `output.hidden_states`, `output.attentions`, etc. + attributes (`Tuple[str]`): The names of the output's element if the output is a tuple/list with each element + being a named field in the output. + """ + + self.assertEqual(type(name), str) + if attributes is not None: + self.assertEqual(type(attributes), tuple, f"{name}: The argument `attributes` should be a `tuple`") + + # Allow `ModelOutput` (e.g. `CLIPOutput` has `text_model_output` and `vision_model_output`). + if isinstance(tf_outputs, ModelOutput): + self.assertTrue( + isinstance(pt_outputs, ModelOutput), + f"{name}: `pt_outputs` should an instance of `ModelOutput` when `tf_outputs` is", + ) + + # Don't copy this block to model specific test file! + # TODO: remove this method and this line after issues are fixed + tf_outputs, pt_outputs = self._postprocessing_to_ignore_test_cases(tf_outputs, pt_outputs, model_class) + + tf_keys = [k for k, v in tf_outputs.items() if v is not None] + pt_keys = [k for k, v in pt_outputs.items() if v is not None] + + self.assertEqual(tf_keys, pt_keys, f"{name}: Output keys differ between TF and PyTorch") + + # convert to the case of `tuple` + # appending each key to the current (string) `names` + attributes = tuple([f"{name}.{k}" for k in tf_keys]) + self.check_pt_tf_outputs( + tf_outputs.to_tuple(), pt_outputs.to_tuple(), model_class, tol=tol, name=name, attributes=attributes + ) + + # Allow `list` (e.g. `TransfoXLModelOutput.mems` is a list of tensors.) + elif type(tf_outputs) in [tuple, list]: + self.assertEqual(type(tf_outputs), type(pt_outputs), f"{name}: Output types differ between TF and PyTorch") + self.assertEqual(len(tf_outputs), len(pt_outputs), f"{name}: Output lengths differ between TF and PyTorch") + + if attributes is not None: + # case 1: each output has assigned name (e.g. a tuple form of a `ModelOutput`) + self.assertEqual( + len(attributes), + len(tf_outputs), + f"{name}: The tuple `names` should have the same length as `tf_outputs`", + ) + else: + # case 2: each output has no assigned name (e.g. hidden states of each layer) -> add an index to `names` + attributes = tuple([f"{name}_{idx}" for idx in range(len(tf_outputs))]) + + for tf_output, pt_output, attr in zip(tf_outputs, pt_outputs, attributes): + self.check_pt_tf_outputs(tf_output, pt_output, model_class, tol=tol, name=attr) + + elif isinstance(tf_outputs, tf.Tensor): + self.assertTrue( + isinstance(pt_outputs, torch.Tensor), f"{name}: `pt_outputs` should a tensor when `tf_outputs` is" + ) + + tf_outputs = tf_outputs.numpy() + pt_outputs = pt_outputs.detach().to("cpu").numpy() + + self.assertEqual( + tf_outputs.shape, pt_outputs.shape, f"{name}: Output shapes differ between TF and PyTorch" + ) + + # deal with NumPy's scalars to make replacing nan values by 0 work. + if np.isscalar(tf_outputs): + tf_outputs = np.array([tf_outputs]) + pt_outputs = np.array([pt_outputs]) + + tf_nans = np.isnan(tf_outputs) + pt_nans = np.isnan(pt_outputs) + + pt_outputs[tf_nans] = 0 + tf_outputs[tf_nans] = 0 + pt_outputs[pt_nans] = 0 + tf_outputs[pt_nans] = 0 + + max_diff = np.amax(np.abs(tf_outputs - pt_outputs)) + self.assertLessEqual(max_diff, tol, f"{name}: Difference between torch and tf is {max_diff} (>= {tol}).") + else: + raise ValueError( + "`tf_outputs` should be an instance of `tf.Tensor`, a `tuple`, or an instance of `tf.Tensor`. Got" + f" {type(tf_outputs)} instead." + ) + + def prepare_pt_inputs_from_tf_inputs(self, tf_inputs_dict): + pt_inputs_dict = {} + for name, key in tf_inputs_dict.items(): + if isinstance(key, bool): + pt_inputs_dict[name] = key + elif name == "input_values": + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.float32) + elif name == "pixel_values": + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.float32) + elif name == "input_features": + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.float32) + # other general float inputs + elif tf_inputs_dict[name].dtype.is_floating: + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.float32) + else: + pt_inputs_dict[name] = torch.from_numpy(key.numpy()).to(torch.long) + + return pt_inputs_dict + + def check_pt_tf_models(self, tf_model, pt_model, tf_inputs_dict): + pt_inputs_dict = self.prepare_pt_inputs_from_tf_inputs(tf_inputs_dict) + + # send pytorch inputs to the correct device + pt_inputs_dict = { + k: v.to(device=torch_device) if isinstance(v, torch.Tensor) else v for k, v in pt_inputs_dict.items() + } + + # send pytorch model to the correct device + pt_model.to(torch_device) + + # Check predictions on first output (logits/hidden-states) are close enough given low-level computational differences + pt_model.eval() + + with torch.no_grad(): + pt_outputs = pt_model(**pt_inputs_dict) + tf_outputs = tf_model(tf_inputs_dict) + + # tf models returned loss is usually a tensor rather than a scalar. + # (see `hf_compute_loss`: it uses `tf.keras.losses.Reduction.NONE`) + # Change it here to a scalar to match PyTorch models' loss + tf_loss = getattr(tf_outputs, "loss", None) + if tf_loss is not None: + tf_outputs.loss = tf.math.reduce_mean(tf_loss) + + self.check_pt_tf_outputs(tf_outputs, pt_outputs, type(tf_model)) + + @is_pt_tf_cross_test + def test_pt_tf_model_equivalence(self, allow_missing_keys=False): + import transformers + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # Output all for aggressive testing + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + # Make sure no sequence has all zeros as attention mask, otherwise some tests fail due to the inconsistency + # of the usage `1e-4`, `1e-9`, `1e-30`, `-inf`. + # TODO: Use a uniform value for all models, make sure all tests pass without this processing, and remove it. + self._make_attention_mask_non_null(inputs_dict) + + pt_model_class_name = model_class.__name__[2:] # Skip the "TF" at the beginning + pt_model_class = getattr(transformers, pt_model_class_name) + + tf_model = model_class(config) + pt_model = pt_model_class(config) + + tf_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + tf_inputs_dict_with_labels = self._prepare_for_class( + inputs_dict, + model_class, + # Not all models accept "labels" in the forward pass (yet :) ) + return_labels=True if "labels" in inspect.signature(model_class.call).parameters.keys() else False, + ) + + # For some models (e.g. base models), there is no label returned. + # Set the input dict to `None` to avoid check outputs twice for the same input dicts. + if not set(tf_inputs_dict_with_labels.keys()).symmetric_difference(tf_inputs_dict.keys()): + tf_inputs_dict_with_labels = None + + # Check we can load pt model in tf and vice-versa with model => model functions + tf_model = transformers.load_pytorch_model_in_tf2_model( + tf_model, pt_model, tf_inputs=tf_inputs_dict, allow_missing_keys=allow_missing_keys + ) + pt_model = transformers.load_tf2_model_in_pytorch_model( + pt_model, tf_model, allow_missing_keys=allow_missing_keys + ) + + # Original test: check without `labels` + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + # check with `labels` + if tf_inputs_dict_with_labels: + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict_with_labels) + + # Check we can load pt model in tf and vice-versa with checkpoint => model functions + with tempfile.TemporaryDirectory() as tmpdirname: + pt_checkpoint_path = os.path.join(tmpdirname, "pt_model.bin") + torch.save(pt_model.state_dict(), pt_checkpoint_path) + tf_model = transformers.load_pytorch_checkpoint_in_tf2_model( + tf_model, pt_checkpoint_path, allow_missing_keys=allow_missing_keys + ) + + tf_checkpoint_path = os.path.join(tmpdirname, "tf_model.h5") + tf_model.save_weights(tf_checkpoint_path) + pt_model = transformers.load_tf2_checkpoint_in_pytorch_model( + pt_model, tf_checkpoint_path, allow_missing_keys=allow_missing_keys + ) + + # Original test: check without `labels` + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict) + # check with `labels` + if tf_inputs_dict_with_labels: + self.check_pt_tf_models(tf_model, pt_model, tf_inputs_dict_with_labels) + + @slow + def test_compile_tf_model(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes[:2]: + # Prepare our model + model = model_class(config) + # These are maximally general inputs for the model, with multiple None dimensions + # Hopefully this will catch any conditionals that fail for flexible shapes + functional_inputs = { + key: tf.keras.Input(shape=val.shape[1:], dtype=val.dtype, name=key) + for key, val in model.input_signature.items() + if key in model.dummy_inputs + } + outputs_dict = model(functional_inputs) + + hidden_states = outputs_dict[0] + + # Compile extended model + functional_model = tf.keras.Model(inputs=functional_inputs, outputs=hidden_states) + model_out = functional_model.predict(model.dummy_inputs) # Check we can pass inputs with the Keras API + self.assertTrue(model_out is not None) + with tempfile.TemporaryDirectory() as tmpdirname: + functional_model.save(tmpdirname) # Ensure we can save/export the whole functional model + + def test_keyword_and_dict_args(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs_dict = model(inputs) + + inputs_keywords = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + outputs_keywords = model(**inputs_keywords) + output_dict = outputs_dict[0].numpy() + output_keywords = outputs_keywords[0].numpy() + + self.assertLess(np.sum(np.abs(output_dict - output_keywords)), 1e-6) + + def test_attention_outputs(self): + if not self.has_attentions: + self.skipTest(reason="Model does not output attentions") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", self.model_tester.seq_length) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", self.model_tester.seq_length) + decoder_key_length = getattr(self.model_tester, "key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + def check_decoder_attentions_output(outputs): + out_len = len(outputs) + self.assertEqual(min(out_len % 2, out_len % 5), 0) # differentiation due to newly added cross_attentions + decoder_attentions = outputs.decoder_attentions + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + def check_encoder_attentions_output(outputs): + attentions = [ + t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) + ] + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + out_len = len(outputs) + self.assertEqual(config.output_hidden_states, False) + check_encoder_attentions_output(outputs) + + if self.is_encoder_decoder: + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + self.assertEqual(config.output_hidden_states, False) + check_decoder_attentions_output(outputs) + + # Check that output attentions can also be changed via the config + del inputs_dict["output_attentions"] + config.output_attentions = True + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + self.assertEqual(config.output_hidden_states, False) + check_encoder_attentions_output(outputs) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + config.output_hidden_states = True + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + + self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1), len(outputs)) + self.assertEqual(model.config.output_hidden_states, True) + check_encoder_attentions_output(outputs) + + def test_headmasking(self): + if not self.test_head_masking: + return + + random.Random().seed(42) + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + random.Random().seed() + + inputs_dict["output_attentions"] = True + config.output_hidden_states = True + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + + # Prepare head_mask + def prepare_layer_head_mask(i, attention_heads, num_hidden_layers): + if i == 0: + return tf.concat( + (tf.zeros(1, dtype=tf.float32), tf.ones(attention_heads - 1, dtype=tf.float32)), 0 + ) + elif i == num_hidden_layers - 1: + return tf.concat( + (tf.zeros(attention_heads - 1, dtype=tf.float32), tf.ones(1, dtype=tf.float32)), 0 + ) + else: + return tf.ones(attention_heads, dtype=tf.float32) + + head_mask = tf.stack( + [ + prepare_layer_head_mask(i, config.num_attention_heads, config.num_hidden_layers) + for i in range(config.num_hidden_layers) + ], + 0, + ) + + inputs = self._prepare_for_class(inputs_dict, model_class).copy() + inputs["head_mask"] = head_mask + if model.config.is_encoder_decoder: + signature = inspect.signature(model.call) + arg_names = [*signature.parameters.keys()] + if "decoder_head_mask" in arg_names: # necessary diferentiation because of T5 model + inputs["decoder_head_mask"] = head_mask + if "cross_attn_head_mask" in arg_names: + inputs["cross_attn_head_mask"] = head_mask + + outputs = model(**inputs, return_dict=True) + + def check_attentions_validity(attentions): + # Remove Nan + for t in attentions: + self.assertLess( + (tf.math.reduce_sum(tf.cast(tf.math.is_nan(t), tf.float32))).numpy(), (tf.size(t) / 4).numpy() + ) # Check we don't have more than 25% nans (arbitrary) + + attentions = [ + tf.where(tf.math.is_nan(t), 0.0, t) for t in attentions + ] # remove them (the test is less complete) + + self.assertAlmostEqual(tf.math.reduce_sum(attentions[0][..., 0, :, :]).numpy(), 0.0) + self.assertNotEqual(tf.math.reduce_sum(attentions[0][..., -1, :, :]).numpy(), 0.0) + if len(attentions) > 2: # encoder-decodere models have only 2 layers in each modules + self.assertNotEqual(tf.math.reduce_sum(attentions[1][..., 0, :, :]).numpy(), 0.0) + self.assertAlmostEqual(tf.math.reduce_sum(attentions[-1][..., -2, :, :]).numpy(), 0.0) + self.assertNotEqual(tf.math.reduce_sum(attentions[-1][..., -1, :, :]).numpy(), 0.0) + + if model.config.is_encoder_decoder: + check_attentions_validity(outputs.encoder_attentions) + check_attentions_validity(outputs.decoder_attentions) + if "cross_attn_head_mask" in arg_names: + check_attentions_validity(outputs.cross_attentions) + else: + check_attentions_validity(outputs.attentions) + + def test_hidden_states_output(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_hidden_states_output(config, inputs_dict, model_class): + model = model_class(config) + outputs = model(self._prepare_for_class(inputs_dict, model_class)) + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + + if model.config.is_encoder_decoder: + encoder_hidden_states = outputs.encoder_hidden_states + decoder_hidden_states = outputs.decoder_hidden_states + + self.assertEqual(config.output_attentions, False) + self.assertEqual(len(encoder_hidden_states), expected_num_layers) + self.assertListEqual( + list(encoder_hidden_states[0].shape[-2:]), + [self.model_tester.seq_length, self.model_tester.hidden_size], + ) + self.assertEqual(len(decoder_hidden_states), expected_num_layers) + self.assertListEqual( + list(decoder_hidden_states[0].shape[-2:]), + [self.model_tester.seq_length, self.model_tester.hidden_size], + ) + else: + hidden_states = outputs.hidden_states + self.assertEqual(config.output_attentions, False) + self.assertEqual(len(hidden_states), expected_num_layers) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.seq_length, self.model_tester.hidden_size], + ) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(config, inputs_dict, model_class) + + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + check_hidden_states_output(config, inputs_dict, model_class) + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + text_in_text_out_models = ( + get_values(TF_MODEL_FOR_CAUSAL_LM_MAPPING) + + get_values(TF_MODEL_FOR_MASKED_LM_MAPPING) + + get_values(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING) + ) + speech_in_text_out_models = get_values(TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING) + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), tf.keras.layers.Layer) + + legacy_text_in_text_out = model.get_lm_head() is not None + if model_class in text_in_text_out_models or legacy_text_in_text_out: + out_embeddings = model.get_output_embeddings() + self.assertIsInstance(out_embeddings, tf.keras.layers.Layer) + bias = model.get_bias() + if bias is not None: + self.assertIsInstance(bias, dict) + for _, v in bias.items(): + self.assertIsInstance(v, tf.Variable) + elif model_class in speech_in_text_out_models: + out_embeddings = model.get_output_embeddings() + self.assertIsInstance(out_embeddings, tf.keras.layers.Layer) + bias = model.get_bias() + self.assertIsNone(bias) + else: + out_embeddings = model.get_output_embeddings() + assert out_embeddings is None + bias = model.get_bias() + self.assertIsNone(bias) + + def test_determinism(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + first, second = ( + model(self._prepare_for_class(inputs_dict, model_class), training=False)[0], + model(self._prepare_for_class(inputs_dict, model_class), training=False)[0], + ) + out_1 = first.numpy() + out_2 = second.numpy() + out_1 = out_1[~np.isnan(out_1)] + out_2 = out_2[~np.isnan(out_2)] + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + def test_model_outputs_equivalence(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): + tuple_output = model(tuple_inputs, return_dict=False, **additional_kwargs) + dict_output = model(dict_inputs, return_dict=True, **additional_kwargs).to_tuple() + + def recursive_check(tuple_object, dict_object): + if isinstance(tuple_object, (List, Tuple)): + for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif tuple_object is None: + return + else: + self.assertTrue( + all(tf.equal(tuple_object, dict_object)), + msg=( + "Tuple and dict output are not equal. Difference:" + f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}" + ), + ) + + recursive_check(tuple_output, dict_output) + + for model_class in self.all_model_classes: + model = model_class(config) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + if self.has_attentions: + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + # Not all models accept "labels" in the forward pass (yet :) ) + if "labels" in inspect.signature(model.call).parameters.keys(): + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + if self.has_attentions: + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence( + model, tuple_inputs, dict_inputs, {"output_hidden_states": True, "output_attentions": True} + ) + + def test_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + + inputs = copy.deepcopy(inputs_dict) + + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + del inputs["input_ids"] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + + if not self.is_encoder_decoder: + inputs["inputs_embeds"] = model.get_input_embeddings()(input_ids) + else: + inputs["inputs_embeds"] = model.get_input_embeddings()(encoder_input_ids) + inputs["decoder_inputs_embeds"] = model.get_input_embeddings()(decoder_input_ids) + + inputs = self._prepare_for_class(inputs, model_class) + + model(inputs) + + def test_numpy_arrays_inputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def prepare_numpy_arrays(inputs_dict): + inputs_np_dict = {} + for k, v in inputs_dict.items(): + if tf.is_tensor(v): + inputs_np_dict[k] = v.numpy() + else: + inputs_np_dict[k] = np.array(k) + + return inputs_np_dict + + for model_class in self.all_model_classes: + model = model_class(config) + + inputs = self._prepare_for_class(inputs_dict, model_class) + inputs_np = prepare_numpy_arrays(inputs) + + output_for_dict_input = model(inputs_np) + output_for_kw_input = model(**inputs_np) + self.assert_outputs_same(output_for_dict_input, output_for_kw_input) + + def test_valid_input_signature_and_dummies(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model = model_class(config) + call_args = inspect.signature(model.call).parameters + for key in model.input_signature: + self.assertIn(key, call_args) + for key in model.dummy_inputs: + self.assertIn(key, call_args) + + def test_resize_token_embeddings(self): + # TODO (joao): after the embeddings refactor is complete, rework this test so as to rely exclusively on + # tf.keras.layers.Embedding + + if not self.test_resize_embeddings: + return + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def _get_word_embedding_weight(model, embedding_layer): + if isinstance(embedding_layer, tf.keras.layers.Embedding): + # builds the embeddings layer + model.build() + return embedding_layer.embeddings + else: + return model._get_word_embedding_weight(embedding_layer) + + for model_class in self.all_model_classes: + for size in [config.vocab_size - 10, config.vocab_size + 10, None]: + # build the embeddings + model = model_class(config=copy.deepcopy(config)) # `resize_token_embeddings` mutates `config` + old_input_embeddings = _get_word_embedding_weight(model, model.get_input_embeddings()) + old_bias = model.get_bias() + old_output_embeddings = _get_word_embedding_weight(model, model.get_output_embeddings()) + # reshape the embeddings + model.resize_token_embeddings(size) + new_input_embeddings = _get_word_embedding_weight(model, model.get_input_embeddings()) + new_bias = model.get_bias() + new_output_embeddings = _get_word_embedding_weight(model, model.get_output_embeddings()) + + # check that the resized embeddings size matches the desired size. + assert_size = size if size is not None else config.vocab_size + self.assertEqual(new_input_embeddings.shape[0], assert_size) + + # check that weights remain the same after resizing + models_equal = True + for p1, p2 in zip(old_input_embeddings.value(), new_input_embeddings.value()): + if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0: + models_equal = False + self.assertTrue(models_equal) + + if old_bias is not None and new_bias is not None: + for old_weight, new_weight in zip(old_bias.values(), new_bias.values()): + self.assertEqual(new_weight.shape[-1], assert_size) + + models_equal = True + for p1, p2 in zip(tf.squeeze(old_weight), tf.squeeze(new_weight)): + if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0: + models_equal = False + self.assertTrue(models_equal) + + if old_output_embeddings is not None and new_output_embeddings is not None: + self.assertEqual(new_output_embeddings.shape[0], assert_size) + self.assertEqual(new_output_embeddings.shape[1], old_output_embeddings.shape[1]) + + models_equal = True + for p1, p2 in zip(old_output_embeddings.value(), new_output_embeddings.value()): + if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0: + models_equal = False + self.assertTrue(models_equal) + + # TODO (Joao): this test is not slow, but it's tagged as such to keep track of failures on the scheduled CI runs, + # while passing push CI. Fix the underlying issues and remove the tag. + @slow + def test_save_load_after_resize_token_embeddings(self): + if not self.test_resize_embeddings: + return + config, original_inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + # create a model with resized (expended) embeddings + new_tokens_size = 10 + old_total_size = config.vocab_size + new_total_size = old_total_size + new_tokens_size + model = model_class(config=copy.deepcopy(config)) # `resize_token_embeddings` mutates `config` + model.build() + model.resize_token_embeddings(new_total_size) + + # fetch the output for an input exclusively made of new members of the vocabulary + inputs_dict = copy.deepcopy(original_inputs_dict) + ids_feat_name = None + if "input_ids" in inputs_dict: + ids_feat_name = "input_ids" + elif "decoder_input_ids" in inputs_dict: + ids_feat_name = "decoder_input_ids" + else: + assert False, "No input ids feature found in the inputs dict" + + new_vocab_input_ids = ids_tensor(inputs_dict[ids_feat_name].shape, new_tokens_size) + new_vocab_input_ids += old_total_size + inputs_dict[ids_feat_name] = new_vocab_input_ids + if "input_ids" in inputs_dict: + inputs_dict["input_ids"] = new_vocab_input_ids + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"] = new_vocab_input_ids + prepared_inputs = self._prepare_for_class(inputs_dict, model_class) + outputs = model(**prepared_inputs) + + # save and load the model + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, saved_model=False) + model = model_class.from_pretrained(tmpdirname) + restored_model_outputs = model(**prepared_inputs) + + # check that the output for the restored model is the same + self.assert_outputs_same(restored_model_outputs, outputs) + + @unittest.skipIf( + not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0, + reason="This test always passes on CPU.", + ) + def test_embeddings_out_of_bounds_raise_exception(self): + # TF embeddings layers don't raise an exception when an index is out of bounds on GPU, so we manually raise it. + # This test should only fail on GPU for models where we haven't added the safety check. + if not self.test_resize_embeddings: + return + config, original_inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config=config) + inputs_dict = copy.deepcopy(original_inputs_dict) + if "input_ids" in inputs_dict: + inputs_dict["input_ids"] = inputs_dict["input_ids"] * int(1e9) + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"] = inputs_dict["decoder_input_ids"] * int(1e9) + prepared_inputs = self._prepare_for_class(inputs_dict, model_class) + with self.assertRaises(tf.errors.InvalidArgumentError): + model(**prepared_inputs) + + def test_lm_head_model_random_no_beam_search_generate(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_ids = inputs_dict.get("input_ids", None) + + # iterate over all generative models + for model_class in self.all_generative_model_classes: + model = model_class(config) + + if config.bos_token_id is None: + # if bos token id is not defined model needs input_ids + with self.assertRaises(ValueError): + model.generate(do_sample=True, max_length=5) + # num_return_sequences = 1 + self._check_generated_ids(model.generate(input_ids, do_sample=True)) + elif model_class.__name__ not in ["TFSpeech2TextForConditionalGeneration"]: + # Models with non-text inputs won't work here; num_return_sequences = 1 + self._check_generated_ids(model.generate(do_sample=True, max_length=5)) + + with self.assertRaises(ValueError): + # generating multiple sequences when no beam search generation + # is not allowed as it would always generate the same sequences + model.generate(input_ids, do_sample=False, num_return_sequences=2) + + # num_return_sequences > 1, sample + self._check_generated_ids(model.generate(input_ids, do_sample=True, num_return_sequences=2)) + + # check bad words tokens language generation + # create list of 1-seq bad token and list of 2-seq of bad tokens + bad_words_ids = [self._generate_random_bad_tokens(1, model), self._generate_random_bad_tokens(2, model)] + output_tokens = model.generate( + input_ids, do_sample=True, bad_words_ids=bad_words_ids, num_return_sequences=2 + ) + # only count generated tokens + generated_ids = output_tokens[:, input_ids.shape[-1] :] + self.assertFalse(self._check_match_tokens(generated_ids.numpy().tolist(), bad_words_ids)) + + def test_lm_head_model_no_beam_search_generate_dict_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_ids = inputs_dict.get("input_ids", None) + if input_ids is None: + input_ids = inputs_dict.get("input_features", None) + + # iterate over all generative models + for model_class in self.all_generative_model_classes: + model = model_class(config) + output_greedy = model.generate( + input_ids, + do_sample=False, + output_scores=True, + output_hidden_states=True, + output_attentions=True, + return_dict_in_generate=True, + ) + output_sample = model.generate( + input_ids, + do_sample=True, + output_scores=True, + output_hidden_states=True, + output_attentions=True, + return_dict_in_generate=True, + ) + + if model.config.is_encoder_decoder: + self.assertIsInstance(output_greedy, TFGreedySearchEncoderDecoderOutput) + self.assertIsInstance(output_sample, TFSampleEncoderDecoderOutput) + else: + self.assertIsInstance(output_greedy, TFGreedySearchDecoderOnlyOutput) + self.assertIsInstance(output_sample, TFSampleDecoderOnlyOutput) + + def test_lm_head_model_random_beam_search_generate(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_ids = inputs_dict.get("input_ids", None) + + for model_class in self.all_generative_model_classes: + model = model_class(config) + + if config.bos_token_id is None: + # if bos token id is not defined model needs input_ids, num_return_sequences = 1 + self._check_generated_ids(model.generate(input_ids, do_sample=True, num_beams=2)) + else: + # num_return_sequences = 1 + self._check_generated_ids(model.generate(do_sample=True, max_length=5, num_beams=2)) + + with self.assertRaises(ValueError): + # generating more sequences than having beams leads is not possible + model.generate(input_ids, do_sample=False, num_return_sequences=3, num_beams=2) + + # num_return_sequences > 1, sample + self._check_generated_ids( + model.generate( + input_ids, + do_sample=True, + num_beams=2, + num_return_sequences=2, + ) + ) + # num_return_sequences > 1, greedy + self._check_generated_ids(model.generate(input_ids, do_sample=False, num_beams=2, num_return_sequences=2)) + + # check bad words tokens language generation + # create list of 1-seq bad token and list of 2-seq of bad tokens + bad_words_ids = [self._generate_random_bad_tokens(1, model), self._generate_random_bad_tokens(2, model)] + output_tokens = model.generate( + input_ids, do_sample=False, bad_words_ids=bad_words_ids, num_beams=2, num_return_sequences=2 + ) + # only count generated tokens + generated_ids = output_tokens[:, input_ids.shape[-1] :] + self.assertFalse(self._check_match_tokens(generated_ids.numpy().tolist(), bad_words_ids)) + + def test_lm_head_model_beam_search_generate_dict_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + input_ids = inputs_dict.get("input_ids", None) + if input_ids is None: + input_ids = inputs_dict.get("input_features", None) + + # iterate over all generative models + for model_class in self.all_generative_model_classes: + model = model_class(config) + output_beam_search = model.generate( + input_ids, + num_beams=2, + do_sample=False, + output_scores=True, + output_hidden_states=True, + output_attentions=True, + return_dict_in_generate=True, + ) + output_beam_sample = model.generate( + input_ids, + num_beams=2, + do_sample=True, + output_scores=True, + output_hidden_states=True, + output_attentions=True, + return_dict_in_generate=True, + ) + + if model.config.is_encoder_decoder: + self.assertIsInstance(output_beam_search, TFBeamSearchEncoderDecoderOutput) + self.assertIsInstance(output_beam_sample, TFBeamSampleEncoderDecoderOutput) + else: + self.assertIsInstance(output_beam_search, TFBeamSearchDecoderOnlyOutput) + self.assertIsInstance(output_beam_sample, TFBeamSampleDecoderOnlyOutput) + + def test_loss_computation(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model = model_class(config) + # The number of elements in the loss should be the same as the number of elements in the label + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + added_label_names = sorted(prepared_for_class.keys() - inputs_dict.keys(), reverse=True) + if not added_label_names: + continue # This test is only for models with easily-separable labels + added_label = prepared_for_class[added_label_names[0]] + expected_loss_size = added_label.shape.as_list()[:1] + + # Test that model correctly compute the loss with kwargs + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + possible_input_names = {"input_ids", "pixel_values", "input_features", "input_values"} + input_name = possible_input_names.intersection(set(prepared_for_class)).pop() + model_input = prepared_for_class.pop(input_name) + + outputs = model(model_input, **prepared_for_class) + if not isinstance(outputs, ModelOutput) or not hasattr(outputs, "loss"): + continue + + loss = outputs.loss + self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]) + + # Test that model correctly compute the loss when we mask some positions + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + possible_input_names = {"input_ids", "pixel_values", "input_features", "input_values"} + input_name = possible_input_names.intersection(set(prepared_for_class)).pop() + model_input = prepared_for_class.pop(input_name) + if "labels" in prepared_for_class: + labels = prepared_for_class["labels"].numpy() + if len(labels.shape) > 1 and labels.shape[1] != 1: + labels[0] = -100 + prepared_for_class["labels"] = tf.convert_to_tensor(labels) + loss = model(model_input, **prepared_for_class)[0] + self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]) + self.assertTrue(not np.any(np.isnan(loss.numpy()))) + + # Test that model correctly compute the loss with a dict + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + loss = model(prepared_for_class)[0] + self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]) + + # Test that model correctly compute the loss with a tuple + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + + # Get keys that were added with the _prepare_for_class function + label_keys = prepared_for_class.keys() - inputs_dict.keys() + signature = inspect.signature(model.call).parameters + signature_names = list(signature.keys()) + + # Create a dictionary holding the location of the tensors in the tuple + tuple_index_mapping = {0: input_name} + for label_key in label_keys: + label_key_index = signature_names.index(label_key) + tuple_index_mapping[label_key_index] = label_key + sorted_tuple_index_mapping = sorted(tuple_index_mapping.items()) + # Initialize a list with their default values, update the values and convert to a tuple + list_input = [] + + for name in signature_names: + if name != "kwargs": + list_input.append(signature[name].default) + + for index, value in sorted_tuple_index_mapping: + list_input[index] = prepared_for_class[value] + + tuple_input = tuple(list_input) + + # Send to model + loss = model(tuple_input[:-1])[0] + + self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]) + + def check_keras_fit_results(self, val_loss1, val_loss2, atol=1e-2, rtol=1e-3): + self.assertTrue(np.allclose(val_loss1, val_loss2, atol=atol, rtol=rtol)) + + @slow + def test_keras_fit(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model = model_class(config) + # Test that model correctly compute the loss with kwargs + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + # We also remove "return_loss" as this is covered by the train_step when using fit() + prepared_for_class = { + key: val + for key, val in prepared_for_class.items() + if key not in ("head_mask", "decoder_head_mask", "cross_attn_head_mask", "return_loss") + } + if "labels" in prepared_for_class and "decoder_input_ids" in prepared_for_class: + del prepared_for_class["decoder_input_ids"] + + accuracy_classes = [ + "ForPreTraining", + "ForCausalLM", + "ForMaskedLM", + "ForQuestionAnswering", + "ForMultipleChoice", + "ForSequenceClassification", + "ForTokenClassification", + "ForNextSentencePrediction", + "LMHeadModel", + ] + for accuracy_class in accuracy_classes: + if model.__class__.__name__.endswith(accuracy_class): + metrics = [tf.keras.metrics.SparseCategoricalAccuracy()] + break + else: + metrics = [] + + if hasattr(self.model_tester, "batch_size"): + sample_weight = tf.convert_to_tensor([0.5] * self.model_tester.batch_size, dtype=tf.float32) + else: + sample_weight = None + # Build the model so we can get some constant weights and check outputs + outputs = model(prepared_for_class) + if getattr(outputs, "loss", None) is None: + continue + model_weights = model.get_weights() + + # Run eagerly to save some expensive compilation times + model.compile(optimizer=tf.keras.optimizers.SGD(0.0), run_eagerly=True, metrics=metrics) + # Make sure the model fits without crashing regardless of where we pass the labels + history1 = model.fit( + prepared_for_class, + validation_data=prepared_for_class, + sample_weight=sample_weight, + steps_per_epoch=1, + validation_steps=1, + shuffle=False, + ) + val_loss1 = history1.history["val_loss"][0] + self.assertTrue(not isnan(val_loss1)) + accuracy1 = {key: val[0] for key, val in history1.history.items() if key.endswith("accuracy")} + + possible_label_cols = { + "labels", + "label", + "label_ids", + "start_positions", + "start_position", + "end_positions", + "end_position", + "next_sentence_label", + } + label_names = possible_label_cols.intersection(set(prepared_for_class)) + if len(label_names) == 0: + # The next tests only make sense for models with separate inputs and labels, and do not make + # sense for models that don't clearly distinguish between the two (e.g. CLIP) + return + labels = {key: val for key, val in prepared_for_class.items() if key in label_names} + inputs_minus_labels = {key: val for key, val in prepared_for_class.items() if key not in label_names} + self.assertGreater(len(inputs_minus_labels), 0) + + # We reinitialize the model here even though our learning rate was zero + # because BatchNorm updates weights by means other than gradient descent. + model.set_weights(model_weights) + + history2 = model.fit( + inputs_minus_labels, + labels, + validation_data=(inputs_minus_labels, labels), + sample_weight=sample_weight, + steps_per_epoch=1, + validation_steps=1, + shuffle=False, + ) + val_loss2 = history2.history["val_loss"][0] + self.assertTrue(not isnan(val_loss2)) + accuracy2 = {key: val[0] for key, val in history2.history.items() if key.endswith("accuracy")} + self.check_keras_fit_results(val_loss1, val_loss2) + self.assertEqual(history1.history.keys(), history2.history.keys()) + for key in history1.history.keys(): + if not key.startswith("val_"): + self.assertTrue("val_" + key in history1.history.keys(), "Outputs differ in train/test step!") + if metrics: + self.assertTrue(len(accuracy1) == len(accuracy2) > 0, "Missing metrics!") + + def test_int_support(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + prepared_for_class = self._prepare_for_class( + inputs_dict.copy(), + model_class, + return_labels=True if "labels" in inspect.signature(model_class.call).parameters.keys() else False, + ) + if not any( + tensor.dtype.is_integer for tensor in prepared_for_class.values() if isinstance(tensor, tf.Tensor) + ): + return # No integer inputs means no need for this test + + prepared_for_class = { + key: tf.cast(tensor, tf.int64) if isinstance(tensor, tf.Tensor) and tensor.dtype.is_integer else tensor + for key, tensor in prepared_for_class.items() + } + model = model_class(config) + model(**prepared_for_class) # No assertion, we're just checking this doesn't throw an error + int32_prepared_for_class = { + key: tf.cast(tensor, tf.int32) if isinstance(tensor, tf.Tensor) and tensor.dtype.is_integer else tensor + for key, tensor in prepared_for_class.items() + } + model(**int32_prepared_for_class) # No assertion, we're just checking this doesn't throw an error + + # After testing that the model accepts all int inputs, confirm that its dummies are int32 + for key, tensor in model.dummy_inputs.items(): + self.assertTrue( + isinstance(tensor, tf.Tensor) or tf.keras.backend.is_keras_tensor(tensor), + "Dummy inputs should be tf.Tensor!", + ) + if tensor.dtype.is_integer: + self.assertTrue(tensor.dtype == tf.int32, "Integer dummy inputs should be tf.int32!") + + # Also confirm that the input_signature uses int32 + for key, tensor_spec in model.input_signature.items(): + if tensor_spec.dtype.is_integer: + self.assertTrue(tensor_spec.dtype == tf.int32, "Input signatures should use tf.int32 for ints!") + + def test_generate_with_headmasking(self): + attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"] + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_generative_model_classes: + model = model_class(config) + + # We want to test only encoder-decoder models + if not config.is_encoder_decoder: + continue + + head_masking = { + "head_mask": tf.zeros((config.encoder_layers, config.encoder_attention_heads)), + "decoder_head_mask": tf.zeros((config.decoder_layers, config.decoder_attention_heads)), + "cross_attn_head_mask": tf.zeros((config.decoder_layers, config.decoder_attention_heads)), + } + + signature = inspect.signature(model.call) + if set(head_masking.keys()) < {*signature.parameters.keys()}: + continue + + for attn_name, (name, mask) in zip(attention_names, head_masking.items()): + out = model.generate( + inputs_dict["input_ids"], + num_beams=1, + max_length=inputs_dict["input_ids"] + 5, + output_attentions=True, + return_dict_in_generate=True, + **{name: mask}, + ) + # We check the state of decoder_attentions and cross_attentions just from the last step + attn_weights = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] + self.assertEqual(sum([tf.reduce_sum(w).numpy() for w in attn_weights]), 0.0) + + def test_load_with_mismatched_shapes(self): + if not self.test_mismatched_shapes: + return + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class not in get_values(TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING): + continue + + with self.subTest(msg=f"Testing {model_class}"): + with tempfile.TemporaryDirectory() as tmp_dir: + model = model_class(config) + inputs = self._prepare_for_class(inputs_dict, model_class) + _ = model(**inputs) + model.save_pretrained(tmp_dir) + + # Fails when we don't set ignore_mismatched_sizes=True + with self.assertRaises(ValueError): + new_model = TFAutoModelForSequenceClassification.from_pretrained(tmp_dir, num_labels=42) + with self.assertRaises(ValueError): + new_model_without_prefix = TFAutoModel.from_pretrained(tmp_dir, vocab_size=10) + + logger = logging.get_logger("transformers.modeling_tf_utils") + with CaptureLogger(logger) as cl: + new_model = TFAutoModelForSequenceClassification.from_pretrained( + tmp_dir, num_labels=42, ignore_mismatched_sizes=True + ) + self.assertIn("the shapes did not match", cl.out) + + logits = new_model(**inputs).logits + self.assertEqual(logits.shape[1], 42) + + with CaptureLogger(logger) as cl: + new_model_without_prefix = TFAutoModel.from_pretrained( + tmp_dir, vocab_size=10, ignore_mismatched_sizes=True + ) + self.assertIn("the shapes did not match", cl.out) + + # Although Tf models always have a prefix pointing to `MainLayer`, + # we still add this "without prefix" test to keep a consistency between tf and pt tests. + input_ids = ids_tensor((2, 8), 10) + if self.is_encoder_decoder: + new_model_without_prefix(input_ids, decoder_input_ids=input_ids) + else: + new_model_without_prefix(input_ids) + + def test_model_main_input_name(self): + for model_class in self.all_model_classes: + model_signature = inspect.signature(getattr(model_class, "call")) + # The main input is the name of the argument after `self` + observed_main_input_name = list(model_signature.parameters.keys())[1] + self.assertEqual(model_class.main_input_name, observed_main_input_name) + + def test_dataset_conversion(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model = model_class(config) + tf_inputs_dict = self._prepare_for_class(inputs_dict, model_class, return_labels=False) + if "labels" in tf_inputs_dict: + return # This is some kinda funky decoder model that needs labels in its forward pass + tf_inputs_dict = { + key: val + for key, val in tf_inputs_dict.items() + if "head_mask" not in key and isinstance(val, tf.Tensor) + } + tf_inputs_dict["extra_unwanted_column"] = list(tf_inputs_dict.values())[0] # Use a random other tensor + input_dataset = Dataset.from_dict(tf_inputs_dict) + tf_dataset = model.prepare_tf_dataset( + input_dataset, batch_size=len(input_dataset), drop_remainder=False, shuffle=False + ) + test_batch = next(iter(tf_dataset)) + if isinstance(test_batch, tf.Tensor): + self.assertEqual(len(test_batch), len(input_dataset)) # Assert we didn't lose any data + elif isinstance(test_batch, dict): + # Assert we discarded the unwanted extra column but kept everything else + self.assertEqual(len(test_batch), len(input_dataset.features) - 1) + self.assertNotIn("extra_unwanted_column", test_batch) + for tensor in test_batch.values(): + self.assertTrue(isinstance(tensor, tf.Tensor)) + self.assertEqual(len(tensor), len(input_dataset)) # Assert we didn't lose any data + model(test_batch, training=False) + + if "labels" in inspect.signature(model_class.call).parameters.keys(): + tf_inputs_dict = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + if "labels" not in tf_inputs_dict: + return # This model isn't giving us labels after all, don't try training with it + tf_inputs_dict = {key: val for key, val in tf_inputs_dict.items() if "head_mask" not in key} + tf_inputs_dict["extra_unwanted_column"] = list(tf_inputs_dict.values())[0] # Use a random other tensor + input_dataset = Dataset.from_dict(tf_inputs_dict) + tf_dataset = model.prepare_tf_dataset( + input_dataset, batch_size=len(input_dataset), drop_remainder=False, shuffle=False + ) + test_batch, test_batch_labels = next(iter(tf_dataset)) + self.assertGreater(len(test_batch_labels), 0) # Assert the labels are present + feature_columns = 1 if isinstance(test_batch, tf.Tensor) else len(test_batch) + label_columns = 1 if isinstance(test_batch_labels, tf.Tensor) else len(test_batch_labels) + # Assert we discarded the unwanted extra column but kept everything else + self.assertEqual(feature_columns + label_columns, len(input_dataset.features) - 1) + if isinstance(test_batch, dict): + self.assertNotIn("extra_unwanted_column", test_batch) + if isinstance(test_batch_labels, dict): + self.assertNotIn("extra_unwanted_column", test_batch_labels) + model.compile(optimizer="sgd", run_eagerly=True) + model.train_on_batch(test_batch, test_batch_labels) + + def _test_xla_generate(self, **generate_kwargs): + def _generate_and_check_results(model, inputs_dict): + if "input_ids" in inputs_dict: + inputs = inputs_dict["input_ids"] + # make sure there are no pad tokens in prompt, which may trigger unwanted behavior + if model.generation_config.pad_token_id is not None: + if config.pad_token_id == 0: + new_pad_token = model.generation_config.pad_token_id + 1 + else: + new_pad_token = model.generation_config.pad_token_id - 1 + else: + new_pad_token = None + inputs = tf.where(inputs != model.generation_config.pad_token_id, inputs, new_pad_token) + elif "input_features" in inputs_dict: + inputs = inputs_dict["input_features"] + else: + raise ValueError("No valid generate input found in inputs_dict") + + generated = model.generate(inputs, **generate_kwargs).numpy() + generate_xla = tf.function(model.generate, jit_compile=True) + generated_xla = generate_xla(inputs, **generate_kwargs).numpy() + + # Due to numerical instability, let's fail the test only if there are more than 10% of input sequences give + # different outputs between XLA and non-XLA versions. If there are less than 10 examples, let's be strict + # and not allow any difference. + diff = [[], []] + for _generated, _generated_xla in zip(generated.tolist(), generated_xla.tolist()): + if _generated != _generated_xla: + diff[0].append(_generated) + diff[1].append(_generated_xla) + ratio = len(diff[0]) / len(generated) + if ratio > 0.1 or (len(diff[0]) > 0 and len(generated) < 10): + self.assertListEqual(diff[0], diff[1]) + + for model_class in self.all_generative_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.eos_token_id = None # Generate until max length + config.do_sample = False + + # fix config for models with additional sequence-length limiting settings + for var_name in ["max_position_embeddings", "max_target_positions"]: + attr = getattr(config, var_name, None) + if attr is not None and attr < generate_kwargs["max_new_tokens"]: + try: + setattr(config, var_name, generate_kwargs["max_new_tokens"]) + except NotImplementedError: + # xlnet will raise an exception when trying to set + # max_position_embeddings. + pass + + model = model_class(config) + + if model.supports_xla_generation: + _generate_and_check_results(model, inputs_dict) + else: + with self.assertRaises(ValueError): + _generate_and_check_results(model, inputs_dict) + + def test_xla_generate_fast(self): + """ + Basic quick test for generate-compatible classes that confirms that XLA-generated tokens are the same as their + non XLA counterparts. + + Either the model supports XLA generation and passes the inner test, or it raises an appropriate exception + """ + self._test_xla_generate(num_beams=1, num_return_sequences=1, max_new_tokens=3) + + @slow + def test_xla_generate_contrastive(self): + """ + Slow and challenging version of `test_xla_generate_fast` for contrastive search -- contrastive search directly + manipulates the model cache and other outputs, and this test ensures that they are in a valid format that is + also supported by XLA. + + Either the model supports XLA generation and passes the inner test, or it raises an appropriate exception + """ + self._test_xla_generate(num_beams=1, num_return_sequences=1, max_new_tokens=16, penalty_alpha=0.5, top_k=4) + + @slow + def test_xla_generate_slow(self): + """ + Slow and challenging version of `test_xla_generate_fast` -- this test asks for several long sequences using + beam search, with and without XLA. The two outputs should match, and a failure in this test indicates that the + model may need further analysis if it is to be used for XLA generation. + + Either the model supports XLA generation and passes the inner test, or it raises an appropriate exception + """ + self._test_xla_generate(num_beams=8, num_return_sequences=2, max_new_tokens=128) + + def _generate_random_bad_tokens(self, num_bad_tokens, model): + # special tokens cannot be bad tokens + special_tokens = [] + if model.config.bos_token_id is not None: + special_tokens.append(model.config.bos_token_id) + if model.config.pad_token_id is not None: + special_tokens.append(model.config.pad_token_id) + if model.config.eos_token_id is not None: + special_tokens.append(model.config.eos_token_id) + + # create random bad tokens that are not special tokens + bad_tokens = [] + while len(bad_tokens) < num_bad_tokens: + token = tf.squeeze(ids_tensor((1, 1), self.model_tester.vocab_size), 0).numpy()[0] + if token not in special_tokens: + bad_tokens.append(token) + return bad_tokens + + def _check_generated_ids(self, output_ids): + for token_id in output_ids[0].numpy().tolist(): + self.assertGreaterEqual(token_id, 0) + self.assertLess(token_id, self.model_tester.vocab_size) + + def _check_match_tokens(self, generated_ids, bad_words_ids): + # for all bad word tokens + for bad_word_ids in bad_words_ids: + # for all slices in batch + for generated_ids_slice in generated_ids: + # for all word idx + for i in range(len(bad_word_ids), len(generated_ids_slice)): + # if tokens match + if generated_ids_slice[i - len(bad_word_ids) : i] == bad_word_ids: + return True + return False + + +def ids_tensor(shape, vocab_size, rng=None, name=None, dtype=None): + """Creates a random int32 tensor of the shape within the vocab size.""" + if rng is None: + rng = random.Random() + + total_dims = 1 + for dim in shape: + total_dims *= dim + + values = [] + for _ in range(total_dims): + values.append(rng.randint(0, vocab_size - 1)) + + output = tf.constant(values, shape=shape, dtype=dtype if dtype is not None else tf.int32) + + return output + + +def random_attention_mask(shape, rng=None, name=None, dtype=None): + attn_mask = ids_tensor(shape, vocab_size=2, rng=None, name=None, dtype=dtype) + # make sure that at least one token is attended to for each batch + attn_mask = tf.concat([attn_mask[:, :-1], tf.ones_like(attn_mask[:, -1:], dtype=dtype)], axis=-1) + return attn_mask + + +def floats_tensor(shape, scale=1.0, rng=None, name=None, dtype=None): + """Creates a random float32 tensor""" + if rng is None: + rng = random.Random() + + total_dims = 1 + for dim in shape: + total_dims *= dim + + values = [] + for _ in range(total_dims): + values.append(rng.random() * scale) + + return tf.reshape(tf.constant(values, dtype=dtype if dtype is not None else tf.float32), shape=shape) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_tf_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_tf_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ccc3f1f5cef2f561761286c2b87fb48440b5dbe5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_tf_utils.py @@ -0,0 +1,729 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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. + + +from __future__ import annotations + +import inspect +import json +import os +import random +import tempfile +import unittest +import unittest.mock as mock + +from huggingface_hub import HfFolder, Repository, delete_repo, snapshot_download +from huggingface_hub.file_download import http_get +from requests.exceptions import HTTPError + +from transformers import is_tf_available, is_torch_available +from transformers.configuration_utils import PretrainedConfig +from transformers.testing_utils import ( # noqa: F401 + TOKEN, + USER, + CaptureLogger, + _tf_gpu_memory_limit, + is_pt_tf_cross_test, + is_staging_test, + require_safetensors, + require_tf, + require_torch, + slow, +) +from transformers.utils import SAFE_WEIGHTS_NAME, TF2_WEIGHTS_INDEX_NAME, TF2_WEIGHTS_NAME, logging + + +logger = logging.get_logger(__name__) + + +if is_tf_available(): + import h5py + import numpy as np + import tensorflow as tf + + from transformers import ( + BertConfig, + PreTrainedModel, + PushToHubCallback, + RagRetriever, + TFBertForMaskedLM, + TFBertForSequenceClassification, + TFBertModel, + TFPreTrainedModel, + TFRagModel, + ) + from transformers.modeling_tf_utils import tf_shard_checkpoint, unpack_inputs + from transformers.tf_utils import stable_softmax + + tf.config.experimental.enable_tensor_float_32_execution(False) + + if _tf_gpu_memory_limit is not None: + gpus = tf.config.list_physical_devices("GPU") + for gpu in gpus: + # Restrict TensorFlow to only allocate x GB of memory on the GPUs + try: + tf.config.set_logical_device_configuration( + gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)] + ) + logical_gpus = tf.config.list_logical_devices("GPU") + print("Logical GPUs", logical_gpus) + except RuntimeError as e: + # Virtual devices must be set before GPUs have been initialized + print(e) + +if is_torch_available(): + from transformers import BertModel + + +@require_tf +class TFModelUtilsTest(unittest.TestCase): + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + # This check we did call the fake head request + mock_head.assert_called() + + def test_load_from_one_file(self): + try: + tmp_file = tempfile.mktemp() + with open(tmp_file, "wb") as f: + http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/tf_model.h5", f) + + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + _ = TFBertModel.from_pretrained(tmp_file, config=config) + finally: + os.remove(tmp_file) + + def test_legacy_load_from_url(self): + # This test is for deprecated behavior and can be removed in v5 + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + _ = TFBertModel.from_pretrained( + "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/tf_model.h5", config=config + ) + + # tests whether the unpack_inputs function behaves as expected + def test_unpack_inputs(self): + class DummyModel: + def __init__(self): + config_kwargs = {"output_attentions": False, "output_hidden_states": False, "return_dict": False} + self.config = PretrainedConfig(**config_kwargs) + self.main_input_name = "input_ids" + + @unpack_inputs + def call( + self, + input_ids=None, + past_key_values=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + ): + return input_ids, past_key_values, output_attentions, output_hidden_states, return_dict + + @unpack_inputs + def foo(self, pixel_values, output_attentions=None, output_hidden_states=None, return_dict=None): + return pixel_values, output_attentions, output_hidden_states, return_dict + + dummy_model = DummyModel() + input_ids = tf.constant([0, 1, 2, 3], dtype=tf.int32) + past_key_values = tf.constant([4, 5, 6, 7], dtype=tf.int32) + pixel_values = tf.constant([8, 9, 10, 11], dtype=tf.int32) + + # test case 1: Pass inputs as keyword arguments; Booleans are inherited from the config. + output = dummy_model.call(input_ids=input_ids, past_key_values=past_key_values) + tf.debugging.assert_equal(output[0], input_ids) + tf.debugging.assert_equal(output[1], past_key_values) + self.assertFalse(output[2]) + self.assertFalse(output[3]) + self.assertFalse(output[4]) + + # test case 2: Same as above, but with positional arguments. + output = dummy_model.call(input_ids, past_key_values) + tf.debugging.assert_equal(output[0], input_ids) + tf.debugging.assert_equal(output[1], past_key_values) + self.assertFalse(output[2]) + self.assertFalse(output[3]) + self.assertFalse(output[4]) + + # test case 3: We can also pack everything in the first input. + output = dummy_model.call(input_ids={"input_ids": input_ids, "past_key_values": past_key_values}) + tf.debugging.assert_equal(output[0], input_ids) + tf.debugging.assert_equal(output[1], past_key_values) + self.assertFalse(output[2]) + self.assertFalse(output[3]) + self.assertFalse(output[4]) + + # test case 4: Explicit boolean arguments should override the config. + output = dummy_model.call( + input_ids=input_ids, past_key_values=past_key_values, output_attentions=False, return_dict=True + ) + tf.debugging.assert_equal(output[0], input_ids) + tf.debugging.assert_equal(output[1], past_key_values) + self.assertFalse(output[2]) + self.assertFalse(output[3]) + self.assertTrue(output[4]) + + # test case 5: Unexpected arguments should raise an exception. + with self.assertRaises(ValueError): + output = dummy_model.call(input_ids=input_ids, past_key_values=past_key_values, foo="bar") + + # test case 6: the decorator is independent from `main_input_name` -- it treats the first argument of the + # decorated function as its main input. + output = dummy_model.foo(pixel_values=pixel_values) + tf.debugging.assert_equal(output[0], pixel_values) + self.assertFalse(output[1]) + self.assertFalse(output[2]) + self.assertFalse(output[3]) + + # Tests whether the stable softmax is stable on CPU, with and without XLA + def test_xla_stable_softmax(self): + large_penalty = -1e9 + n_tokens = 10 + batch_size = 8 + + def masked_softmax(x, boolean_mask): + numerical_mask = (1.0 - tf.cast(boolean_mask, dtype=tf.float32)) * large_penalty + masked_x = x + numerical_mask + return stable_softmax(masked_x) + + xla_masked_softmax = tf.function(masked_softmax, jit_compile=True) + xla_stable_softmax = tf.function(stable_softmax, jit_compile=True) + x = tf.random.normal((batch_size, n_tokens)) + + # Same outcome regardless of the boolean mask here + masked_tokens = random.randint(0, n_tokens) + boolean_mask = tf.convert_to_tensor([[1] * (n_tokens - masked_tokens) + [0] * masked_tokens], dtype=tf.int32) + + # We can randomly mask a random numerical input OUTSIDE XLA + numerical_mask = (1.0 - tf.cast(boolean_mask, dtype=tf.float32)) * large_penalty + masked_x = x + numerical_mask + xla_out = xla_stable_softmax(masked_x) + out = stable_softmax(masked_x) + assert tf.experimental.numpy.allclose(xla_out, out) + + # The stable softmax has the same output as the original softmax + unstable_out = tf.nn.softmax(masked_x) + assert tf.experimental.numpy.allclose(unstable_out, out) + + # We can randomly mask a random numerical input INSIDE XLA + xla_out = xla_masked_softmax(x, boolean_mask) + out = masked_softmax(x, boolean_mask) + assert tf.experimental.numpy.allclose(xla_out, out) + + def test_checkpoint_sharding_from_hub(self): + model = TFBertModel.from_pretrained("ArthurZ/tiny-random-bert-sharded") + # the model above is the same as the model below, just a sharded version. + ref_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + for p1, p2 in zip(model.weights, ref_model.weights): + assert np.allclose(p1.numpy(), p2.numpy()) + + def test_sharded_checkpoint_with_prefix(self): + model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert", load_weight_prefix="a/b") + sharded_model = TFBertModel.from_pretrained("ArthurZ/tiny-random-bert-sharded", load_weight_prefix="a/b") + for p1, p2 in zip(model.weights, sharded_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + self.assertTrue(p1.name.startswith("a/b/")) + self.assertTrue(p2.name.startswith("a/b/")) + + def test_sharded_checkpoint_transfer(self): + # If this doesn't throw an error then the test passes + TFBertForSequenceClassification.from_pretrained("ArthurZ/tiny-random-bert-sharded") + + @is_pt_tf_cross_test + def test_checkpoint_sharding_local_from_pt(self): + with tempfile.TemporaryDirectory() as tmp_dir: + _ = Repository(local_dir=tmp_dir, clone_from="hf-internal-testing/tiny-random-bert-sharded") + model = TFBertModel.from_pretrained(tmp_dir, from_pt=True) + # the model above is the same as the model below, just a sharded pytorch version. + ref_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + for p1, p2 in zip(model.weights, ref_model.weights): + assert np.allclose(p1.numpy(), p2.numpy()) + + @is_pt_tf_cross_test + def test_checkpoint_loading_with_prefix_from_pt(self): + model = TFBertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert", from_pt=True, load_weight_prefix="a/b" + ) + ref_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert", from_pt=True) + for p1, p2 in zip(model.weights, ref_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + self.assertTrue(p1.name.startswith("a/b/")) + + @is_pt_tf_cross_test + def test_checkpoint_sharding_hub_from_pt(self): + model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded", from_pt=True) + # the model above is the same as the model below, just a sharded pytorch version. + ref_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + for p1, p2 in zip(model.weights, ref_model.weights): + assert np.allclose(p1.numpy(), p2.numpy()) + + def test_shard_checkpoint(self): + # This is the model we will use, total size 340,000 bytes. + model = tf.keras.Sequential( + [ + tf.keras.layers.Dense(200, use_bias=False), # size 80,000 + tf.keras.layers.Dense(200, use_bias=False), # size 160,000 + tf.keras.layers.Dense(100, use_bias=False), # size 80,000 + tf.keras.layers.Dense(50, use_bias=False), # size 20,000 + ] + ) + inputs = tf.zeros((1, 100), dtype=tf.float32) + model(inputs) + weights = model.weights + weights_dict = {w.name: w for w in weights} + with self.subTest("No shard when max size is bigger than model size"): + shards, index = tf_shard_checkpoint(weights) + self.assertIsNone(index) + self.assertDictEqual(shards, {TF2_WEIGHTS_NAME: weights}) + + with self.subTest("Test sharding, no weights bigger than max size"): + shards, index = tf_shard_checkpoint(weights, max_shard_size="300kB") + # Split is first two layers then last two. + self.assertDictEqual( + index, + { + "metadata": {"total_size": 340000}, + "weight_map": { + "dense/kernel:0": "tf_model-00001-of-00002.h5", + "dense_1/kernel:0": "tf_model-00001-of-00002.h5", + "dense_2/kernel:0": "tf_model-00002-of-00002.h5", + "dense_3/kernel:0": "tf_model-00002-of-00002.h5", + }, + }, + ) + + shard1 = [weights_dict["dense/kernel:0"], weights_dict["dense_1/kernel:0"]] + shard2 = [weights_dict["dense_2/kernel:0"], weights_dict["dense_3/kernel:0"]] + self.assertDictEqual(shards, {"tf_model-00001-of-00002.h5": shard1, "tf_model-00002-of-00002.h5": shard2}) + + with self.subTest("Test sharding with weights bigger than max size"): + shards, index = tf_shard_checkpoint(weights, max_shard_size="100kB") + # Split is first layer, second layer then last 2. + self.assertDictEqual( + index, + { + "metadata": {"total_size": 340000}, + "weight_map": { + "dense/kernel:0": "tf_model-00001-of-00003.h5", + "dense_1/kernel:0": "tf_model-00002-of-00003.h5", + "dense_2/kernel:0": "tf_model-00003-of-00003.h5", + "dense_3/kernel:0": "tf_model-00003-of-00003.h5", + }, + }, + ) + + shard1 = [weights_dict["dense/kernel:0"]] + shard2 = [weights_dict["dense_1/kernel:0"]] + shard3 = [weights_dict["dense_2/kernel:0"], weights_dict["dense_3/kernel:0"]] + self.assertDictEqual( + shards, + { + "tf_model-00001-of-00003.h5": shard1, + "tf_model-00002-of-00003.h5": shard2, + "tf_model-00003-of-00003.h5": shard3, + }, + ) + + @slow + def test_special_layer_name_sharding(self): + retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True) + model = TFRagModel.from_pretrained("facebook/rag-token-nq", retriever=retriever) + + with tempfile.TemporaryDirectory() as tmp_dir: + for max_size in ["150kB", "150kiB", "200kB", "200kiB"]: + model.save_pretrained(tmp_dir, max_shard_size=max_size) + ref_model = TFRagModel.from_pretrained(tmp_dir, retriever=retriever) + for p1, p2 in zip(model.weights, ref_model.weights): + assert np.allclose(p1.numpy(), p2.numpy()) + + def test_checkpoint_sharding_local(self): + model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + # We use the same folder for various sizes to make sure a new save erases the old checkpoint. + for max_size in ["150kB", "150kiB", "200kB", "200kiB"]: + model.save_pretrained(tmp_dir, max_shard_size=max_size) + + # Get each shard file and its size + shard_to_size = {} + for shard in os.listdir(tmp_dir): + if shard.endswith(".h5"): + shard_file = os.path.join(tmp_dir, shard) + shard_to_size[shard_file] = os.path.getsize(shard_file) + + index_file = os.path.join(tmp_dir, TF2_WEIGHTS_INDEX_NAME) + # Check there is an index but no regular weight file + self.assertTrue(os.path.isfile(index_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, TF2_WEIGHTS_NAME))) + + # Check a file is bigger than max_size only when it has a single weight + for shard_file, size in shard_to_size.items(): + if max_size.endswith("kiB"): + max_size_int = int(max_size[:-3]) * 2**10 + else: + max_size_int = int(max_size[:-2]) * 10**3 + # Note: pickle adds some junk so the weight of the file can end up being slightly bigger than + # the size asked for (since we count parameters) + if size >= max_size_int + 50000: + with h5py.File(shard_file, "r") as state_file: + self.assertEqual(len(state_file), 1) + + # Check the index and the shard files found match + with open(index_file, "r", encoding="utf-8") as f: + index = json.loads(f.read()) + + all_shards = set(index["weight_map"].values()) + shards_found = {f for f in os.listdir(tmp_dir) if f.endswith(".h5")} + self.assertSetEqual(all_shards, shards_found) + + # Finally, check the model can be reloaded + new_model = TFBertModel.from_pretrained(tmp_dir) + + model.build() + new_model.build() + + for p1, p2 in zip(model.weights, new_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @slow + def test_save_pretrained_signatures(self): + model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Short custom TF signature function. + # `input_signature` is specific to BERT. + @tf.function( + input_signature=[ + [ + tf.TensorSpec([None, None], tf.int32, name="input_ids"), + tf.TensorSpec([None, None], tf.int32, name="token_type_ids"), + tf.TensorSpec([None, None], tf.int32, name="attention_mask"), + ] + ] + ) + def serving_fn(input): + return model(input) + + # Using default signature (default behavior) overrides 'serving_default' + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, saved_model=True, signatures=None) + model_loaded = tf.keras.models.load_model(f"{tmp_dir}/saved_model/1") + self.assertTrue("serving_default" in list(model_loaded.signatures.keys())) + + # Providing custom signature function + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, saved_model=True, signatures={"custom_signature": serving_fn}) + model_loaded = tf.keras.models.load_model(f"{tmp_dir}/saved_model/1") + self.assertTrue("custom_signature" in list(model_loaded.signatures.keys())) + + # Providing multiple custom signature function + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained( + tmp_dir, + saved_model=True, + signatures={"custom_signature_1": serving_fn, "custom_signature_2": serving_fn}, + ) + model_loaded = tf.keras.models.load_model(f"{tmp_dir}/saved_model/1") + self.assertTrue("custom_signature_1" in list(model_loaded.signatures.keys())) + self.assertTrue("custom_signature_2" in list(model_loaded.signatures.keys())) + + @require_safetensors + def test_safetensors_save_and_load(self): + model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + # No tf_model.h5 file, only a model.safetensors + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, TF2_WEIGHTS_NAME))) + + new_model = TFBertModel.from_pretrained(tmp_dir) + + # Check models are equal + for p1, p2 in zip(model.weights, new_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @is_pt_tf_cross_test + def test_safetensors_save_and_load_pt_to_tf(self): + model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + pt_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + with tempfile.TemporaryDirectory() as tmp_dir: + pt_model.save_pretrained(tmp_dir, safe_serialization=True) + # Check we have a model.safetensors file + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + + new_model = TFBertModel.from_pretrained(tmp_dir) + + # Check models are equal + for p1, p2 in zip(model.weights, new_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @require_safetensors + def test_safetensors_load_from_hub(self): + tf_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Can load from the TF-formatted checkpoint + safetensors_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert-safetensors-tf") + + # Check models are equal + for p1, p2 in zip(safetensors_model.weights, tf_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + # Can load from the PyTorch-formatted checkpoint + safetensors_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert-safetensors") + + # Check models are equal + for p1, p2 in zip(safetensors_model.weights, tf_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @require_safetensors + def test_safetensors_tf_from_tf(self): + model = TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-tf-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + new_model = TFBertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(model.weights, new_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @require_safetensors + @is_pt_tf_cross_test + def test_safetensors_tf_from_torch(self): + hub_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-tf-only") + model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + new_model = TFBertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(hub_model.weights, new_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @require_safetensors + def test_safetensors_tf_from_sharded_h5_with_sharded_safetensors_local(self): + with tempfile.TemporaryDirectory() as tmp_dir: + path = snapshot_download("hf-internal-testing/tiny-bert-tf-safetensors-h5-sharded", cache_dir=tmp_dir) + + # This should not raise even if there are two types of sharded weights + TFBertModel.from_pretrained(path) + + @require_safetensors + def test_safetensors_tf_from_sharded_h5_with_sharded_safetensors_hub(self): + # This should not raise even if there are two types of sharded weights + # This should discard the safetensors weights in favor of the .h5 sharded weights + TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-tf-safetensors-h5-sharded") + + @require_safetensors + def test_safetensors_load_from_local(self): + """ + This test checks that we can load safetensors from a checkpoint that only has those on the Hub + """ + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-tf-only", cache_dir=tmp) + tf_model = TFBertModel.from_pretrained(location) + + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-tf-safetensors-only", cache_dir=tmp) + safetensors_model = TFBertModel.from_pretrained(location) + + for p1, p2 in zip(tf_model.weights, safetensors_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @require_safetensors + def test_safetensors_load_from_hub_from_safetensors_pt(self): + """ + This test checks that we can load safetensors from a checkpoint that only has those on the Hub. + saved in the "pt" format. + """ + tf_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-h5") + + # Can load from the PyTorch-formatted checkpoint + safetensors_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors") + for p1, p2 in zip(tf_model.weights, safetensors_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @require_safetensors + def test_safetensors_load_from_local_from_safetensors_pt(self): + """ + This test checks that we can load safetensors from a local checkpoint that only has those + saved in the "pt" format. + """ + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-h5", cache_dir=tmp) + tf_model = TFBertModel.from_pretrained(location) + + # Can load from the PyTorch-formatted checkpoint + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors", cache_dir=tmp) + safetensors_model = TFBertModel.from_pretrained(location) + + for p1, p2 in zip(tf_model.weights, safetensors_model.weights): + self.assertTrue(np.allclose(p1.numpy(), p2.numpy())) + + @require_safetensors + def test_safetensors_load_from_hub_h5_before_safetensors(self): + """ + This test checks that we'll first download h5 weights before safetensors + The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch + """ + TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors-msgpack") + + @require_safetensors + def test_safetensors_load_from_local_h5_before_safetensors(self): + """ + This test checks that we'll first download h5 weights before safetensors + The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch + """ + with tempfile.TemporaryDirectory() as tmp: + location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors-msgpack", cache_dir=tmp) + TFBertModel.from_pretrained(location) + + +@require_tf +@is_staging_test +class TFModelPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + try: + delete_repo(token=cls._token, repo_id="test-model-tf") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="test-model-tf-callback") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="valid_org/test-model-tf-org") + except HTTPError: + pass + + def test_push_to_hub(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = TFBertModel(config) + # Make sure model is properly initialized + model.build() + + logging.set_verbosity_info() + logger = logging.get_logger("transformers.utils.hub") + with CaptureLogger(logger) as cl: + model.push_to_hub("test-model-tf", token=self._token) + logging.set_verbosity_warning() + # Check the model card was created and uploaded. + self.assertIn("Uploading the following files to __DUMMY_TRANSFORMERS_USER__/test-model-tf", cl.out) + + new_model = TFBertModel.from_pretrained(f"{USER}/test-model-tf") + models_equal = True + for p1, p2 in zip(model.weights, new_model.weights): + if not tf.math.reduce_all(p1 == p2): + models_equal = False + break + self.assertTrue(models_equal) + + # Reset repo + delete_repo(token=self._token, repo_id="test-model-tf") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, repo_id="test-model-tf", push_to_hub=True, token=self._token) + + new_model = TFBertModel.from_pretrained(f"{USER}/test-model-tf") + models_equal = True + for p1, p2 in zip(model.weights, new_model.weights): + if not tf.math.reduce_all(p1 == p2): + models_equal = False + break + self.assertTrue(models_equal) + + @is_pt_tf_cross_test + def test_push_to_hub_callback(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = TFBertForMaskedLM(config) + model.compile() + + with tempfile.TemporaryDirectory() as tmp_dir: + push_to_hub_callback = PushToHubCallback( + output_dir=tmp_dir, + hub_model_id="test-model-tf-callback", + hub_token=self._token, + ) + model.fit(model.dummy_inputs, model.dummy_inputs, epochs=1, callbacks=[push_to_hub_callback]) + + new_model = TFBertForMaskedLM.from_pretrained(f"{USER}/test-model-tf-callback") + models_equal = True + for p1, p2 in zip(model.weights, new_model.weights): + if not tf.math.reduce_all(p1 == p2): + models_equal = False + break + self.assertTrue(models_equal) + + tf_push_to_hub_params = dict(inspect.signature(TFPreTrainedModel.push_to_hub).parameters) + tf_push_to_hub_params.pop("base_model_card_args") + pt_push_to_hub_params = dict(inspect.signature(PreTrainedModel.push_to_hub).parameters) + pt_push_to_hub_params.pop("deprecated_kwargs") + self.assertDictEaual(tf_push_to_hub_params, pt_push_to_hub_params) + + def test_push_to_hub_in_organization(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = TFBertModel(config) + # Make sure model is properly initialized + model.build() + + model.push_to_hub("valid_org/test-model-tf-org", token=self._token) + + new_model = TFBertModel.from_pretrained("valid_org/test-model-tf-org") + models_equal = True + for p1, p2 in zip(model.weights, new_model.weights): + if not tf.math.reduce_all(p1 == p2): + models_equal = False + break + self.assertTrue(models_equal) + + # Reset repo + delete_repo(token=self._token, repo_id="valid_org/test-model-tf-org") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, push_to_hub=True, token=self._token, repo_id="valid_org/test-model-tf-org") + + new_model = TFBertModel.from_pretrained("valid_org/test-model-tf-org") + models_equal = True + for p1, p2 in zip(model.weights, new_model.weights): + if not tf.math.reduce_all(p1 == p2): + models_equal = False + break + self.assertTrue(models_equal) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfaad5214dc502b49b403668a396f086ef42ec4 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_modeling_utils.py @@ -0,0 +1,1852 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import copy +import glob +import json +import os +import os.path +import sys +import tempfile +import unittest +import unittest.mock as mock +import uuid +from pathlib import Path + +import requests +from huggingface_hub import HfApi, HfFolder, delete_repo +from huggingface_hub.file_download import http_get +from pytest import mark +from requests.exceptions import HTTPError + +from transformers import ( + AutoConfig, + AutoModel, + PretrainedConfig, + is_torch_available, + logging, +) +from transformers.testing_utils import ( + TOKEN, + USER, + CaptureLogger, + TestCasePlus, + is_staging_test, + require_accelerate, + require_flax, + require_safetensors, + require_tf, + require_torch, + require_torch_accelerator, + require_torch_multi_accelerator, + require_usr_bin_time, + slow, + torch_device, +) +from transformers.utils import ( + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, +) +from transformers.utils.import_utils import ( + is_flash_attn_2_available, + is_flax_available, + is_tf_available, + is_torch_sdpa_available, + is_torchdynamo_available, +) + + +sys.path.append(str(Path(__file__).parent.parent / "utils")) + +from test_module.custom_configuration import CustomConfig, NoSuperInitConfig # noqa E402 + + +if is_torch_available(): + import torch + from safetensors.torch import save_file as safe_save_file + from test_module.custom_modeling import CustomModel, NoSuperInitModel + from torch import nn + + from transformers import ( + BERT_PRETRAINED_MODEL_ARCHIVE_LIST, + AutoModelForCausalLM, + AutoTokenizer, + BertConfig, + BertModel, + CLIPTextModel, + PreTrainedModel, + T5Config, + T5ForConditionalGeneration, + ) + from transformers.modeling_attn_mask_utils import ( + AttentionMaskConverter, + _create_4d_causal_attention_mask, + _prepare_4d_attention_mask, + _prepare_4d_causal_attention_mask, + ) + from transformers.modeling_utils import shard_checkpoint + + # Fake pretrained models for tests + class BaseModel(PreTrainedModel): + base_model_prefix = "base" + config_class = PretrainedConfig + + def __init__(self, config): + super().__init__(config) + self.linear = nn.Linear(5, 5) + self.linear_2 = nn.Linear(5, 5) + + def forward(self, x): + return self.linear_2(self.linear(x)) + + class BaseModelWithTiedWeights(PreTrainedModel): + config_class = PretrainedConfig + + def __init__(self, config): + super().__init__(config) + self.linear = nn.Linear(5, 5) + self.linear_2 = nn.Linear(5, 5) + + def forward(self, x): + return self.linear_2(self.linear(x)) + + def tie_weights(self): + self.linear_2.weight = self.linear.weight + + class ModelWithHead(PreTrainedModel): + base_model_prefix = "base" + config_class = PretrainedConfig + + def _init_weights(self, module): + pass + + def __init__(self, config): + super().__init__(config) + self.base = BaseModel(config) + # linear is a common name between Base and Head on purpose. + self.linear = nn.Linear(5, 5) + self.linear2 = nn.Linear(5, 5) + + def forward(self, x): + return self.linear2(self.linear(self.base(x))) + + class ModelWithHeadAndTiedWeights(PreTrainedModel): + base_model_prefix = "base" + config_class = PretrainedConfig + + def _init_weights(self, module): + pass + + def __init__(self, config): + super().__init__(config) + self.base = BaseModel(config) + self.decoder = nn.Linear(5, 5) + + def forward(self, x): + return self.decoder(self.base(x)) + + def tie_weights(self): + self.decoder.weight = self.base.linear.weight + + class Prepare4dCausalAttentionMaskModel(nn.Module): + def forward(self, inputs_embeds): + batch_size, seq_length, _ = inputs_embeds.shape + past_key_values_length = 4 + attention_mask = _prepare_4d_causal_attention_mask( + None, (batch_size, seq_length), inputs_embeds, past_key_values_length + ) + return attention_mask + + class Create4dCausalAttentionMaskModel(nn.Module): + def forward(self, inputs_embeds): + batch_size, seq_length, _ = inputs_embeds.shape + past_key_values_length = 4 + attention_mask = _create_4d_causal_attention_mask( + (batch_size, seq_length), + dtype=inputs_embeds.dtype, + device=inputs_embeds.device, + past_key_values_length=past_key_values_length, + ) + return attention_mask + + class Prepare4dAttentionMaskModel(nn.Module): + def forward(self, mask, inputs_embeds): + attention_mask = _prepare_4d_attention_mask(mask, dtype=inputs_embeds.dtype) + return attention_mask + + +if is_flax_available(): + from transformers import FlaxBertModel + +if is_tf_available(): + from transformers import TFBertModel + + +TINY_T5 = "patrickvonplaten/t5-tiny-random" +TINY_BERT_FOR_TOKEN_CLASSIFICATION = "hf-internal-testing/tiny-bert-for-token-classification" + + +def check_models_equal(model1, model2): + models_are_equal = True + for model1_p, model2_p in zip(model1.parameters(), model2.parameters()): + if model1_p.data.ne(model2_p.data).sum() > 0: + models_are_equal = False + + return models_are_equal + + +@require_torch +class ModelUtilsTest(TestCasePlus): + @slow + def test_model_from_pretrained(self): + for model_name in BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: + config = BertConfig.from_pretrained(model_name) + self.assertIsNotNone(config) + self.assertIsInstance(config, PretrainedConfig) + + model = BertModel.from_pretrained(model_name) + model, loading_info = BertModel.from_pretrained(model_name, output_loading_info=True) + self.assertIsNotNone(model) + self.assertIsInstance(model, PreTrainedModel) + + self.assertEqual(len(loading_info["missing_keys"]), 0) + self.assertEqual(len(loading_info["unexpected_keys"]), 8) + self.assertEqual(len(loading_info["mismatched_keys"]), 0) + self.assertEqual(len(loading_info["error_msgs"]), 0) + + config = BertConfig.from_pretrained(model_name, output_attentions=True, output_hidden_states=True) + + # Not sure this is the intended behavior. TODO fix Lysandre & Thom + config.name_or_path = model_name + + model = BertModel.from_pretrained(model_name, output_attentions=True, output_hidden_states=True) + self.assertEqual(model.config.output_hidden_states, True) + self.assertEqual(model.config, config) + + def test_model_from_pretrained_subfolder(self): + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + model = BertModel(config) + + subfolder = "bert" + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(os.path.join(tmp_dir, subfolder)) + + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(tmp_dir) + + model_loaded = BertModel.from_pretrained(tmp_dir, subfolder=subfolder) + + self.assertTrue(check_models_equal(model, model_loaded)) + + def test_model_from_pretrained_subfolder_sharded(self): + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + model = BertModel(config) + + subfolder = "bert" + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(os.path.join(tmp_dir, subfolder), max_shard_size="10KB") + + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(tmp_dir) + + model_loaded = BertModel.from_pretrained(tmp_dir, subfolder=subfolder) + + self.assertTrue(check_models_equal(model, model_loaded)) + + def test_model_from_pretrained_hub_subfolder(self): + subfolder = "bert" + model_id = "hf-internal-testing/tiny-random-bert-subfolder" + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(model_id) + + model = BertModel.from_pretrained(model_id, subfolder=subfolder) + + self.assertIsNotNone(model) + + def test_model_from_pretrained_hub_subfolder_sharded(self): + subfolder = "bert" + model_id = "hf-internal-testing/tiny-random-bert-sharded-subfolder" + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(model_id) + + model = BertModel.from_pretrained(model_id, subfolder=subfolder) + + self.assertIsNotNone(model) + + def test_model_from_pretrained_with_different_pretrained_model_name(self): + model = T5ForConditionalGeneration.from_pretrained(TINY_T5) + self.assertIsNotNone(model) + + logger = logging.get_logger("transformers.configuration_utils") + with CaptureLogger(logger) as cl: + BertModel.from_pretrained(TINY_T5) + self.assertTrue("You are using a model of type t5 to instantiate a model of type bert" in cl.out) + + def test_model_from_config_torch_dtype(self): + # test that the model can be instantiated with dtype of user's choice - as long as it's a + # float dtype. To make it happen config.torch_dtype needs to be set before instantiating the + # model from the config object. + + config = T5Config.from_pretrained(TINY_T5) + model = AutoModel.from_config(config) + # XXX: isn't supported + # model = T5ForConditionalGeneration.from_config(config) + self.assertEqual(model.dtype, torch.float32) + + model = AutoModel.from_config(config, torch_dtype=torch.float16) + self.assertEqual(model.dtype, torch.float16) + + # torch.set_default_dtype() supports only float dtypes, so will fail with non-float type + with self.assertRaises(ValueError): + model = AutoModel.from_config(config, torch_dtype=torch.int64) + + def test_model_from_pretrained_torch_dtype(self): + # test that the model can be instantiated with dtype of either + # 1. explicit from_pretrained's torch_dtype argument + # 2. via autodiscovery by looking at model weights (torch_dtype="auto") + # so if a model.half() was saved, we want it to be instantiated as such. + # + # test an explicit model class, but also AutoModel separately as the latter goes through a different code path + model_path = self.get_auto_remove_tmp_dir() + + # baseline - we know TINY_T5 is fp32 model + model = T5ForConditionalGeneration.from_pretrained(TINY_T5) + self.assertEqual(model.dtype, torch.float32) + + def remove_torch_dtype(model_path): + file = f"{model_path}/config.json" + with open(file, "r", encoding="utf-8") as f: + s = json.load(f) + s.pop("torch_dtype") + with open(file, "w", encoding="utf-8") as f: + json.dump(s, f) + + # test the default fp32 save_pretrained => from_pretrained cycle + model.save_pretrained(model_path) + model = T5ForConditionalGeneration.from_pretrained(model_path) + self.assertEqual(model.dtype, torch.float32) + # 1. test torch_dtype="auto" via `config.torch_dtype` + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float32) + # 2. test torch_dtype="auto" via auto-derivation + # now remove the torch_dtype entry from config.json and try "auto" again which should + # perform auto-derivation from weights + remove_torch_dtype(model_path) + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float32) + + # test forced loading in fp16 (even though the weights are in fp32) + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype=torch.float16) + self.assertEqual(model.dtype, torch.float16) + + # test fp16 save_pretrained, loaded with auto-detection + model = model.half() + model.save_pretrained(model_path) + # 1. test torch_dtype="auto" via `config.torch_dtype` + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.config.torch_dtype, torch.float16) + self.assertEqual(model.dtype, torch.float16) + # tests `config.torch_dtype` saving + with open(f"{model_path}/config.json") as f: + config_dict = json.load(f) + self.assertEqual(config_dict["torch_dtype"], "float16") + # 2. test torch_dtype="auto" via auto-derivation + # now same with using config info + remove_torch_dtype(model_path) + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float16) + + # 3. now retest that AutoModel behaves the same wrt torch_dtype="auto" as T5ForConditionalGeneration + model = AutoModel.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float16) + + # test fp16 save_pretrained, loaded with the explicit fp16 + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype=torch.float16) + self.assertEqual(model.dtype, torch.float16) + + # test AutoModel separately as it goes through a different path + # test auto-detection - as currently TINY_T5 doesn't have torch_dtype entry + model = AutoModel.from_pretrained(TINY_T5, torch_dtype="auto") + # test that the config object didn't get polluted with torch_dtype="auto" + # there was a bug that after this call we ended up with config.torch_dtype=="auto" + self.assertNotEqual(model.config.torch_dtype, "auto") + # now test the outcome + self.assertEqual(model.dtype, torch.float32) + model = AutoModel.from_pretrained(TINY_T5, torch_dtype=torch.float16) + self.assertEqual(model.dtype, torch.float16) + + # test model whose first param is not of a floating type, but int + model = AutoModel.from_pretrained(TINY_BERT_FOR_TOKEN_CLASSIFICATION, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float32) + + def test_no_super_init_config_and_model(self): + config = NoSuperInitConfig(attribute=32) + model = NoSuperInitModel(config) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + new_model = NoSuperInitModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + def test_shard_checkpoint(self): + # This is the model we will use, total size 340,000 bytes. + model = torch.nn.Sequential( + torch.nn.Linear(100, 200, bias=False), # size 80,000 + torch.nn.Linear(200, 200, bias=False), # size 160,000 + torch.nn.Linear(200, 100, bias=False), # size 80,000 + torch.nn.Linear(100, 50, bias=False), # size 20,000 + ) + state_dict = model.state_dict() + + with self.subTest("No shard when max size is bigger than model size"): + shards, index = shard_checkpoint(state_dict) + self.assertIsNone(index) + self.assertDictEqual(shards, {WEIGHTS_NAME: state_dict}) + + with self.subTest("Test sharding, no weights bigger than max size"): + shards, index = shard_checkpoint(state_dict, max_shard_size="300kB") + # Split is first two layers then last two. + self.assertDictEqual( + index, + { + "metadata": {"total_size": 340000}, + "weight_map": { + "0.weight": "pytorch_model-00001-of-00002.bin", + "1.weight": "pytorch_model-00001-of-00002.bin", + "2.weight": "pytorch_model-00002-of-00002.bin", + "3.weight": "pytorch_model-00002-of-00002.bin", + }, + }, + ) + + shard1 = {"0.weight": state_dict["0.weight"], "1.weight": state_dict["1.weight"]} + shard2 = {"2.weight": state_dict["2.weight"], "3.weight": state_dict["3.weight"]} + self.assertDictEqual( + shards, {"pytorch_model-00001-of-00002.bin": shard1, "pytorch_model-00002-of-00002.bin": shard2} + ) + + with self.subTest("Test sharding with weights bigger than max size"): + shards, index = shard_checkpoint(state_dict, max_shard_size="100kB") + # Split is first layer, second layer then last 2. + self.assertDictEqual( + index, + { + "metadata": {"total_size": 340000}, + "weight_map": { + "0.weight": "pytorch_model-00001-of-00003.bin", + "1.weight": "pytorch_model-00002-of-00003.bin", + "2.weight": "pytorch_model-00003-of-00003.bin", + "3.weight": "pytorch_model-00003-of-00003.bin", + }, + }, + ) + + shard1 = {"0.weight": state_dict["0.weight"]} + shard2 = {"1.weight": state_dict["1.weight"]} + shard3 = {"2.weight": state_dict["2.weight"], "3.weight": state_dict["3.weight"]} + self.assertDictEqual( + shards, + { + "pytorch_model-00001-of-00003.bin": shard1, + "pytorch_model-00002-of-00003.bin": shard2, + "pytorch_model-00003-of-00003.bin": shard3, + }, + ) + + def test_checkpoint_sharding_local_bin(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + # We use the same folder for various sizes to make sure a new save erases the old checkpoint. + for max_size in ["50kB", "50kiB", "100kB", "100kiB", "200kB", "200kiB"]: + model.save_pretrained(tmp_dir, max_shard_size=max_size, safe_serialization=False) + + # Get each shard file and its size + shard_to_size = {} + for shard in os.listdir(tmp_dir): + if shard.endswith(".bin"): + shard_file = os.path.join(tmp_dir, shard) + shard_to_size[shard_file] = os.path.getsize(shard_file) + + index_file = os.path.join(tmp_dir, WEIGHTS_INDEX_NAME) + # Check there is an index but no regular weight file + self.assertTrue(os.path.isfile(index_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + + # Check a file is bigger than max_size only when it has a single weight + for shard_file, size in shard_to_size.items(): + if max_size.endswith("kiB"): + max_size_int = int(max_size[:-3]) * 2**10 + else: + max_size_int = int(max_size[:-2]) * 10**3 + # Note: pickle adds some junk so the weight of the file can end up being slightly bigger than + # the size asked for (since we count parameters) + if size >= max_size_int + 50000: + state_dict = torch.load(shard_file) + self.assertEqual(len(state_dict), 1) + + # Check the index and the shard files found match + with open(index_file, "r", encoding="utf-8") as f: + index = json.loads(f.read()) + + all_shards = set(index["weight_map"].values()) + shards_found = {f for f in os.listdir(tmp_dir) if f.endswith(".bin")} + self.assertSetEqual(all_shards, shards_found) + + # Finally, check the model can be reloaded + new_model = BertModel.from_pretrained(tmp_dir) + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + def test_checkpoint_sharding_from_hub(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded") + # the model above is the same as the model below, just a sharded version. + ref_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + for p1, p2 in zip(model.parameters(), ref_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + def test_checkpoint_variant_local_bin(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, variant="v2", safe_serialization=False) + + weights_name = ".".join(WEIGHTS_NAME.split(".")[:-1] + ["v2"] + ["bin"]) + + weights_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained(tmp_dir) + + new_model = BertModel.from_pretrained(tmp_dir, variant="v2") + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + def test_checkpoint_variant_local_sharded_bin(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, variant="v2", max_shard_size="50kB", safe_serialization=False) + + weights_index_name = ".".join(WEIGHTS_INDEX_NAME.split(".")[:-1] + ["v2"] + ["json"]) + weights_index_file = os.path.join(tmp_dir, weights_index_name) + self.assertTrue(os.path.isfile(weights_index_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_INDEX_NAME))) + + for i in range(1, 5): + weights_name = ".".join(WEIGHTS_NAME.split(".")[:-1] + [f"v2-0000{i}-of-00005"] + ["bin"]) + weights_name_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_name_file)) + + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained(tmp_dir) + + new_model = BertModel.from_pretrained(tmp_dir, variant="v2") + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + @require_safetensors + def test_checkpoint_variant_local_safe(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, variant="v2", safe_serialization=True) + + weights_name = ".".join(SAFE_WEIGHTS_NAME.split(".")[:-1] + ["v2"] + ["safetensors"]) + + weights_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained(tmp_dir) + + new_model = BertModel.from_pretrained(tmp_dir, variant="v2") + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + @require_safetensors + def test_checkpoint_variant_local_sharded_safe(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, variant="v2", max_shard_size="50kB", safe_serialization=True) + + weights_index_name = ".".join(SAFE_WEIGHTS_INDEX_NAME.split(".")[:-1] + ["v2"] + ["json"]) + weights_index_file = os.path.join(tmp_dir, weights_index_name) + self.assertTrue(os.path.isfile(weights_index_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_INDEX_NAME))) + + for i in range(1, 5): + weights_name = ".".join(SAFE_WEIGHTS_NAME.split(".")[:-1] + [f"v2-0000{i}-of-00005"] + ["safetensors"]) + weights_name_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_name_file)) + + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained(tmp_dir) + + new_model = BertModel.from_pretrained(tmp_dir, variant="v2") + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + def test_checkpoint_variant_hub(self): + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-variant", cache_dir=tmp_dir) + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant", cache_dir=tmp_dir, variant="v2" + ) + self.assertIsNotNone(model) + + def test_checkpoint_variant_hub_sharded(self): + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-sharded", cache_dir=tmp_dir + ) + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-sharded", cache_dir=tmp_dir, variant="v2" + ) + self.assertIsNotNone(model) + + @require_safetensors + def test_checkpoint_variant_hub_safe(self): + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-variant-safe", cache_dir=tmp_dir) + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-safe", cache_dir=tmp_dir, variant="v2" + ) + self.assertIsNotNone(model) + + @require_safetensors + def test_checkpoint_variant_hub_sharded_safe(self): + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-sharded-safe", cache_dir=tmp_dir + ) + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-sharded-safe", cache_dir=tmp_dir, variant="v2" + ) + self.assertIsNotNone(model) + + def test_checkpoint_variant_save_load_bin(self): + with tempfile.TemporaryDirectory() as tmp_dir: + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant", cache_dir=tmp_dir, variant="v2" + ) + weights_name = ".".join(WEIGHTS_NAME.split(".")[:-1] + ["v2"] + ["bin"]) + + model.save_pretrained(tmp_dir, variant="v2", safe_serialization=False) + # saving will create a variant checkpoint + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, weights_name))) + + model.save_pretrained(tmp_dir, safe_serialization=False) + # saving shouldn't delete variant checkpoints + weights_name = ".".join(WEIGHTS_NAME.split(".")[:-1] + ["v2"] + ["bin"]) + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, weights_name))) + + # there should be a normal checkpoint + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + + self.assertIsNotNone(model) + + @require_accelerate + @mark.accelerate_tests + def test_from_pretrained_low_cpu_mem_usage_functional(self): + # test that we can use `from_pretrained(..., low_cpu_mem_usage=True)` with normal and + # sharded models + + mnames = [ + "hf-internal-testing/tiny-random-bert-sharded", + "hf-internal-testing/tiny-random-bert", + ] + for mname in mnames: + _ = BertModel.from_pretrained(mname, low_cpu_mem_usage=True) + + @require_usr_bin_time + @require_accelerate + @mark.accelerate_tests + def test_from_pretrained_low_cpu_mem_usage_measured(self): + # test that `from_pretrained(..., low_cpu_mem_usage=True)` uses less cpu memory than default + + mname = "bert-base-cased" + + preamble = "from transformers import AutoModel" + one_liner_str = f'{preamble}; AutoModel.from_pretrained("{mname}", low_cpu_mem_usage=False)' + max_rss_normal = self.python_one_liner_max_rss(one_liner_str) + # print(f"{max_rss_normal=}") + + one_liner_str = f'{preamble}; AutoModel.from_pretrained("{mname}", low_cpu_mem_usage=True)' + max_rss_low_mem = self.python_one_liner_max_rss(one_liner_str) + # print(f"{max_rss_low_mem=}") + + diff_bytes = max_rss_normal - max_rss_low_mem + diff_percent = diff_bytes / max_rss_low_mem + # print(f"{diff_bytes=}, {diff_percent=}") + # ideally we would compare that the diff is close to ~1x checkpoint size in bytes, but + # measuring cpu memory on linux is very tricky and inconsistent, so instead let's check that + # it's at least 15% less cpu memory consumed + + self.assertGreater( + diff_percent, + 0.15, + "should use less CPU memory for low_cpu_mem_usage=True, " + f"but got max_rss_normal={max_rss_normal} and max_rss_low_mem={max_rss_low_mem}", + ) + + # if you want to compare things manually, let's first look at the size of the model in bytes + # model = BertModel.from_pretrained(mname, low_cpu_mem_usage=False) + # total_numel = sum(dict((p.data_ptr(), p.numel()) for p in model.parameters()).values()) + # total_bytes = total_numel * 4 # 420MB + # Now the diff_bytes should be very close to total_bytes, but the reports are inconsistent. + # The easiest way to test this is to switch the model and torch.load to do all the work on + # gpu - that way one can measure exactly the total and peak memory used. Perhaps once we add + # functionality to load models directly on gpu, this test can be rewritten to use torch's + # cuda memory tracking and then we should be able to do a much more precise test. + + @require_accelerate + @mark.accelerate_tests + @require_torch_multi_accelerator + @slow + def test_model_parallelism_gpt2(self): + device_map = {"transformer.wte": 0, "transformer.wpe": 0, "lm_head": 0, "transformer.ln_f": 1} + for i in range(12): + device_map[f"transformer.h.{i}"] = 0 if i <= 5 else 1 + + model = AutoModelForCausalLM.from_pretrained("gpt2", device_map=device_map) + + tokenizer = AutoTokenizer.from_pretrained("gpt2") + inputs = tokenizer("Hello, my name is", return_tensors="pt") + output = model.generate(inputs["input_ids"].to(0)) + + text_output = tokenizer.decode(output[0].tolist()) + self.assertEqual(text_output, "Hello, my name is John. I'm a writer, and I'm a writer. I'm") + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_from_pretrained_disk_offload_task_model(self): + model = AutoModel.from_pretrained("hf-internal-testing/tiny-random-gpt2") + device_map = { + "transformer.wte": 0, + "transformer.wpe": 0, + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": "cpu", + "transformer.h.3": "disk", + "transformer.h.4": "disk", + "transformer.ln_f": 0, + "lm_head": 0, + } + with tempfile.TemporaryDirectory() as tmp_dir: + inputs = torch.tensor([[1, 2, 3]]).to(0) + + model.save_pretrained(tmp_dir) + new_model = AutoModelForCausalLM.from_pretrained(tmp_dir).to(0) + outputs1 = new_model.to(0)(inputs) + + offload_folder = os.path.join(tmp_dir, "offload") + new_model_with_offload = AutoModelForCausalLM.from_pretrained( + tmp_dir, device_map=device_map, offload_folder=offload_folder + ) + outputs2 = new_model_with_offload(inputs) + + self.assertTrue(torch.allclose(outputs1.logits.cpu(), outputs2.logits.cpu())) + + # With state dict temp offload + offload_folder = os.path.join(tmp_dir, "offload") + new_model_with_offload = AutoModelForCausalLM.from_pretrained( + tmp_dir, + device_map=device_map, + offload_folder=offload_folder, + offload_state_dict=True, + ) + outputs2 = new_model_with_offload(inputs) + + self.assertTrue(torch.allclose(outputs1.logits.cpu(), outputs2.logits.cpu())) + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_from_pretrained_disk_offload_derived_to_base_model(self): + derived_model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2") + + device_map = { + "wte": 0, + "wpe": 0, + "h.0": "cpu", + "h.1": "cpu", + "h.2": "cpu", + "h.3": "disk", + "h.4": "disk", + "ln_f": 0, + } + with tempfile.TemporaryDirectory() as tmp_dir: + inputs = torch.tensor([[1, 2, 3]]).to(0) + derived_model.save_pretrained(tmp_dir, use_safetensors=True) + base_model = AutoModel.from_pretrained(tmp_dir) + outputs1 = base_model.to(0)(inputs) + + # with disk offload + offload_folder = os.path.join(tmp_dir, "offload") + base_model_with_offload = AutoModel.from_pretrained( + tmp_dir, device_map=device_map, offload_folder=offload_folder + ) + outputs2 = base_model_with_offload(inputs) + self.assertTrue(torch.allclose(outputs1[0].cpu(), outputs2[0].cpu())) + + # With state dict temp offload + new_model_with_offload = AutoModel.from_pretrained( + tmp_dir, + device_map=device_map, + offload_folder=offload_folder, + offload_state_dict=True, + ) + outputs2 = new_model_with_offload(inputs) + self.assertTrue(torch.allclose(outputs1[0].cpu(), outputs2[0].cpu())) + + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + # This check we did call the fake head request + mock_head.assert_called() + + def test_load_from_one_file(self): + try: + tmp_file = tempfile.mktemp() + with open(tmp_file, "wb") as f: + http_get( + "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/pytorch_model.bin", f + ) + + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + _ = BertModel.from_pretrained(tmp_file, config=config) + finally: + os.remove(tmp_file) + + def test_legacy_load_from_url(self): + # This test is for deprecated behavior and can be removed in v5 + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + _ = BertModel.from_pretrained( + "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/pytorch_model.bin", config=config + ) + + @require_safetensors + def test_use_safetensors(self): + # Should not raise anymore + AutoModel.from_pretrained("hf-internal-testing/tiny-random-RobertaModel", use_safetensors=True) + + # test that error if only safetensors is available + with self.assertRaises(OSError) as env_error: + BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-safetensors", use_safetensors=False) + + self.assertTrue("does not appear to have a file named pytorch_model.bin" in str(env_error.exception)) + + # test that only safetensors if both available and use_safetensors=False + with tempfile.TemporaryDirectory() as tmp_dir: + CLIPTextModel.from_pretrained( + "hf-internal-testing/diffusers-stable-diffusion-tiny-all", + subfolder="text_encoder", + use_safetensors=False, + cache_dir=tmp_dir, + ) + + all_downloaded_files = glob.glob(os.path.join(tmp_dir, "*", "snapshots", "*", "*", "*")) + self.assertTrue(any(f.endswith("bin") for f in all_downloaded_files)) + self.assertFalse(any(f.endswith("safetensors") for f in all_downloaded_files)) + + # test that no safetensors if both available and use_safetensors=True + with tempfile.TemporaryDirectory() as tmp_dir: + CLIPTextModel.from_pretrained( + "hf-internal-testing/diffusers-stable-diffusion-tiny-all", + subfolder="text_encoder", + use_safetensors=True, + cache_dir=tmp_dir, + ) + + all_downloaded_files = glob.glob(os.path.join(tmp_dir, "*", "snapshots", "*", "*", "*")) + self.assertTrue(any(f.endswith("safetensors") for f in all_downloaded_files)) + self.assertFalse(any(f.endswith("bin") for f in all_downloaded_files)) + + @require_safetensors + def test_safetensors_save_and_load(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + # No pytorch_model.bin file, only a model.safetensors + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + + new_model = BertModel.from_pretrained(tmp_dir) + + # Check models are equal + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + @require_safetensors + def test_safetensors_load_from_hub(self): + safetensors_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-safetensors") + pytorch_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Check models are equal + for p1, p2 in zip(safetensors_model.parameters(), pytorch_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + @require_safetensors + def test_safetensors_save_and_load_sharded(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True, max_shard_size="100kB") + # No pytorch_model.bin index file, only a model.safetensors index + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_INDEX_NAME))) + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_INDEX_NAME))) + # No regular weights file + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + + new_model = BertModel.from_pretrained(tmp_dir) + + # Check models are equal + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + @require_safetensors + def test_safetensors_load_from_hub_sharded(self): + safetensors_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded-safetensors") + pytorch_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded") + + # Check models are equal + for p1, p2 in zip(safetensors_model.parameters(), pytorch_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + def test_base_model_to_head_model_load(self): + base_model = BaseModel(PretrainedConfig()) + with tempfile.TemporaryDirectory() as tmp_dir: + base_model.save_pretrained(tmp_dir, safe_serialization=False) + + # Can load a base model in a model with head + model = ModelWithHead.from_pretrained(tmp_dir) + for p1, p2 in zip(model.base.parameters(), base_model.parameters()): + self.assertTrue(torch.allclose(p1, p2)) + + # It doesn't work if the state dict has a mix of keys of the head and base without prefix though. + base_state_dict = base_model.state_dict() + head_state_dict = model.state_dict() + base_state_dict["linear2.weight"] = head_state_dict["linear2.weight"] + base_state_dict["linear2.bias"] = head_state_dict["linear2.bias"] + safe_save_file(base_state_dict, os.path.join(tmp_dir, SAFE_WEIGHTS_NAME), metadata={"format": "pt"}) + + with self.assertRaisesRegex( + ValueError, "The state dictionary of the model you are trying to load is corrupted." + ): + _ = ModelWithHead.from_pretrained(tmp_dir) + + def test_tied_weights_reload(self): + # Base + model = BaseModelWithTiedWeights(PretrainedConfig()) + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + new_model = BaseModelWithTiedWeights.from_pretrained(tmp_dir) + self.assertIs(new_model.linear.weight, new_model.linear_2.weight) + + state_dict = model.state_dict() + # Remove tied weight from state_dict -> model should load with no complain of missing keys + del state_dict["linear_2.weight"] + torch.save(state_dict, os.path.join(tmp_dir, WEIGHTS_NAME)) + new_model, load_info = BaseModelWithTiedWeights.from_pretrained(tmp_dir, output_loading_info=True) + self.assertListEqual(load_info["missing_keys"], []) + self.assertIs(new_model.linear.weight, new_model.linear_2.weight) + + # With head + model.save_pretrained(tmp_dir) + new_model, load_info = ModelWithHeadAndTiedWeights.from_pretrained(tmp_dir, output_loading_info=True) + self.assertIs(new_model.base.linear.weight, new_model.decoder.weight) + # Should only complain about the missing bias + self.assertListEqual(load_info["missing_keys"], ["decoder.bias"]) + + def test_unexpected_keys_warnings(self): + model = ModelWithHead(PretrainedConfig()) + logger = logging.get_logger("transformers.modeling_utils") + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + # Loading the model with a new class, we don't get a warning for unexpected weights, just an info + with CaptureLogger(logger) as cl: + _, loading_info = BaseModel.from_pretrained(tmp_dir, output_loading_info=True) + self.assertNotIn("were not used when initializing ModelWithHead", cl.out) + self.assertEqual( + set(loading_info["unexpected_keys"]), + {"linear.weight", "linear.bias", "linear2.weight", "linear2.bias"}, + ) + + # Loading the model with the same class, we do get a warning for unexpected weights + state_dict = model.state_dict() + state_dict["added_key"] = copy.deepcopy(state_dict["linear.weight"]) + safe_save_file(state_dict, os.path.join(tmp_dir, SAFE_WEIGHTS_NAME), metadata={"format": "pt"}) + with CaptureLogger(logger) as cl: + _, loading_info = ModelWithHead.from_pretrained(tmp_dir, output_loading_info=True) + self.assertIn("were not used when initializing ModelWithHead: ['added_key']", cl.out) + self.assertEqual(loading_info["unexpected_keys"], ["added_key"]) + + def test_warn_if_padding_and_no_attention_mask(self): + logger = logging.get_logger("transformers.modeling_utils") + + with self.subTest("Ensure no warnings when pad_token_id is None."): + logger.warning_once.cache_clear() + with CaptureLogger(logger) as cl: + config_no_pad_token = PretrainedConfig() + config_no_pad_token.pad_token_id = None + model = ModelWithHead(config_no_pad_token) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertNotIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure no warnings when there is an attention_mask."): + logger.warning_once.cache_clear() + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask) + self.assertNotIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure no warnings when there are no pad_token_ids in the input_ids."): + logger.warning_once.cache_clear() + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[1, 345, 232, 328, 740, 140, 1695, 69, 6078, 2341, 25]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertNotIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure a warning is shown when the input_ids start with a pad_token_id."): + logger.warning_once.cache_clear() + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 432, 5232]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure a warning is shown when the input_ids end with a pad_token_id."): + logger.warning_once.cache_clear() + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[432, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure that the warning is shown at most once."): + logger.warning_once.cache_clear() + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertEqual(cl.out.count("We strongly recommend passing in an `attention_mask`"), 1) + + with self.subTest("Ensure a different warning is shown when the pad_token_id is equal to the bos_token_id."): + logger.warning_once.cache_clear() + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + config.bos_token_id = config.pad_token_id + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertIn("You may ignore this warning if your `pad_token_id`", cl.out) + + if not is_torchdynamo_available(): + return + with self.subTest("Ensure that the warning code is skipped when compiling with torchdynamo."): + logger.warning_once.cache_clear() + from torch._dynamo import config, testing + + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 432, 5232]]) + + def f(input_ids): + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + + compile_counter = testing.CompileCounter() + opt_fn = torch.compile(f, dynamic=True, backend=compile_counter) + opt_fn(input_ids) + self.assertEqual(compile_counter.frame_count, 0) + + @require_torch_accelerator + @slow + def test_pretrained_low_mem_new_config(self): + # Checking for 1 model(the same one which was described in the issue) . + model_ids = ["gpt2"] + + for model_id in model_ids: + model_config = AutoConfig.from_pretrained(pretrained_model_name_or_path=model_id) + model_config.n_layer = 48 + model_config.n_head = 25 + model_config.n_embd = 1600 + model = AutoModelForCausalLM.from_pretrained( + pretrained_model_name_or_path=model_id, + config=model_config, + ignore_mismatched_sizes=True, + torch_dtype=torch.float16, + low_cpu_mem_usage=True, + ) + model_ref = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path=model_id) + + self.assertEqual(model.__class__.__name__, model_ref.__class__.__name__) + + def test_generation_config_is_loaded_with_model(self): + # Note: `joaogante/tiny-random-gpt2-with-generation-config` has a `generation_config.json` containing a dummy + # `transformers_version` field set to `foo`. If loading the file fails, this test also fails. + + # 1. Load without further parameters + model = AutoModelForCausalLM.from_pretrained("joaogante/tiny-random-gpt2-with-generation-config") + self.assertEqual(model.generation_config.transformers_version, "foo") + + # 2. Load with `device_map` + model = AutoModelForCausalLM.from_pretrained( + "joaogante/tiny-random-gpt2-with-generation-config", device_map="auto" + ) + self.assertEqual(model.generation_config.transformers_version, "foo") + + @require_safetensors + def test_safetensors_torch_from_torch(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + new_model = BertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + @require_safetensors + @require_flax + def test_safetensors_torch_from_flax(self): + hub_model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only") + model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + new_model = BertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(hub_model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + @require_tf + @require_safetensors + def test_safetensors_torch_from_tf(self): + hub_model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only") + model = TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-tf-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + new_model = BertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(hub_model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + @require_safetensors + def test_safetensors_torch_from_torch_sharded(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True, max_shard_size="100kB") + new_model = BertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + +@slow +@require_torch +class ModelOnTheFlyConversionTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.user = "huggingface-hub-ci" + cls.token = os.getenv("HUGGINGFACE_PRODUCTION_USER_TOKEN", None) + + if cls.token is None: + raise ValueError("Cannot run tests as secret isn't setup.") + + cls.api = HfApi(token=cls.token) + + def setUp(self) -> None: + self.repo_name = f"{self.user}/test-model-on-the-fly-{uuid.uuid4()}" + + def tearDown(self) -> None: + self.api.delete_repo(self.repo_name) + + def test_safetensors_on_the_fly_conversion(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, "SFconvertbot") + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_conversion_private(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False, private=True) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name, token=self.token) + discussion = next(discussions) + self.assertEqual(discussion.author, self.user) + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_conversion_gated(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False) + headers = {"Authorization": f"Bearer {self.token}"} + requests.put( + f"https://huggingface.co/api/models/{self.repo_name}/settings", json={"gated": "auto"}, headers=headers + ) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, "SFconvertbot") + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_sharded_conversion(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False, max_shard_size="200kb") + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, "SFconvertbot") + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_sharded_conversion_private(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub( + self.repo_name, token=self.token, safe_serialization=False, max_shard_size="200kb", private=True + ) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, self.user) + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_sharded_conversion_gated(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, max_shard_size="200kb", safe_serialization=False) + headers = {"Authorization": f"Bearer {self.token}"} + requests.put( + f"https://huggingface.co/api/models/{self.repo_name}/settings", json={"gated": "auto"}, headers=headers + ) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, "SFconvertbot") + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + @unittest.skip("Edge case, should work once the Space is updated`") + def test_safetensors_on_the_fly_wrong_user_opened_pr(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False, private=True) + BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + # This should have opened a PR with the user's account + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, self.user) + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + # We now switch the repo visibility to public + self.api.update_repo_visibility(self.repo_name, private=False) + + # We once again call from_pretrained, which should call the bot to open a PR + BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + + bot_opened_pr = None + bot_opened_pr_title = None + + for discussion in discussions: + if discussion.author == "SFconvertBot": + bot_opened_pr = True + bot_opened_pr_title = discussion.title + + self.assertTrue(bot_opened_pr) + self.assertEqual(bot_opened_pr_title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_specific_revision(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + # Push a model on `main` + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False) + + # Push a model on a given revision + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False, revision="new-branch") + + # Try to convert the model on that revision should raise + with self.assertRaises(EnvironmentError): + BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token, revision="new-branch") + + +@require_torch +@is_staging_test +class ModelPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + try: + delete_repo(token=cls._token, repo_id="test-model") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="valid_org/test-model-org") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="test-dynamic-model") + except HTTPError: + pass + + @unittest.skip("This test is flaky") + def test_push_to_hub(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + model.push_to_hub("test-model", token=self._token) + + new_model = BertModel.from_pretrained(f"{USER}/test-model") + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + # Reset repo + delete_repo(token=self._token, repo_id="test-model") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, repo_id="test-model", push_to_hub=True, token=self._token) + + new_model = BertModel.from_pretrained(f"{USER}/test-model") + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + def test_push_to_hub_with_description(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + COMMIT_DESCRIPTION = """ +The commit description supports markdown synthax see: +```python +>>> form transformers import AutoConfig +>>> config = AutoConfig.from_pretrained("bert-base-uncased") +``` +""" + commit_details = model.push_to_hub( + "test-model", use_auth_token=self._token, create_pr=True, commit_description=COMMIT_DESCRIPTION + ) + self.assertEqual(commit_details.commit_description, COMMIT_DESCRIPTION) + + @unittest.skip("This test is flaky") + def test_push_to_hub_in_organization(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + model.push_to_hub("valid_org/test-model-org", token=self._token) + + new_model = BertModel.from_pretrained("valid_org/test-model-org") + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + # Reset repo + delete_repo(token=self._token, repo_id="valid_org/test-model-org") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, push_to_hub=True, token=self._token, repo_id="valid_org/test-model-org") + + new_model = BertModel.from_pretrained("valid_org/test-model-org") + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + def test_push_to_hub_dynamic_model(self): + CustomConfig.register_for_auto_class() + CustomModel.register_for_auto_class() + + config = CustomConfig(hidden_size=32) + model = CustomModel(config) + + model.push_to_hub("test-dynamic-model", token=self._token) + # checks + self.assertDictEqual( + config.auto_map, + {"AutoConfig": "custom_configuration.CustomConfig", "AutoModel": "custom_modeling.CustomModel"}, + ) + + new_model = AutoModel.from_pretrained(f"{USER}/test-dynamic-model", trust_remote_code=True) + # Can't make an isinstance check because the new_model is from the CustomModel class of a dynamic module + self.assertEqual(new_model.__class__.__name__, "CustomModel") + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + config = AutoConfig.from_pretrained(f"{USER}/test-dynamic-model", trust_remote_code=True) + new_model = AutoModel.from_config(config, trust_remote_code=True) + self.assertEqual(new_model.__class__.__name__, "CustomModel") + + +@require_torch +class AttentionMaskTester(unittest.TestCase): + def check_non_causal(self, bsz, q_len, kv_len, mask_2d, mask_4d): + mask_indices = (mask_2d != 1)[:, None].broadcast_to((bsz, q_len, kv_len)) + mask_4d_values = mask_4d[:, 0][mask_indices] + is_inf = mask_4d_values == -float("inf") + is_min = mask_4d_values == torch.finfo(mask_4d.dtype).min + assert torch.logical_or(is_inf, is_min).all() + + def check_to_4d(self, mask_converter, q_len, kv_len, additional_mask=None, bsz=3): + mask_2d = torch.ones((bsz, kv_len), device=torch_device, dtype=torch.long) + + if additional_mask is not None: + for bsz_idx, seq_idx in additional_mask: + mask_2d[bsz_idx, seq_idx] = 0 + + mask_4d = mask_converter.to_4d(mask_2d, query_length=q_len, key_value_length=kv_len, dtype=torch.float32) + + assert mask_4d.shape == (bsz, 1, q_len, kv_len) + + # make sure there are no overflows + assert mask_4d.min() != float("-inf") + + context = mask_converter.sliding_window + if mask_converter.is_causal and context is None: + # k * (k+1) / 2 tokens are masked in triangualar masks + num_tokens_masked = bsz * (q_len * (q_len - 1) // 2) + + if 0 not in mask_2d: + assert (mask_4d != 0).sum().cpu().item() == num_tokens_masked + if 0 in mask_2d: + # at least causal mask + maybe more + assert (mask_4d != 0).sum().cpu().item() >= num_tokens_masked + self.check_non_causal(bsz, q_len, kv_len, mask_2d, mask_4d) + elif not mask_converter.is_causal and context is None: + if 0 not in mask_2d: + assert (mask_4d != 0).sum().cpu().item() == 0 + if 0 in mask_2d: + self.check_non_causal(bsz, q_len, kv_len, mask_2d, mask_4d) + elif mask_converter.is_causal and context is not None: + # k * (k+1) / 2 tokens are masked in triangualar masks + num_tokens_masked = (q_len * (q_len - 1) // 2) + self.compute_num_context_mask(kv_len, context, q_len) + num_tokens_masked = bsz * num_tokens_masked + + if 0 not in mask_2d: + assert (mask_4d != 0).sum().cpu().item() == num_tokens_masked + if 0 in mask_2d: + # at least causal mask + maybe more + assert (mask_4d != 0).sum().cpu().item() >= num_tokens_masked + self.check_non_causal(bsz, q_len, kv_len, mask_2d, mask_4d) + + def check_to_causal(self, mask_converter, q_len, kv_len, bsz=3): + mask_4d = mask_converter.to_causal_4d( + bsz, query_length=q_len, key_value_length=kv_len, device=torch_device, dtype=torch.float32 + ) + + if q_len == 1 and mask_converter.sliding_window is None: + # no causal mask if q_len is 1 + assert mask_4d is None + return + + context = mask_converter.sliding_window + if mask_converter.is_causal and context is None: + # k * (k+1) / 2 tokens are masked in triangualar masks + num_tokens_masked = bsz * (q_len * (q_len - 1) // 2) + + assert (mask_4d != 0).sum().cpu().item() == num_tokens_masked + elif not mask_converter.is_causal and context is None: + assert (mask_4d != 0).sum().cpu().item() == 0 + elif mask_converter.is_causal and context is not None: + # k * (k+1) / 2 tokens are masked in triangualar masks + num_tokens_masked = (q_len * (q_len - 1) // 2) + self.compute_num_context_mask(kv_len, context, q_len) + num_tokens_masked = bsz * num_tokens_masked + + assert (mask_4d != 0).sum().cpu().item() == num_tokens_masked + + def compute_num_context_mask(self, kv_len, context, q_len): + # This function computes the # of attention tokens that are added for + # the sliding window + c_mask_len = kv_len - context + num_mask_triangle = c_mask_len * (c_mask_len + 1) // 2 + cut_mask_len = max(c_mask_len - q_len, 0) + num_cut_mask = cut_mask_len * (cut_mask_len + 1) // 2 + return num_mask_triangle - num_cut_mask + + def test_2d_to_4d_causal(self): + mask_converter = AttentionMaskConverter(is_causal=True) + + # auto-regressive use case + self.check_to_4d(mask_converter, q_len=1, kv_len=7) + # special auto-regressive case + self.check_to_4d(mask_converter, q_len=3, kv_len=7) + # non auto-regressive case + self.check_to_4d(mask_converter, q_len=7, kv_len=7) + + # same with extra attention masks + self.check_to_4d(mask_converter, q_len=1, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + self.check_to_4d(mask_converter, q_len=3, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + self.check_to_4d(mask_converter, q_len=7, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + + # check that the mask does not overflow on causal masked tokens + self.check_to_4d(mask_converter, q_len=7, kv_len=7, additional_mask=[(0, 0), (1, 0), (1, 1)]) + + def test_2d_to_4d(self): + mask_converter = AttentionMaskConverter(is_causal=False) + + # non auto-regressive case + self.check_to_4d(mask_converter, q_len=7, kv_len=7) + + # same with extra attention masks + self.check_to_4d(mask_converter, q_len=7, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + + def test_2d_to_4d_causal_sliding(self): + mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=5) + + # auto-regressive use case + self.check_to_4d(mask_converter, q_len=1, kv_len=7) + # special auto-regressive case + self.check_to_4d(mask_converter, q_len=3, kv_len=7) + # non auto-regressive case + self.check_to_4d(mask_converter, q_len=7, kv_len=7) + + # same with extra attention masks + self.check_to_4d(mask_converter, q_len=1, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + self.check_to_4d(mask_converter, q_len=3, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + self.check_to_4d(mask_converter, q_len=7, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + + def test_causal_mask(self): + mask_converter = AttentionMaskConverter(is_causal=True) + + # auto-regressive use case + self.check_to_causal(mask_converter, q_len=1, kv_len=7) + # special auto-regressive case + self.check_to_causal(mask_converter, q_len=3, kv_len=7) + # non auto-regressive case + self.check_to_causal(mask_converter, q_len=7, kv_len=7) + + def test_causal_mask_sliding(self): + mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=3) + + # auto-regressive use case + self.check_to_causal(mask_converter, q_len=1, kv_len=7) + # special auto-regressive case + self.check_to_causal(mask_converter, q_len=3, kv_len=7) + # non auto-regressive case + self.check_to_causal(mask_converter, q_len=7, kv_len=7) + + def test_torch_compile_fullgraph(self): + model = Prepare4dCausalAttentionMaskModel() + + inputs_embeds = torch.rand([1, 3, 32]) + res_non_compiled = model(inputs_embeds) + + compiled_model = torch.compile(model, fullgraph=True) + + res_compiled = compiled_model(inputs_embeds) + + self.assertTrue(torch.equal(res_non_compiled, res_compiled)) + + model = Create4dCausalAttentionMaskModel() + + inputs_embeds = torch.rand(2, 4, 16) + res_non_compiled = model(inputs_embeds) + + compiled_model = torch.compile(model, fullgraph=True) + res_compiled = compiled_model(inputs_embeds) + + self.assertTrue(torch.equal(res_non_compiled, res_compiled)) + + model = Prepare4dAttentionMaskModel() + + mask = torch.ones(2, 4) + mask[0, :2] = 0 + inputs_embeds = torch.rand(2, 4, 16) + + res_non_compiled = model(mask, inputs_embeds) + + compiled_model = torch.compile(model, fullgraph=True) + res_compiled = compiled_model(mask, inputs_embeds) + + self.assertTrue(torch.equal(res_non_compiled, res_compiled)) + + @require_torch + @slow + def test_unmask_unattended_left_padding(self): + attention_mask = torch.Tensor([[0, 0, 1], [1, 1, 1], [0, 1, 1]]).to(torch.int64) + + expanded_mask = torch.Tensor( + [ + [[[0, 0, 0], [0, 0, 0], [0, 0, 1]]], + [[[1, 0, 0], [1, 1, 0], [1, 1, 1]]], + [[[0, 0, 0], [0, 1, 0], [0, 1, 1]]], + ] + ).to(torch.int64) + + reference_output = torch.Tensor( + [ + [[[1, 1, 1], [1, 1, 1], [0, 0, 1]]], + [[[1, 0, 0], [1, 1, 0], [1, 1, 1]]], + [[[1, 1, 1], [0, 1, 0], [0, 1, 1]]], + ] + ).to(torch.int64) + + result = AttentionMaskConverter._unmask_unattended(expanded_mask, attention_mask, unmasked_value=1) + + self.assertTrue(torch.equal(result, reference_output)) + + attention_mask = torch.Tensor([[0, 0, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1]]).to(torch.int64) + + attn_mask_converter = AttentionMaskConverter(is_causal=True) + past_key_values_length = 0 + key_value_length = attention_mask.shape[-1] + past_key_values_length + + expanded_mask = attn_mask_converter.to_4d( + attention_mask, attention_mask.shape[-1], key_value_length=key_value_length, dtype=torch.float32 + ) + + result = AttentionMaskConverter._unmask_unattended(expanded_mask, attention_mask, unmasked_value=0) + min_inf = torch.finfo(torch.float32).min + reference_output = torch.Tensor( + [ + [ + [ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [min_inf, min_inf, 0, min_inf, min_inf], + [min_inf, min_inf, 0, 0, min_inf], + [min_inf, min_inf, 0, 0, 0], + ] + ], + [ + [ + [0, min_inf, min_inf, min_inf, min_inf], + [0, 0, min_inf, min_inf, min_inf], + [0, 0, 0, min_inf, min_inf], + [0, 0, 0, 0, min_inf], + [0, 0, 0, 0, 0], + ] + ], + [ + [ + [0, 0, 0, 0, 0], + [min_inf, 0, min_inf, min_inf, min_inf], + [min_inf, 0, 0, min_inf, min_inf], + [min_inf, 0, 0, 0, min_inf], + [min_inf, 0, 0, 0, 0], + ] + ], + ] + ) + + self.assertTrue(torch.equal(reference_output, result)) + + @require_torch + @slow + def test_unmask_unattended_right_padding(self): + attention_mask = torch.Tensor([[1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 0, 0]]).to(torch.int64) + + attn_mask_converter = AttentionMaskConverter(is_causal=True) + past_key_values_length = 0 + key_value_length = attention_mask.shape[-1] + past_key_values_length + + expanded_mask = attn_mask_converter.to_4d( + attention_mask, attention_mask.shape[-1], key_value_length=key_value_length, dtype=torch.float32 + ) + + result = AttentionMaskConverter._unmask_unattended(expanded_mask, attention_mask, unmasked_value=0) + + self.assertTrue(torch.equal(expanded_mask, result)) + + @require_torch + @slow + def test_unmask_unattended_random_mask(self): + attention_mask = torch.Tensor([[1, 0, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1]]).to(torch.int64) + + attn_mask_converter = AttentionMaskConverter(is_causal=True) + past_key_values_length = 0 + key_value_length = attention_mask.shape[-1] + past_key_values_length + + expanded_mask = attn_mask_converter.to_4d( + attention_mask, attention_mask.shape[-1], key_value_length=key_value_length, dtype=torch.float32 + ) + + result = AttentionMaskConverter._unmask_unattended(expanded_mask, attention_mask, unmasked_value=0) + + self.assertTrue(torch.equal(expanded_mask, result)) + + +@require_torch +class TestAttentionImplementation(unittest.TestCase): + def test_error_no_sdpa_available(self): + with self.assertRaises(ValueError) as cm: + _ = AutoModel.from_pretrained("hf-tiny-model-private/tiny-random-MCTCTModel", attn_implementation="sdpa") + + self.assertTrue( + "does not support an attention implementation through torch.nn.functional.scaled_dot_product_attention" + in str(cm.exception) + ) + + _ = AutoModel.from_pretrained("hf-tiny-model-private/tiny-random-MCTCTModel") + + def test_error_no_flash_available(self): + with self.assertRaises(ValueError) as cm: + _ = AutoModel.from_pretrained( + "hf-tiny-model-private/tiny-random-MCTCTModel", attn_implementation="flash_attention_2" + ) + + self.assertTrue("does not support Flash Attention 2.0" in str(cm.exception)) + + def test_error_wrong_attn_implementation(self): + with self.assertRaises(ValueError) as cm: + _ = AutoModel.from_pretrained("hf-tiny-model-private/tiny-random-MCTCTModel", attn_implementation="foo") + + self.assertTrue('The only possible arguments are `attn_implementation="eager"' in str(cm.exception)) + + def test_not_available_flash(self): + if is_flash_attn_2_available(): + self.skipTest("Please uninstall flash-attn package to run test_not_available_flash") + + with self.assertRaises(ImportError) as cm: + _ = AutoModel.from_pretrained( + "hf-internal-testing/tiny-random-GPTBigCodeModel", attn_implementation="flash_attention_2" + ) + + self.assertTrue("the package flash_attn seems to be not installed" in str(cm.exception)) + + def test_not_available_sdpa(self): + if is_torch_sdpa_available(): + self.skipTest("This test requires torch<=2.0") + + with self.assertRaises(ImportError) as cm: + _ = AutoModel.from_pretrained( + "hf-internal-testing/tiny-random-GPTBigCodeModel", attn_implementation="sdpa" + ) + + self.assertTrue("PyTorch SDPA requirements in Transformers are not met" in str(cm.exception)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_pipeline_mixin.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_pipeline_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..bd4b9eb39343a2b4a19b23fdbd52b94a6837274e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_pipeline_mixin.py @@ -0,0 +1,518 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import json +import os +import random +import unittest +from pathlib import Path + +from transformers.testing_utils import ( + is_pipeline_test, + require_decord, + require_pytesseract, + require_timm, + require_torch, + require_torch_or_tf, + require_vision, +) +from transformers.utils import direct_transformers_import, logging + +from .pipelines.test_pipelines_audio_classification import AudioClassificationPipelineTests +from .pipelines.test_pipelines_automatic_speech_recognition import AutomaticSpeechRecognitionPipelineTests +from .pipelines.test_pipelines_conversational import ConversationalPipelineTests +from .pipelines.test_pipelines_depth_estimation import DepthEstimationPipelineTests +from .pipelines.test_pipelines_document_question_answering import DocumentQuestionAnsweringPipelineTests +from .pipelines.test_pipelines_feature_extraction import FeatureExtractionPipelineTests +from .pipelines.test_pipelines_fill_mask import FillMaskPipelineTests +from .pipelines.test_pipelines_image_classification import ImageClassificationPipelineTests +from .pipelines.test_pipelines_image_segmentation import ImageSegmentationPipelineTests +from .pipelines.test_pipelines_image_to_image import ImageToImagePipelineTests +from .pipelines.test_pipelines_image_to_text import ImageToTextPipelineTests +from .pipelines.test_pipelines_mask_generation import MaskGenerationPipelineTests +from .pipelines.test_pipelines_object_detection import ObjectDetectionPipelineTests +from .pipelines.test_pipelines_question_answering import QAPipelineTests +from .pipelines.test_pipelines_summarization import SummarizationPipelineTests +from .pipelines.test_pipelines_table_question_answering import TQAPipelineTests +from .pipelines.test_pipelines_text2text_generation import Text2TextGenerationPipelineTests +from .pipelines.test_pipelines_text_classification import TextClassificationPipelineTests +from .pipelines.test_pipelines_text_generation import TextGenerationPipelineTests +from .pipelines.test_pipelines_text_to_audio import TextToAudioPipelineTests +from .pipelines.test_pipelines_token_classification import TokenClassificationPipelineTests +from .pipelines.test_pipelines_translation import TranslationPipelineTests +from .pipelines.test_pipelines_video_classification import VideoClassificationPipelineTests +from .pipelines.test_pipelines_visual_question_answering import VisualQuestionAnsweringPipelineTests +from .pipelines.test_pipelines_zero_shot import ZeroShotClassificationPipelineTests +from .pipelines.test_pipelines_zero_shot_audio_classification import ZeroShotAudioClassificationPipelineTests +from .pipelines.test_pipelines_zero_shot_image_classification import ZeroShotImageClassificationPipelineTests +from .pipelines.test_pipelines_zero_shot_object_detection import ZeroShotObjectDetectionPipelineTests + + +pipeline_test_mapping = { + "audio-classification": {"test": AudioClassificationPipelineTests}, + "automatic-speech-recognition": {"test": AutomaticSpeechRecognitionPipelineTests}, + "conversational": {"test": ConversationalPipelineTests}, + "depth-estimation": {"test": DepthEstimationPipelineTests}, + "document-question-answering": {"test": DocumentQuestionAnsweringPipelineTests}, + "feature-extraction": {"test": FeatureExtractionPipelineTests}, + "fill-mask": {"test": FillMaskPipelineTests}, + "image-classification": {"test": ImageClassificationPipelineTests}, + "image-segmentation": {"test": ImageSegmentationPipelineTests}, + "image-to-image": {"test": ImageToImagePipelineTests}, + "image-to-text": {"test": ImageToTextPipelineTests}, + "mask-generation": {"test": MaskGenerationPipelineTests}, + "object-detection": {"test": ObjectDetectionPipelineTests}, + "question-answering": {"test": QAPipelineTests}, + "summarization": {"test": SummarizationPipelineTests}, + "table-question-answering": {"test": TQAPipelineTests}, + "text2text-generation": {"test": Text2TextGenerationPipelineTests}, + "text-classification": {"test": TextClassificationPipelineTests}, + "text-generation": {"test": TextGenerationPipelineTests}, + "text-to-audio": {"test": TextToAudioPipelineTests}, + "token-classification": {"test": TokenClassificationPipelineTests}, + "translation": {"test": TranslationPipelineTests}, + "video-classification": {"test": VideoClassificationPipelineTests}, + "visual-question-answering": {"test": VisualQuestionAnsweringPipelineTests}, + "zero-shot": {"test": ZeroShotClassificationPipelineTests}, + "zero-shot-audio-classification": {"test": ZeroShotAudioClassificationPipelineTests}, + "zero-shot-image-classification": {"test": ZeroShotImageClassificationPipelineTests}, + "zero-shot-object-detection": {"test": ZeroShotObjectDetectionPipelineTests}, +} + +for task, task_info in pipeline_test_mapping.items(): + test = task_info["test"] + task_info["mapping"] = { + "pt": getattr(test, "model_mapping", None), + "tf": getattr(test, "tf_model_mapping", None), + } + + +# The default value `hf-internal-testing` is for running the pipeline testing against the tiny models on the Hub. +# For debugging purpose, we can specify a local path which is the `output_path` argument of a previous run of +# `utils/create_dummy_models.py`. +TRANSFORMERS_TINY_MODEL_PATH = os.environ.get("TRANSFORMERS_TINY_MODEL_PATH", "hf-internal-testing") +if TRANSFORMERS_TINY_MODEL_PATH == "hf-internal-testing": + TINY_MODEL_SUMMARY_FILE_PATH = os.path.join(Path(__file__).parent.parent, "tests/utils/tiny_model_summary.json") +else: + TINY_MODEL_SUMMARY_FILE_PATH = os.path.join(TRANSFORMERS_TINY_MODEL_PATH, "reports", "tiny_model_summary.json") +with open(TINY_MODEL_SUMMARY_FILE_PATH) as fp: + tiny_model_summary = json.load(fp) + + +PATH_TO_TRANSFORMERS = os.path.join(Path(__file__).parent.parent, "src/transformers") + + +# Dynamically import the Transformers module to grab the attribute classes of the processor form their names. +transformers_module = direct_transformers_import(PATH_TO_TRANSFORMERS) + +logger = logging.get_logger(__name__) + + +class PipelineTesterMixin: + model_tester = None + pipeline_model_mapping = None + supported_frameworks = ["pt", "tf"] + + def run_task_tests(self, task): + """Run pipeline tests for a specific `task` + + Args: + task (`str`): + A task name. This should be a key in the mapping `pipeline_test_mapping`. + """ + if task not in self.pipeline_model_mapping: + self.skipTest( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')} is skipped: `{task}` is not in " + f"`self.pipeline_model_mapping` for `{self.__class__.__name__}`." + ) + + model_architectures = self.pipeline_model_mapping[task] + if not isinstance(model_architectures, tuple): + model_architectures = (model_architectures,) + if not isinstance(model_architectures, tuple): + raise ValueError(f"`model_architectures` must be a tuple. Got {type(model_architectures)} instead.") + + for model_architecture in model_architectures: + model_arch_name = model_architecture.__name__ + + # Get the canonical name + for _prefix in ["Flax", "TF"]: + if model_arch_name.startswith(_prefix): + model_arch_name = model_arch_name[len(_prefix) :] + break + + tokenizer_names = [] + processor_names = [] + commit = None + if model_arch_name in tiny_model_summary: + tokenizer_names = tiny_model_summary[model_arch_name]["tokenizer_classes"] + processor_names = tiny_model_summary[model_arch_name]["processor_classes"] + if "sha" in tiny_model_summary[model_arch_name]: + commit = tiny_model_summary[model_arch_name]["sha"] + # Adding `None` (if empty) so we can generate tests + tokenizer_names = [None] if len(tokenizer_names) == 0 else tokenizer_names + processor_names = [None] if len(processor_names) == 0 else processor_names + + repo_name = f"tiny-random-{model_arch_name}" + if TRANSFORMERS_TINY_MODEL_PATH != "hf-internal-testing": + repo_name = model_arch_name + + self.run_model_pipeline_tests( + task, repo_name, model_architecture, tokenizer_names, processor_names, commit + ) + + def run_model_pipeline_tests(self, task, repo_name, model_architecture, tokenizer_names, processor_names, commit): + """Run pipeline tests for a specific `task` with the give model class and tokenizer/processor class names + + Args: + task (`str`): + A task name. This should be a key in the mapping `pipeline_test_mapping`. + repo_name (`str`): + A model repository id on the Hub. + model_architecture (`type`): + A subclass of `PretrainedModel` or `PretrainedModel`. + tokenizer_names (`List[str]`): + A list of names of a subclasses of `PreTrainedTokenizerFast` or `PreTrainedTokenizer`. + processor_names (`List[str]`): + A list of names of subclasses of `BaseImageProcessor` or `FeatureExtractionMixin`. + """ + # Get an instance of the corresponding class `XXXPipelineTests` in order to use `get_test_pipeline` and + # `run_pipeline_test`. + pipeline_test_class_name = pipeline_test_mapping[task]["test"].__name__ + + for tokenizer_name in tokenizer_names: + for processor_name in processor_names: + if self.is_pipeline_test_to_skip( + pipeline_test_class_name, + model_architecture.config_class, + model_architecture, + tokenizer_name, + processor_name, + ): + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')} is skipped: test is " + f"currently known to fail for: model `{model_architecture.__name__}` | tokenizer " + f"`{tokenizer_name}` | processor `{processor_name}`." + ) + continue + self.run_pipeline_test(task, repo_name, model_architecture, tokenizer_name, processor_name, commit) + + def run_pipeline_test(self, task, repo_name, model_architecture, tokenizer_name, processor_name, commit): + """Run pipeline tests for a specific `task` with the give model class and tokenizer/processor class name + + The model will be loaded from a model repository on the Hub. + + Args: + task (`str`): + A task name. This should be a key in the mapping `pipeline_test_mapping`. + repo_name (`str`): + A model repository id on the Hub. + model_architecture (`type`): + A subclass of `PretrainedModel` or `PretrainedModel`. + tokenizer_name (`str`): + The name of a subclass of `PreTrainedTokenizerFast` or `PreTrainedTokenizer`. + processor_name (`str`): + The name of a subclass of `BaseImageProcessor` or `FeatureExtractionMixin`. + """ + repo_id = f"{TRANSFORMERS_TINY_MODEL_PATH}/{repo_name}" + if TRANSFORMERS_TINY_MODEL_PATH != "hf-internal-testing": + model_type = model_architecture.config_class.model_type + repo_id = os.path.join(TRANSFORMERS_TINY_MODEL_PATH, model_type, repo_name) + + tokenizer = None + if tokenizer_name is not None: + tokenizer_class = getattr(transformers_module, tokenizer_name) + tokenizer = tokenizer_class.from_pretrained(repo_id, revision=commit) + + processor = None + if processor_name is not None: + processor_class = getattr(transformers_module, processor_name) + # If the required packages (like `Pillow` or `torchaudio`) are not installed, this will fail. + try: + processor = processor_class.from_pretrained(repo_id, revision=commit) + except Exception: + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')} is skipped: Could not load the " + f"processor from `{repo_id}` with `{processor_name}`." + ) + return + + # TODO: Maybe not upload such problematic tiny models to Hub. + if tokenizer is None and processor is None: + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')} is skipped: Could not find or load " + f"any tokenizer / processor from `{repo_id}`." + ) + return + + # TODO: We should check if a model file is on the Hub repo. instead. + try: + model = model_architecture.from_pretrained(repo_id, revision=commit) + except Exception: + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')} is skipped: Could not find or load " + f"the model from `{repo_id}` with `{model_architecture}`." + ) + return + + pipeline_test_class_name = pipeline_test_mapping[task]["test"].__name__ + if self.is_pipeline_test_to_skip_more(pipeline_test_class_name, model.config, model, tokenizer, processor): + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')} is skipped: test is " + f"currently known to fail for: model `{model_architecture.__name__}` | tokenizer " + f"`{tokenizer_name}` | processor `{processor_name}`." + ) + return + + # validate + validate_test_components(self, task, model, tokenizer, processor) + + if hasattr(model, "eval"): + model = model.eval() + + # Get an instance of the corresponding class `XXXPipelineTests` in order to use `get_test_pipeline` and + # `run_pipeline_test`. + task_test = pipeline_test_mapping[task]["test"]() + + pipeline, examples = task_test.get_test_pipeline(model, tokenizer, processor) + if pipeline is None: + # The test can disable itself, but it should be very marginal + # Concerns: Wav2Vec2ForCTC without tokenizer test (FastTokenizer don't exist) + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')} is skipped: Could not get the " + "pipeline for testing." + ) + return + + task_test.run_pipeline_test(pipeline, examples) + + def run_batch_test(pipeline, examples): + # Need to copy because `Conversation` are stateful + if pipeline.tokenizer is not None and pipeline.tokenizer.pad_token_id is None: + return # No batching for this and it's OK + + # 10 examples with batch size 4 means there needs to be a unfinished batch + # which is important for the unbatcher + def data(n): + for _ in range(n): + # Need to copy because Conversation object is mutated + yield copy.deepcopy(random.choice(examples)) + + out = [] + if task == "conversational": + for item in pipeline(data(10), batch_size=4, max_new_tokens=5): + out.append(item) + else: + for item in pipeline(data(10), batch_size=4): + out.append(item) + self.assertEqual(len(out), 10) + + run_batch_test(pipeline, examples) + + @is_pipeline_test + def test_pipeline_audio_classification(self): + self.run_task_tests(task="audio-classification") + + @is_pipeline_test + def test_pipeline_automatic_speech_recognition(self): + self.run_task_tests(task="automatic-speech-recognition") + + @is_pipeline_test + def test_pipeline_conversational(self): + self.run_task_tests(task="conversational") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_depth_estimation(self): + self.run_task_tests(task="depth-estimation") + + @is_pipeline_test + @require_pytesseract + @require_torch + @require_vision + def test_pipeline_document_question_answering(self): + self.run_task_tests(task="document-question-answering") + + @is_pipeline_test + def test_pipeline_feature_extraction(self): + self.run_task_tests(task="feature-extraction") + + @is_pipeline_test + def test_pipeline_fill_mask(self): + self.run_task_tests(task="fill-mask") + + @is_pipeline_test + @require_torch_or_tf + @require_vision + def test_pipeline_image_classification(self): + self.run_task_tests(task="image-classification") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_image_segmentation(self): + self.run_task_tests(task="image-segmentation") + + @is_pipeline_test + @require_vision + def test_pipeline_image_to_text(self): + self.run_task_tests(task="image-to-text") + + @unittest.skip(reason="`run_pipeline_test` is currently not implemented.") + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_mask_generation(self): + self.run_task_tests(task="mask-generation") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_object_detection(self): + self.run_task_tests(task="object-detection") + + @is_pipeline_test + def test_pipeline_question_answering(self): + self.run_task_tests(task="question-answering") + + @is_pipeline_test + def test_pipeline_summarization(self): + self.run_task_tests(task="summarization") + + @is_pipeline_test + def test_pipeline_table_question_answering(self): + self.run_task_tests(task="table-question-answering") + + @is_pipeline_test + def test_pipeline_text2text_generation(self): + self.run_task_tests(task="text2text-generation") + + @is_pipeline_test + def test_pipeline_text_classification(self): + self.run_task_tests(task="text-classification") + + @is_pipeline_test + @require_torch_or_tf + def test_pipeline_text_generation(self): + self.run_task_tests(task="text-generation") + + @is_pipeline_test + @require_torch + def test_pipeline_text_to_audio(self): + self.run_task_tests(task="text-to-audio") + + @is_pipeline_test + def test_pipeline_token_classification(self): + self.run_task_tests(task="token-classification") + + @is_pipeline_test + def test_pipeline_translation(self): + self.run_task_tests(task="translation") + + @is_pipeline_test + @require_torch_or_tf + @require_vision + @require_decord + def test_pipeline_video_classification(self): + self.run_task_tests(task="video-classification") + + @is_pipeline_test + @require_torch + @require_vision + def test_pipeline_visual_question_answering(self): + self.run_task_tests(task="visual-question-answering") + + @is_pipeline_test + def test_pipeline_zero_shot(self): + self.run_task_tests(task="zero-shot") + + @is_pipeline_test + @require_torch + def test_pipeline_zero_shot_audio_classification(self): + self.run_task_tests(task="zero-shot-audio-classification") + + @is_pipeline_test + @require_vision + def test_pipeline_zero_shot_image_classification(self): + self.run_task_tests(task="zero-shot-image-classification") + + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_zero_shot_object_detection(self): + self.run_task_tests(task="zero-shot-object-detection") + + # This contains the test cases to be skipped without model architecture being involved. + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + """Skip some tests based on the classes or their names without the instantiated objects. + + This is to avoid calling `from_pretrained` (so reducing the runtime) if we already know the tests will fail. + """ + # No fix is required for this case. + if ( + pipeline_test_casse_name == "DocumentQuestionAnsweringPipelineTests" + and tokenizer_name is not None + and not tokenizer_name.endswith("Fast") + ): + # `DocumentQuestionAnsweringPipelineTests` requires a fast tokenizer. + return True + + return False + + def is_pipeline_test_to_skip_more(self, pipeline_test_casse_name, config, model, tokenizer, processor): # noqa + """Skip some more tests based on the information from the instantiated objects.""" + # No fix is required for this case. + if ( + pipeline_test_casse_name == "QAPipelineTests" + and tokenizer is not None + and getattr(tokenizer, "pad_token", None) is None + and not tokenizer.__class__.__name__.endswith("Fast") + ): + # `QAPipelineTests` doesn't work with a slow tokenizer that has no pad token. + return True + + return False + + +def validate_test_components(test_case, task, model, tokenizer, processor): + # TODO: Move this to tiny model creation script + # head-specific (within a model type) necessary changes to the config + # 1. for `BlenderbotForCausalLM` + if model.__class__.__name__ == "BlenderbotForCausalLM": + model.config.encoder_no_repeat_ngram_size = 0 + + # TODO: Change the tiny model creation script: don't create models with problematic tokenizers + # Avoid `IndexError` in embedding layers + CONFIG_WITHOUT_VOCAB_SIZE = ["CanineConfig"] + if tokenizer is not None: + config_vocab_size = getattr(model.config, "vocab_size", None) + # For CLIP-like models + if config_vocab_size is None: + if hasattr(model.config, "text_config"): + config_vocab_size = getattr(model.config.text_config, "vocab_size", None) + elif hasattr(model.config, "text_encoder"): + config_vocab_size = getattr(model.config.text_encoder, "vocab_size", None) + + if config_vocab_size is None and model.config.__class__.__name__ not in CONFIG_WITHOUT_VOCAB_SIZE: + raise ValueError( + "Could not determine `vocab_size` from model configuration while `tokenizer` is not `None`." + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_sequence_feature_extraction_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_sequence_feature_extraction_common.py new file mode 100644 index 0000000000000000000000000000000000000000..f63ad1ede4f5a2da022665da895ab1b6ed2f98b5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_sequence_feature_extraction_common.py @@ -0,0 +1,424 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 numpy as np + +from transformers import BatchFeature +from transformers.testing_utils import require_tf, require_torch + +from .test_feature_extraction_common import FeatureExtractionSavingTestMixin + + +class SequenceFeatureExtractionTestMixin(FeatureExtractionSavingTestMixin): + # to overwrite at feature extractactor specific tests + feat_extract_tester = None + feature_extraction_class = None + + @property + def feat_extract_dict(self): + return self.feat_extract_tester.prepare_feat_extract_dict() + + def test_feat_extract_common_properties(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + self.assertTrue(hasattr(feat_extract, "feature_size")) + self.assertTrue(hasattr(feat_extract, "sampling_rate")) + self.assertTrue(hasattr(feat_extract, "padding_value")) + + def test_batch_feature(self): + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + self.assertTrue(all(len(x) == len(y) for x, y in zip(speech_inputs, processed_features[input_name]))) + + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) + processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="np") + + batch_features_input = processed_features[input_name] + + if len(batch_features_input.shape) < 3: + batch_features_input = batch_features_input[:, :, None] + + self.assertTrue( + batch_features_input.shape + == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) + ) + + @require_torch + def test_batch_feature_pt(self): + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="pt") + + batch_features_input = processed_features[input_name] + + if len(batch_features_input.shape) < 3: + batch_features_input = batch_features_input[:, :, None] + + self.assertTrue( + batch_features_input.shape + == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) + ) + + @require_tf + def test_batch_feature_tf(self): + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="tf") + + batch_features_input = processed_features[input_name] + + if len(batch_features_input.shape) < 3: + batch_features_input = batch_features_input[:, :, None] + + self.assertTrue( + batch_features_input.shape + == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) + ) + + def _check_padding(self, numpify=False): + def _inputs_have_equal_length(input): + length = len(input[0]) + for input_slice in input[1:]: + if len(input_slice) != length: + return False + return True + + def _inputs_are_equal(input_1, input_2): + if len(input_1) != len(input_2): + return False + + for input_slice_1, input_slice_2 in zip(input_1, input_2): + if not np.allclose(np.asarray(input_slice_1), np.asarray(input_slice_2), atol=1e-3): + return False + return True + + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(numpify=numpify) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + pad_diff = self.feat_extract_tester.seq_length_diff + pad_max_length = self.feat_extract_tester.max_seq_length + pad_diff + pad_min_length = self.feat_extract_tester.min_seq_length + batch_size = self.feat_extract_tester.batch_size + feature_size = self.feat_extract_tester.feature_size + + # test padding for List[int] + numpy + input_1 = feat_extract.pad(processed_features, padding=False) + input_1 = input_1[input_name] + + input_2 = feat_extract.pad(processed_features, padding="longest") + input_2 = input_2[input_name] + + input_3 = feat_extract.pad(processed_features, padding="max_length", max_length=len(speech_inputs[-1])) + input_3 = input_3[input_name] + + input_4 = feat_extract.pad(processed_features, padding="longest", return_tensors="np") + input_4 = input_4[input_name] + + # max_length parameter has to be provided when setting `padding="max_length"` + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, padding="max_length")[input_name] + + input_5 = feat_extract.pad( + processed_features, padding="max_length", max_length=pad_max_length, return_tensors="np" + ) + input_5 = input_5[input_name] + + self.assertFalse(_inputs_have_equal_length(input_1)) + self.assertTrue(_inputs_have_equal_length(input_2)) + self.assertTrue(_inputs_have_equal_length(input_3)) + self.assertTrue(_inputs_are_equal(input_2, input_3)) + self.assertTrue(len(input_1[0]) == pad_min_length) + self.assertTrue(len(input_1[1]) == pad_min_length + pad_diff) + self.assertTrue(input_4.shape[:2] == (batch_size, len(input_3[0]))) + self.assertTrue(input_5.shape[:2] == (batch_size, pad_max_length)) + + if feature_size > 1: + self.assertTrue(input_4.shape[2] == input_5.shape[2] == feature_size) + + # test padding for `pad_to_multiple_of` for List[int] + numpy + input_6 = feat_extract.pad(processed_features, pad_to_multiple_of=10) + input_6 = input_6[input_name] + + input_7 = feat_extract.pad(processed_features, padding="longest", pad_to_multiple_of=10) + input_7 = input_7[input_name] + + input_8 = feat_extract.pad( + processed_features, padding="max_length", pad_to_multiple_of=10, max_length=pad_max_length + ) + input_8 = input_8[input_name] + + input_9 = feat_extract.pad( + processed_features, + padding="max_length", + pad_to_multiple_of=10, + max_length=pad_max_length, + return_tensors="np", + ) + input_9 = input_9[input_name] + + self.assertTrue(all(len(x) % 10 == 0 for x in input_6)) + self.assertTrue(_inputs_are_equal(input_6, input_7)) + + expected_mult_pad_length = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 + self.assertTrue(all(len(x) == expected_mult_pad_length for x in input_8)) + self.assertEqual(input_9.shape[:2], (batch_size, expected_mult_pad_length)) + + if feature_size > 1: + self.assertTrue(input_9.shape[2] == feature_size) + + # Check padding value is correct + padding_vector_sum = (np.ones(self.feat_extract_tester.feature_size) * feat_extract.padding_value).sum() + self.assertTrue( + abs(np.asarray(input_2[0])[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) + < 1e-3 + ) + self.assertTrue( + abs( + np.asarray(input_2[1])[pad_min_length + pad_diff :].sum() + - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) + ) + < 1e-3 + ) + self.assertTrue( + abs( + np.asarray(input_2[2])[pad_min_length + 2 * pad_diff :].sum() + - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) + ) + < 1e-3 + ) + self.assertTrue( + abs(input_5[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) < 1e-3 + ) + self.assertTrue( + abs(input_9[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)) + < 1e-3 + ) + + def _check_truncation(self, numpify=False): + def _inputs_have_equal_length(input): + length = len(input[0]) + for input_slice in input[1:]: + if len(input_slice) != length: + return False + return True + + def _inputs_are_equal(input_1, input_2): + if len(input_1) != len(input_2): + return False + + for input_slice_1, input_slice_2 in zip(input_1, input_2): + if not np.allclose(np.asarray(input_slice_1), np.asarray(input_slice_2), atol=1e-3): + return False + return True + + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(numpify=numpify) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + # truncate to smallest + input_1 = feat_extract.pad( + processed_features, padding="max_length", max_length=len(speech_inputs[0]), truncation=True + ) + input_1 = input_1[input_name] + + input_2 = feat_extract.pad(processed_features, padding="max_length", max_length=len(speech_inputs[0])) + input_2 = input_2[input_name] + + self.assertTrue(_inputs_have_equal_length(input_1)) + self.assertFalse(_inputs_have_equal_length(input_2)) + + # truncate to smallest with np + input_3 = feat_extract.pad( + processed_features, + padding="max_length", + max_length=len(speech_inputs[0]), + return_tensors="np", + truncation=True, + ) + input_3 = input_3[input_name] + + input_4 = feat_extract.pad( + processed_features, padding="max_length", max_length=len(speech_inputs[0]), return_tensors="np" + ) + input_4 = input_4[input_name] + + self.assertTrue(_inputs_have_equal_length(input_3)) + self.assertTrue(input_3.shape[1] == len(speech_inputs[0])) + + # since truncation forces padding to be smaller than longest input + # function can't return `np.ndarray`, but has to return list + self.assertFalse(_inputs_have_equal_length(input_4)) + + # truncate to middle + input_5 = feat_extract.pad( + processed_features, + padding="max_length", + max_length=len(speech_inputs[1]), + truncation=True, + return_tensors="np", + ) + input_5 = input_5[input_name] + + input_6 = feat_extract.pad( + processed_features, padding="max_length", max_length=len(speech_inputs[1]), truncation=True + ) + input_6 = input_6[input_name] + + input_7 = feat_extract.pad( + processed_features, padding="max_length", max_length=len(speech_inputs[1]), return_tensors="np" + ) + input_7 = input_7[input_name] + + self.assertTrue(input_5.shape[1] == len(speech_inputs[1])) + self.assertTrue(_inputs_have_equal_length(input_5)) + self.assertTrue(_inputs_have_equal_length(input_6)) + self.assertTrue(_inputs_are_equal(input_5, input_6)) + + # since truncation forces padding to be smaller than longest input + # function can't return `np.ndarray`, but has to return list + self.assertFalse(_inputs_have_equal_length(input_7)) + self.assertTrue(len(input_7[-1]) == len(speech_inputs[-1])) + + # padding has to be max_length when setting `truncation=True` + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, truncation=True)[input_name] + + # padding has to be max_length when setting `truncation=True` + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, padding="longest", truncation=True)[input_name] + + # padding has to be max_length when setting `truncation=True` + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, padding="longest", truncation=True)[input_name] + + # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, padding="max_length", truncation=True)[input_name] + + # test truncation for `pad_to_multiple_of` for List[int] + numpy + pad_to_multiple_of = 12 + input_8 = feat_extract.pad( + processed_features, + padding="max_length", + max_length=len(speech_inputs[0]), + pad_to_multiple_of=pad_to_multiple_of, + truncation=True, + ) + input_8 = input_8[input_name] + + input_9 = feat_extract.pad( + processed_features, + padding="max_length", + max_length=len(speech_inputs[0]), + pad_to_multiple_of=pad_to_multiple_of, + ) + input_9 = input_9[input_name] + + # retrieve expected_length as multiple of pad_to_multiple_of + expected_length = len(speech_inputs[0]) + if expected_length % pad_to_multiple_of != 0: + expected_length = ((len(speech_inputs[0]) // pad_to_multiple_of) + 1) * pad_to_multiple_of + + self.assertTrue(len(input_8[0]) == expected_length) + self.assertTrue(_inputs_have_equal_length(input_8)) + self.assertFalse(_inputs_have_equal_length(input_9)) + + def test_padding_from_list(self): + self._check_padding(numpify=False) + + def test_padding_from_array(self): + self._check_padding(numpify=True) + + def test_truncation_from_list(self): + self._check_truncation(numpify=False) + + def test_truncation_from_array(self): + self._check_truncation(numpify=True) + + @require_torch + def test_padding_accepts_tensors_pt(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + input_np = feat_extract.pad(processed_features, padding="longest", return_tensors="np")[input_name] + input_pt = feat_extract.pad(processed_features, padding="longest", return_tensors="pt")[input_name] + + self.assertTrue(abs(input_np.astype(np.float32).sum() - input_pt.numpy().astype(np.float32).sum()) < 1e-2) + + @require_tf + def test_padding_accepts_tensors_tf(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + input_np = feat_extract.pad(processed_features, padding="longest", return_tensors="np")[input_name] + input_tf = feat_extract.pad(processed_features, padding="longest", return_tensors="tf")[input_name] + + self.assertTrue(abs(input_np.astype(np.float32).sum() - input_tf.numpy().astype(np.float32).sum()) < 1e-2) + + def test_attention_mask(self): + feat_dict = self.feat_extract_dict + feat_dict["return_attention_mask"] = True + feat_extract = self.feature_extraction_class(**feat_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + input_lengths = [len(x) for x in speech_inputs] + input_name = feat_extract.model_input_names[0] + + processed = BatchFeature({input_name: speech_inputs}) + + processed = feat_extract.pad(processed, padding="longest", return_tensors="np") + self.assertIn("attention_mask", processed) + self.assertListEqual(list(processed.attention_mask.shape), list(processed[input_name].shape[:2])) + self.assertListEqual(processed.attention_mask.sum(-1).tolist(), input_lengths) + + def test_attention_mask_with_truncation(self): + feat_dict = self.feat_extract_dict + feat_dict["return_attention_mask"] = True + feat_extract = self.feature_extraction_class(**feat_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + input_lengths = [len(x) for x in speech_inputs] + input_name = feat_extract.model_input_names[0] + + processed = BatchFeature({input_name: speech_inputs}) + max_length = min(input_lengths) + + processed_pad = feat_extract.pad( + processed, padding="max_length", max_length=max_length, truncation=True, return_tensors="np" + ) + self.assertIn("attention_mask", processed_pad) + self.assertListEqual( + list(processed_pad.attention_mask.shape), [processed_pad[input_name].shape[0], max_length] + ) + self.assertListEqual( + processed_pad.attention_mask[:, :max_length].sum(-1).tolist(), [max_length for x in speech_inputs] + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_tokenization_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_tokenization_common.py new file mode 100644 index 0000000000000000000000000000000000000000..9b60b2f186738e5751c290905af07e4514c26c6c --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_tokenization_common.py @@ -0,0 +1,4141 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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 itertools +import json +import os +import pickle +import re +import shutil +import tempfile +import traceback +import unittest +from collections import OrderedDict +from itertools import takewhile +from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union + +from parameterized import parameterized + +from transformers import ( + AlbertTokenizer, + AlbertTokenizerFast, + BertTokenizer, + BertTokenizerFast, + PreTrainedTokenizer, + PreTrainedTokenizerBase, + PreTrainedTokenizerFast, + SpecialTokensMixin, + Trainer, + TrainingArguments, + is_flax_available, + is_tf_available, + is_torch_available, + logging, +) +from transformers.testing_utils import ( + check_json_file_has_correct_format, + get_tests_dir, + is_pt_tf_cross_test, + require_jinja, + require_tf, + require_tokenizers, + require_torch, + run_test_in_subprocess, + slow, +) +from transformers.tokenization_utils import AddedToken + + +if is_torch_available(): + import torch.nn as nn + + +if TYPE_CHECKING: + from transformers import PretrainedConfig, PreTrainedModel, TFPreTrainedModel + + +logger = logging.get_logger(__name__) + +NON_ENGLISH_TAGS = ["chinese", "dutch", "french", "finnish", "german", "multilingual"] + +SMALL_TRAINING_CORPUS = [ + ["This is the first sentence.", "This is the second one."], + ["This sentence (contains #) over symbols and numbers 12 3.", "But not this one."], +] + + +def filter_non_english(_, pretrained_name: str): + """Filter all the model for non-english language""" + 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 + + +def merge_model_tokenizer_mappings( + model_mapping: Dict["PretrainedConfig", Union["PreTrainedModel", "TFPreTrainedModel"]], + tokenizer_mapping: Dict["PretrainedConfig", Tuple["PreTrainedTokenizer", "PreTrainedTokenizerFast"]], +) -> Dict[ + Union["PreTrainedTokenizer", "PreTrainedTokenizerFast"], + Tuple["PretrainedConfig", Union["PreTrainedModel", "TFPreTrainedModel"]], +]: + configurations = list(model_mapping.keys()) + model_tokenizer_mapping = OrderedDict([]) + + for configuration in configurations: + if configuration in model_mapping and configuration in tokenizer_mapping: + model = model_mapping[configuration] + tokenizer = tokenizer_mapping[configuration][0] + tokenizer_fast = tokenizer_mapping[configuration][1] + + if tokenizer is not None: + if configuration.__name__.startswith(tokenizer.__name__.replace("Tokenizer", "")): + model_tokenizer_mapping.update({tokenizer: (configuration, model)}) + if tokenizer_fast is not None: + if configuration.__name__.startswith(tokenizer_fast.__name__.replace("TokenizerFast", "")): + model_tokenizer_mapping.update({tokenizer_fast: (configuration, model)}) + + return model_tokenizer_mapping + + +def _test_subword_regularization_tokenizer(in_queue, out_queue, timeout): + error = None + + try: + inputs = in_queue.get(timeout=timeout) + tokenizer = inputs["tokenizer"] + sp_model_kwargs = inputs["sp_model_kwargs"] + test_sentencepiece_ignore_case = inputs["test_sentencepiece_ignore_case"] + + unittest.TestCase().assertTrue(hasattr(tokenizer, "sp_model_kwargs")) + unittest.TestCase().assertIsNotNone(tokenizer.sp_model_kwargs) + unittest.TestCase().assertTrue(isinstance(tokenizer.sp_model_kwargs, dict)) + unittest.TestCase().assertDictEqual(tokenizer.sp_model_kwargs, sp_model_kwargs) + check_subword_sampling(tokenizer, test_sentencepiece_ignore_case=test_sentencepiece_ignore_case) + + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +def check_subword_sampling( + tokenizer: PreTrainedTokenizer, + text: str = None, + test_sentencepiece_ignore_case: bool = True, +) -> None: + """ + Check if the tokenizer generates different results when subword regularization is enabled. + + Subword regularization augments training data with subword sampling. + This has a random component. + + Args: + tokenizer: The tokenizer to check. + text: The text to use for the checks. + test_sentencepiece_ignore_case: See `TokenizerTesterMixin.test_sentencepiece_ignore_case`. + """ + text = "This is a test for subword regularization." if text is None else text + if test_sentencepiece_ignore_case: + text = text.lower() + + tokens_list = [] + for _ in range(5): + tokens_list.append(tokenizer.tokenize(text)) + + # the list of different pairs of tokens_list + combinations = itertools.combinations(tokens_list, 2) + + # check of sampling is done + subword_sampling_found = False + for combination in combinations: + if combination[0] != combination[1]: + subword_sampling_found = True + unittest.TestCase().assertTrue(subword_sampling_found) + + # check if converting back to original text works + for tokens in tokens_list: + if test_sentencepiece_ignore_case: + unittest.TestCase().assertEqual(text, tokenizer.convert_tokens_to_string(tokens).lower()) + else: + unittest.TestCase().assertEqual(text, tokenizer.convert_tokens_to_string(tokens)) + + +class TokenizerTesterMixin: + tokenizer_class = None + rust_tokenizer_class = None + test_slow_tokenizer = True + test_rust_tokenizer = True + space_between_special_tokens = False + from_pretrained_kwargs = None + from_pretrained_filter = None + from_pretrained_vocab_key = "vocab_file" + test_seq2seq = True + + # set to True to test a sentencepiece tokenizer + test_sentencepiece = False + + # set to True to ignore casing when testing a sentencepiece tokenizer + # test_sentencepiece must also be set to True + test_sentencepiece_ignore_case = False + + def setUp(self) -> None: + # Tokenizer.filter makes it possible to filter which Tokenizer to case based on all the + # information available in Tokenizer (name, rust class, python class, vocab key name) + if self.test_rust_tokenizer: + tokenizers_list = [ + ( + self.rust_tokenizer_class, + pretrained_name, + self.from_pretrained_kwargs if self.from_pretrained_kwargs is not None else {}, + ) + for pretrained_name in self.rust_tokenizer_class.pretrained_vocab_files_map[ + self.from_pretrained_vocab_key + ].keys() + if self.from_pretrained_filter is None + or (self.from_pretrained_filter is not None and self.from_pretrained_filter(pretrained_name)) + ] + self.tokenizers_list = tokenizers_list[:1] # Let's just test the first pretrained vocab for speed + else: + self.tokenizers_list = [] + with open(f"{get_tests_dir()}/fixtures/sample_text.txt", encoding="utf-8") as f_data: + self._data = f_data.read().replace("\n\n", "\n").strip() + + self.tmpdirname = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def get_input_output_texts(self, tokenizer): + input_txt = self.get_clean_sequence(tokenizer)[0] + return input_txt, input_txt + + def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5) -> Tuple[str, list]: + # the length of the tokenizer does not always represent the tokens that it can encode: what if there are holes? + toks = [ + (i, tokenizer.decode([i], clean_up_tokenization_spaces=False)) for i in set(tokenizer.get_vocab().values()) + ] + toks = list(filter(lambda t: re.match(r"^[ a-zA-Z]+$", t[1]), toks)) + toks = list(filter(lambda t: [t[0]] == tokenizer.encode(t[1], add_special_tokens=False), toks)) + if max_length is not None and len(toks) > max_length: + toks = toks[:max_length] + if min_length is not None and len(toks) < min_length and len(toks) > 0: + while len(toks) < min_length: + toks = toks + toks + # toks_str = [t[1] for t in toks] + toks_ids = [t[0] for t in toks] + + # Ensure consistency + output_txt = tokenizer.decode(toks_ids, clean_up_tokenization_spaces=False) + if " " not in output_txt and len(toks_ids) > 1: + output_txt = ( + tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=False) + + " " + + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=False) + ) + if with_prefix_space: + output_txt = " " + output_txt + output_ids = tokenizer.encode(output_txt, add_special_tokens=False) + return output_txt, output_ids + + def get_tokenizers(self, fast=True, **kwargs) -> List[PreTrainedTokenizerBase]: + if fast and self.test_rust_tokenizer and self.test_slow_tokenizer: + return [self.get_tokenizer(**kwargs), self.get_rust_tokenizer(**kwargs)] + elif fast and self.test_rust_tokenizer: + return [self.get_rust_tokenizer(**kwargs)] + elif self.test_slow_tokenizer: + return [self.get_tokenizer(**kwargs)] + else: + raise ValueError("This tokenizer class has no tokenizer to be tested.") + + def get_tokenizer(self, **kwargs) -> PreTrainedTokenizer: + return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs) + + def get_rust_tokenizer(self, **kwargs) -> PreTrainedTokenizerFast: + return self.rust_tokenizer_class.from_pretrained(self.tmpdirname, **kwargs) + + def tokenizer_integration_test_util( + self, + expected_encoding: Dict, + model_name: str, + revision: str = None, + sequences: List[str] = None, + decode_kwargs: Dict[str, Any] = None, + padding: bool = True, + ): + """ + Util for integration test. + + Text is tokenized and then reverted back to text. Both results are then checked. + + Args: + expected_encoding: + The expected result of the tokenizer output. + model_name: + The model name of the tokenizer to load and use. + revision: + The full git revision number of the model. This is to pin the + tokenizer config and to avoid that tests start to fail if the + config gets changed upstream. + sequences: + Can overwrite the texts that are used to check the tokenizer. + This is useful if the tokenizer supports non english languages + like france. + decode_kwargs: + Additional args for the ``decode`` function which reverts the + tokenized text back to a string. + padding: + Activates and controls padding of the tokenizer. + """ + decode_kwargs = {} if decode_kwargs is None else decode_kwargs + + if sequences is None: + sequences = [ + "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " + "general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural " + "Language Understanding (NLU) and Natural Language Generation (NLG) with over 32+ pretrained " + "models in 100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.", + "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " + "conditioning on both left and right context in all layers.", + "The quick brown fox jumps over the lazy dog.", + ] + + if self.test_sentencepiece_ignore_case: + sequences = [sequence.lower() for sequence in sequences] + + tokenizer_classes = [self.tokenizer_class] + if self.test_rust_tokenizer: + tokenizer_classes.append(self.rust_tokenizer_class) + + for tokenizer_class in tokenizer_classes: + tokenizer = tokenizer_class.from_pretrained( + model_name, + revision=revision, # to pin the tokenizer version + ) + + encoding = tokenizer(sequences, padding=padding) + decoded_sequences = [ + tokenizer.decode(seq, skip_special_tokens=True, **decode_kwargs) for seq in encoding["input_ids"] + ] + + encoding_data = encoding.data + self.assertDictEqual(encoding_data, expected_encoding) + + for expected, decoded in zip(sequences, decoded_sequences): + if self.test_sentencepiece_ignore_case: + expected = expected.lower() + self.assertEqual(expected, decoded) + + def assert_padded_input_match(self, input_r: list, input_p: list, max_length: int, pad_token_id: int): + # Ensure we match max_length + self.assertEqual(len(input_r), max_length) + self.assertEqual(len(input_p), max_length) + + # Ensure the number of padded tokens is the same + padded_tokens_r = list(takewhile(lambda i: i == pad_token_id, reversed(input_r))) + padded_tokens_p = list(takewhile(lambda i: i == pad_token_id, reversed(input_p))) + self.assertSequenceEqual(padded_tokens_r, padded_tokens_p) + + def assert_batch_padded_input_match( + self, + input_r: dict, + input_p: dict, + max_length: int, + pad_token_id: int, + model_main_input_name: str = "input_ids", + ): + for i_r in input_r.values(): + ( + self.assertEqual(len(i_r), 2), + self.assertEqual(len(i_r[0]), max_length), + self.assertEqual(len(i_r[1]), max_length), + ) + ( + self.assertEqual(len(i_r), 2), + self.assertEqual(len(i_r[0]), max_length), + self.assertEqual(len(i_r[1]), max_length), + ) + + for i_r, i_p in zip(input_r[model_main_input_name], input_p[model_main_input_name]): + self.assert_padded_input_match(i_r, i_p, max_length, pad_token_id) + + for i_r, i_p in zip(input_r["attention_mask"], input_p["attention_mask"]): + self.assertSequenceEqual(i_r, i_p) + + @staticmethod + def convert_batch_encode_plus_format_to_encode_plus(batch_encode_plus_sequences): + # Switch from batch_encode_plus format: {'input_ids': [[...], [...]], ...} + # to the list of examples/ encode_plus format: [{'input_ids': [...], ...}, {'input_ids': [...], ...}] + return [ + {value: batch_encode_plus_sequences[value][i] for value in batch_encode_plus_sequences.keys()} + for i in range(len(batch_encode_plus_sequences["input_ids"])) + ] + + # TODO: this test can be combined with `test_sentencepiece_tokenize_and_convert_tokens_to_string` after the latter is extended to all tokenizers. + def test_tokenize_special_tokens(self): + """Test `tokenize` with special tokens.""" + tokenizers = self.get_tokenizers(fast=True, do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + SPECIAL_TOKEN_1 = "[SPECIAL_TOKEN_1]" + SPECIAL_TOKEN_2 = "[SPECIAL_TOKEN_2]" + + # Both methods should add the token to `_additional_special_tokens` and `added_tokens_decoder` + tokenizer.add_tokens([SPECIAL_TOKEN_1], special_tokens=True) + tokenizer.add_special_tokens( + {"additional_special_tokens": [SPECIAL_TOKEN_2]}, replace_additional_special_tokens=False + ) + + token_1 = tokenizer.tokenize(SPECIAL_TOKEN_1) + token_2 = tokenizer.tokenize(SPECIAL_TOKEN_2) + + self.assertEqual(len(token_1), 1) + self.assertEqual(len(token_2), 1) + self.assertEqual(token_1[0], SPECIAL_TOKEN_1) + # next is failing for almost all the Fast tokenizers now. + # self.assertEqual(token_2[0], SPECIAL_TOKEN_2) + + # TODO: this test could be extended to all tokenizers - not just the sentencepiece + def test_sentencepiece_tokenize_and_convert_tokens_to_string(self): + """Test ``_tokenize`` and ``convert_tokens_to_string``.""" + if not self.test_sentencepiece: + return + + tokenizer = self.get_tokenizer() + text = "This is text to test the tokenizer." + + if self.test_sentencepiece_ignore_case: + text = text.lower() + + tokens = tokenizer.tokenize(text) + + self.assertTrue(len(tokens) > 0) + + # check if converting back to original text works + reverse_text = tokenizer.convert_tokens_to_string(tokens) + + if self.test_sentencepiece_ignore_case: + reverse_text = reverse_text.lower() + + self.assertEqual(reverse_text, text) + + special_tokens = tokenizer.all_special_tokens + special_tokens_string = tokenizer.convert_tokens_to_string(special_tokens) + for special_token in special_tokens: + self.assertIn(special_token, special_tokens_string) + + if self.test_rust_tokenizer: + rust_tokenizer = self.get_rust_tokenizer() + special_tokens_string_rust = rust_tokenizer.convert_tokens_to_string(special_tokens) + self.assertEqual(special_tokens_string, special_tokens_string_rust) + + def test_sentencepiece_tokenize_and_decode(self): + if not self.test_sentencepiece: + return + + text = "This is text to test the tokenizer." + if self.test_rust_tokenizer: + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + slow_ids = tokenizer(text).input_ids + fast_ids = rust_tokenizer(text).input_ids + self.assertEqual(slow_ids, fast_ids) + + slow_decoded = tokenizer.decode(slow_ids) + fast_decoded = rust_tokenizer.decode(slow_ids) + self.assertEqual(slow_decoded, fast_decoded) + + def test_subword_regularization_tokenizer(self) -> None: + if not self.test_sentencepiece: + return + + # Subword regularization is only available for the slow tokenizer. + sp_model_kwargs = {"enable_sampling": True, "alpha": 0.1, "nbest_size": -1} + tokenizer = self.get_tokenizer(sp_model_kwargs=sp_model_kwargs) + + run_test_in_subprocess( + test_case=self, + target_func=_test_subword_regularization_tokenizer, + inputs={ + "tokenizer": tokenizer, + "sp_model_kwargs": sp_model_kwargs, + "test_sentencepiece_ignore_case": self.test_sentencepiece_ignore_case, + }, + ) + + def test_pickle_subword_regularization_tokenizer(self) -> None: + if not self.test_sentencepiece: + return + + """Google pickle __getstate__ __setstate__ if you are struggling with this.""" + # Subword regularization is only available for the slow tokenizer. + sp_model_kwargs = {"enable_sampling": True, "alpha": 0.1, "nbest_size": -1} + tokenizer = self.get_tokenizer(sp_model_kwargs=sp_model_kwargs) + tokenizer_bin = pickle.dumps(tokenizer) + del tokenizer + tokenizer_new = pickle.loads(tokenizer_bin) + + run_test_in_subprocess( + test_case=self, + target_func=_test_subword_regularization_tokenizer, + inputs={ + "tokenizer": tokenizer_new, + "sp_model_kwargs": sp_model_kwargs, + "test_sentencepiece_ignore_case": self.test_sentencepiece_ignore_case, + }, + ) + + def test_save_sentencepiece_tokenizer(self) -> None: + if not self.test_sentencepiece or not self.test_slow_tokenizer: + return + # We want to verify that we will be able to save the tokenizer even if the original files that were used to + # build the tokenizer have been deleted in the meantime. + text = "This is text to test the tokenizer." + + tokenizer_slow_1 = self.get_tokenizer() + encoding_tokenizer_slow_1 = tokenizer_slow_1(text) + + tmpdirname_1 = tempfile.mkdtemp() + tmpdirname_2 = tempfile.mkdtemp() + + tokenizer_slow_1.save_pretrained(tmpdirname_1) + tokenizer_slow_2 = self.tokenizer_class.from_pretrained(tmpdirname_1) + encoding_tokenizer_slow_2 = tokenizer_slow_2(text) + + shutil.rmtree(tmpdirname_1) + tokenizer_slow_2.save_pretrained(tmpdirname_2) + + tokenizer_slow_3 = self.tokenizer_class.from_pretrained(tmpdirname_2) + encoding_tokenizer_slow_3 = tokenizer_slow_3(text) + shutil.rmtree(tmpdirname_2) + + self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_2) + self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_3) + + def test_model_input_names_signature(self): + accepted_model_main_input_names = [ + "input_ids", # nlp models + "input_values", # speech models + ] + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + # first name of model_input_names has to correspond to main model input name + # to make sure `tokenizer.pad(...)` works correctly + self.assertTrue(tokenizer.model_input_names[0] in accepted_model_main_input_names) + + def test_rust_tokenizer_signature(self): + if not self.test_rust_tokenizer: + return + + signature = inspect.signature(self.rust_tokenizer_class.__init__) + + self.assertIn("tokenizer_file", signature.parameters) + self.assertIsNone(signature.parameters["tokenizer_file"].default) + + def test_tokenizer_slow_store_full_signature(self): + if not self.test_slow_tokenizer: + return + + signature = inspect.signature(self.tokenizer_class.__init__) + tokenizer = self.get_tokenizer() + + for parameter_name, parameter in signature.parameters.items(): + if parameter.default != inspect.Parameter.empty: + self.assertIn(parameter_name, tokenizer.init_kwargs) + + def test_tokenizer_fast_store_full_signature(self): + if not self.test_rust_tokenizer: + return + + signature = inspect.signature(self.rust_tokenizer_class.__init__) + tokenizer = self.get_rust_tokenizer() + + for parameter_name, parameter in signature.parameters.items(): + if parameter.default != inspect.Parameter.empty and parameter_name not in [ + "vocab_file", + "merges_file", + "tokenizer_file", + ]: + self.assertIn(parameter_name, tokenizer.init_kwargs) + + def test_rust_and_python_full_tokenizers(self): + if not self.test_rust_tokenizer: + return + + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + sequence, _ = self.get_input_output_texts(tokenizer) + + # We don't have an exact equivalence on `tokenize()` between Rust and Slow + # Slow tokenizer only split tokens, Rust tokenizers will replace with + # tokens = tokenizer.tokenize(sequence) + # rust_tokens = rust_tokenizer.tokenize(sequence) + # self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + ids = tokenizer.encode(sequence, add_special_tokens=True) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=True) + self.assertListEqual(ids, rust_ids) + + def test_tokenizers_common_properties(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + attributes_list = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token", + ] + for attr in attributes_list: + self.assertTrue(hasattr(tokenizer, attr)) + self.assertTrue(hasattr(tokenizer, attr + "_id")) + + self.assertTrue(hasattr(tokenizer, "additional_special_tokens")) + self.assertTrue(hasattr(tokenizer, "additional_special_tokens_ids")) + + attributes_list = [ + "model_max_length", + "init_inputs", + "init_kwargs", + ] + if not isinstance(tokenizer, PreTrainedTokenizerFast): + attributes_list += [ + "added_tokens_encoder", + "added_tokens_decoder", + ] + for attr in attributes_list: + self.assertTrue(hasattr(tokenizer, attr)) + + def test_tokenizers_common_ids_setters(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + attributes_list = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token", + ] + + vocab = tokenizer.get_vocab() + token_id_to_test_setters = next(iter(vocab.values())) + token_to_test_setters = tokenizer.convert_ids_to_tokens( + token_id_to_test_setters, skip_special_tokens=False + ) + + for attr in attributes_list: + setattr(tokenizer, attr + "_id", None) + self.assertEqual(getattr(tokenizer, attr), None) + self.assertEqual(getattr(tokenizer, attr + "_id"), None) + + setattr(tokenizer, attr + "_id", token_id_to_test_setters) + self.assertEqual(getattr(tokenizer, attr), token_to_test_setters) + self.assertEqual(getattr(tokenizer, attr + "_id"), token_id_to_test_setters) + + setattr(tokenizer, "additional_special_tokens_ids", []) + self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), []) + self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), []) + + setattr(tokenizer, "additional_special_tokens_ids", [token_id_to_test_setters]) + self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), [token_to_test_setters]) + self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), [token_id_to_test_setters]) + + @parameterized.expand([(True,), (False,)]) + def test_tokenizers_special_tokens_properties_unset(self, verbose): + tokenizers = self.get_tokenizers(verbose=verbose) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + attributes_list = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token", + "additional_special_tokens", + ] + for attr in attributes_list: + setattr(tokenizer, attr, None) + self.assertIsNone(getattr(tokenizer, attr)) + + def test_save_and_load_tokenizer(self): + # safety check on max_len default value so we are sure the test works + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + self.assertNotEqual(tokenizer.model_max_length, 42) + + # Now let's start the test + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + sample_text = " He is very happy, UNwant\u00E9d,running" + before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) + 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() + self.assertListEqual(before_tokens, after_tokens) + self.assertDictEqual(before_vocab, after_vocab) + + shutil.rmtree(tmpdirname) + + tokenizers = self.get_tokenizers(model_max_length=42) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + sample_text = " He is very happy, UNwant\u00E9d,running" + tokenizer.add_tokens(["bim", "bambam"]) + additional_special_tokens = tokenizer.additional_special_tokens + additional_special_tokens.append("new_additional_special_token") + tokenizer.add_special_tokens( + {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False + ) + before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) + 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() + self.assertListEqual(before_tokens, after_tokens) + + self.assertDictEqual(before_vocab, after_vocab) + self.assertIn("bim", after_vocab) + self.assertIn("bambam", after_vocab) + self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens) + self.assertEqual(after_tokenizer.model_max_length, 42) + + tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43) + self.assertEqual(tokenizer.model_max_length, 43) + + shutil.rmtree(tmpdirname) + + # Test that we can also use the non-legacy saving format for fast tokenizers + tokenizers = self.get_tokenizers(model_max_length=42) + for tokenizer in tokenizers: + if not tokenizer.is_fast: + continue + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + sample_text = " He is very happy, UNwant\u00E9d,running" + tokenizer.add_tokens(["bim", "bambam"]) + additional_special_tokens = tokenizer.additional_special_tokens + additional_special_tokens.append("new_additional_special_token") + tokenizer.add_special_tokens( + {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False + ) + before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) + 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() + self.assertListEqual(before_tokens, after_tokens) + self.assertDictEqual(before_vocab, after_vocab) + self.assertIn("bim", after_vocab) + self.assertIn("bambam", after_vocab) + self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens) + self.assertEqual(after_tokenizer.model_max_length, 42) + + tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43) + self.assertEqual(tokenizer.model_max_length, 43) + + shutil.rmtree(tmpdirname) + + def test_pickle_tokenizer(self): + """Google pickle __getstate__ __setstate__ if you are struggling with this.""" + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + self.assertIsNotNone(tokenizer) + + text = "Munich and Berlin are nice cities" + subwords = tokenizer.tokenize(text) + + filename = os.path.join(self.tmpdirname, "tokenizer.bin") + with open(filename, "wb") as handle: + pickle.dump(tokenizer, handle) + + with open(filename, "rb") as handle: + tokenizer_new = pickle.load(handle) + + subwords_loaded = tokenizer_new.tokenize(text) + + self.assertListEqual(subwords, subwords_loaded) + + @require_tokenizers + def test_pickle_added_tokens(self): + tok1 = AddedToken("", rstrip=True, lstrip=True, normalized=False, single_word=True) + tok2 = pickle.loads(pickle.dumps(tok1)) + + self.assertEqual(tok1.__getstate__(), tok2.__getstate__()) + + def test_added_tokens_do_lower_case(self): + tokenizers = self.get_tokenizers(do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if not hasattr(tokenizer, "do_lower_case") or not tokenizer.do_lower_case: + continue + + special_token = tokenizer.all_special_tokens[0] + + text = special_token + " aaaaa bbbbbb low cccccccccdddddddd l " + special_token + text2 = special_token + " AAAAA BBBBBB low CCCCCCCCCDDDDDDDD l " + special_token + + toks_before_adding = tokenizer.tokenize(text) # toks before adding new_toks + + new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd", "AAAAA BBBBBB", "CCCCCCCCCDDDDDDDD"] + added = tokenizer.add_tokens([AddedToken(tok, lstrip=True, rstrip=True) for tok in new_toks]) + + toks_after_adding = tokenizer.tokenize(text) + toks_after_adding2 = tokenizer.tokenize(text2) + + # Rust tokenizers dont't lowercase added tokens at the time calling `tokenizer.add_tokens`, + # while python tokenizers do, so new_toks 0 and 2 would be treated as the same, so do new_toks 1 and 3. + self.assertIn(added, [2, 4]) + + self.assertListEqual(toks_after_adding, toks_after_adding2) + self.assertTrue( + len(toks_before_adding) > len(toks_after_adding), # toks_before_adding should be longer + ) + + # Check that none of the special tokens are lowercased + sequence_with_special_tokens = "A " + " yEs ".join(tokenizer.all_special_tokens) + " B" + # Convert the tokenized list to str as some special tokens are tokenized like normal tokens + # which have a prefix spacee e.g. the mask token of Albert, and cannot match the original + # special tokens exactly. + tokenized_sequence = "".join(tokenizer.tokenize(sequence_with_special_tokens)) + + for special_token in tokenizer.all_special_tokens: + self.assertTrue(special_token in tokenized_sequence or special_token.lower() in tokenized_sequence) + + tokenizers = self.get_tokenizers(do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if hasattr(tokenizer, "do_lower_case") and tokenizer.do_lower_case: + continue + + special_token = tokenizer.all_special_tokens[0] + + text = special_token + " aaaaa bbbbbb low cccccccccdddddddd l " + special_token + text2 = special_token + " AAAAA BBBBBB low CCCCCCCCCDDDDDDDD l " + special_token + + toks_before_adding = tokenizer.tokenize(text) # toks before adding new_toks + + new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd", "AAAAA BBBBBB", "CCCCCCCCCDDDDDDDD"] + added = tokenizer.add_tokens([AddedToken(tok, lstrip=True, rstrip=True) for tok in new_toks]) + self.assertIn(added, [2, 4]) + + toks_after_adding = tokenizer.tokenize(text) + toks_after_adding2 = tokenizer.tokenize(text2) + + self.assertEqual(len(toks_after_adding), len(toks_after_adding2)) # Length should still be the same + self.assertNotEqual( + toks_after_adding[1], toks_after_adding2[1] + ) # But at least the first non-special tokens should differ + self.assertTrue( + len(toks_before_adding) > len(toks_after_adding), # toks_before_adding should be longer + ) + + # TODO @ArthurZ Nuke this + def test_add_tokens_tokenizer(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + vocab_size = tokenizer.vocab_size + all_size = len(tokenizer) + + self.assertNotEqual(vocab_size, 0) + + # We usually have added tokens from the start in tests (but also otherwise) because our vocab fixtures are + # smaller than the original vocabs - let's not assert this + # self.assertEqual(vocab_size, all_size) + + new_toks = [ + AddedToken("aaaaa bbbbbb", rstrip=True, lstrip=True), + AddedToken("cccccccccdddddddd", rstrip=True, lstrip=True), + ] + added_toks = tokenizer.add_tokens(new_toks) + vocab_size_2 = tokenizer.vocab_size + all_size_2 = len(tokenizer) + + self.assertNotEqual(vocab_size_2, 0) + self.assertEqual(vocab_size, vocab_size_2) + self.assertEqual(added_toks, len(new_toks)) + self.assertEqual(all_size_2, all_size + len(new_toks)) + + tokens = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False) + + self.assertGreaterEqual(len(tokens), 4) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-2], tokenizer.vocab_size - 1) + + new_toks_2 = { + "eos_token": AddedToken(">>>>|||<||<<|<<", rstrip=True, lstrip=True), + "pad_token": AddedToken("<<<<<|||>|>>>>|>", rstrip=True, lstrip=True), + } + added_toks_2 = tokenizer.add_special_tokens(new_toks_2) + vocab_size_3 = tokenizer.vocab_size + all_size_3 = len(tokenizer) + + self.assertNotEqual(vocab_size_3, 0) + self.assertEqual(vocab_size, vocab_size_3) + self.assertEqual(added_toks_2, len(new_toks_2)) + self.assertEqual(all_size_3, all_size_2 + len(new_toks_2)) + + tokens = tokenizer.encode( + ">>>>|||<||<<|<< aaaaa bbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", add_special_tokens=False + ) + + self.assertGreaterEqual(len(tokens), 6) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[0], tokens[1]) + + self.assertGreater(tokens[-2], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-2], tokens[-3]) + self.assertEqual(tokens[0], tokenizer.eos_token_id) + self.assertEqual(tokens[-2], tokenizer.pad_token_id) + + def test_add_special_tokens(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + input_text, ids = self.get_clean_sequence(tokenizer) + + special_token = AddedToken("[SPECIAL_TOKEN]", lstrip=True, rstrip=True) + + tokenizer.add_special_tokens({"cls_token": special_token}) + special_token = str(special_token) + encoded_special_token = tokenizer.encode(special_token, add_special_tokens=False) + self.assertEqual(len(encoded_special_token), 1) + + text = tokenizer.decode(ids + encoded_special_token, clean_up_tokenization_spaces=False) + encoded = tokenizer.encode(text, add_special_tokens=False) + + input_encoded = tokenizer.encode(input_text, add_special_tokens=False) + special_token_id = tokenizer.encode(special_token, add_special_tokens=False) + self.assertEqual(encoded, input_encoded + special_token_id) + + decoded = tokenizer.decode(encoded, skip_special_tokens=True) + self.assertTrue(special_token not in decoded) + + def test_internal_consistency(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + input_text, output_text = self.get_input_output_texts(tokenizer) + + tokens = tokenizer.tokenize(input_text) + ids = tokenizer.convert_tokens_to_ids(tokens) + ids_2 = tokenizer.encode(input_text, add_special_tokens=False) + self.assertListEqual(ids, ids_2) + + tokens_2 = tokenizer.convert_ids_to_tokens(ids) + self.assertNotEqual(len(tokens_2), 0) + text_2 = tokenizer.decode(ids) + self.assertIsInstance(text_2, str) + + self.assertEqual(text_2, output_text) + + @require_tokenizers + def test_encode_decode_with_spaces(self): + tokenizers = self.get_tokenizers(do_lower_case=False, fast=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + new_toks = [ + # These are added tokens, they will be normalized.... + AddedToken("[ABC]", normalized=True, lstrip=True, rstrip=True), + AddedToken("[DEF]", normalized=True, lstrip=True, rstrip=True), + AddedToken("GHI IHG", normalized=True, lstrip=True, rstrip=True), + ] + tokenizer.add_tokens(new_toks) + tokenizer.add_tokens([AddedToken("[SAMPLE]", normalized=True)], special_tokens=True) + input = "[ABC][DEF][ABC]GHI IHG[DEF]" + if self.space_between_special_tokens: + output = "[ABC] [DEF] [ABC] GHI IHG [DEF]" + else: + output = input + encoded = tokenizer.encode(input, add_special_tokens=False) + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=self.space_between_special_tokens) + + self.assertIn(decoded, [output, output.lower()]) + return + # TODO @ArthurZ Refactor testing as now the do_normalize works for special and non special + encoded = tokenizer.encode("[ABC] [DEF][SAMPLE]", add_special_tokens=False) + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True, skip_special_tokens=False) + self.assertIn(decoded, ["[ABC] [DEF] [SAMPLE]", "[ABC] [DEF] [SAMPLE]".lower()]) + + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True, skip_special_tokens=True) + self.assertIn(decoded, ["[ABC] [DEF]", "[ABC] [DEF]".lower()]) + + encoded = tokenizer.encode("[ABC][SAMPLE][DEF]", add_special_tokens=False) + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True) + self.assertIn(decoded, ["[ABC] [SAMPLE] [DEF]", "[ABC][SAMPLE][DEF]".lower()]) + + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=False) + self.assertIn(decoded, ["[ABC][SAMPLE][DEF]", "[ABC][SAMPLE][DEF]".lower()]) + + def test_pretrained_model_lists(self): + # We should have at least one default checkpoint for each tokenizer + # We should specify the max input length as well (used in some part to list the pretrained checkpoints) + self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map), 1) + self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values())[0]), 1) + self.assertEqual( + len(list(self.tokenizer_class.pretrained_vocab_files_map.values())[0]), + len(self.tokenizer_class.max_model_input_sizes), + ) + + weights_list = list(self.tokenizer_class.max_model_input_sizes.keys()) + weights_lists_2 = [] + for file_id, map_list in self.tokenizer_class.pretrained_vocab_files_map.items(): + weights_lists_2.append(list(map_list.keys())) + + for weights_list_2 in weights_lists_2: + self.assertListEqual(weights_list, weights_list_2) + + def test_mask_output(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if ( + tokenizer.build_inputs_with_special_tokens.__qualname__.split(".")[0] != "PreTrainedTokenizer" + and "token_type_ids" in tokenizer.model_input_names + ): + seq_0 = "Test this method." + seq_1 = "With these inputs." + information = tokenizer.encode_plus(seq_0, seq_1, add_special_tokens=True) + sequences, mask = information["input_ids"], information["token_type_ids"] + self.assertEqual(len(sequences), len(mask)) + + def test_token_type_ids(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0 = "Test this method." + + # We want to have sequence 0 and sequence 1 are tagged + # respectively with 0 and 1 token_ids + # (regardless of whether the model use token type ids) + # We use this assumption in the QA pipeline among other place + output = tokenizer(seq_0, return_token_type_ids=True) + self.assertIn(0, output["token_type_ids"]) + + def test_sequence_ids(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + if not tokenizer.is_fast: + continue + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0 = "Test this method." + seq_1 = "With these inputs." + + # We want to have sequence 0 and sequence 1 are tagged + # respectively with 0 and 1 token_ids + # (regardless of whether the model use token type ids) + # We use this assumption in the QA pipeline among other place + output = tokenizer(seq_0) + self.assertIn(0, output.sequence_ids()) + + output = tokenizer(seq_0, seq_1) + self.assertIn(0, output.sequence_ids()) + self.assertIn(1, output.sequence_ids()) + + if tokenizer.num_special_tokens_to_add(pair=True): + self.assertIn(None, output.sequence_ids()) + + @require_jinja + def test_chat_template(self): + dummy_template = "{% for message in messages %}{{message['role'] + message['content']}}{% endfor %}" + dummy_conversation = [ + {"role": "system", "content": "system message"}, + {"role": "user", "content": "user message"}, + {"role": "assistant", "content": "assistant message"}, + ] + expected_output = "systemsystem messageuseruser messageassistantassistant message" + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=False + ) + self.assertEqual(output, expected_output) # Test we can pass chat_template arg + # Check that no error raised when tokenize=True + tokenizer.apply_chat_template(dummy_conversation, chat_template=dummy_template, tokenize=True) + + tokenizer.chat_template = dummy_template + self.assertEqual(tokenizer.chat_template, dummy_template) # Test property setter + output = tokenizer.apply_chat_template(dummy_conversation, tokenize=False) + self.assertEqual(output, expected_output) # Test chat_template attribute is used if no arg is passed + tokenizer.apply_chat_template(dummy_conversation, tokenize=True) # Check that no error raised + + with tempfile.TemporaryDirectory() as tmp_dir_name: + tokenizer.save_pretrained(tmp_dir_name) + tokenizer = tokenizer.from_pretrained(tmp_dir_name) + + self.assertEqual(tokenizer.chat_template, dummy_template) # Test template has persisted + output = tokenizer.apply_chat_template(dummy_conversation, tokenize=False) + self.assertEqual(output, expected_output) # Test output is the same after reloading + tokenizer.apply_chat_template(dummy_conversation, tokenize=True) # Check that no error raised + + def test_number_of_added_tokens(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0 = "Test this method." + seq_1 = "With these inputs." + + sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=False) + attached_sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=True) + + # Method is implemented (e.g. not GPT-2) + if len(attached_sequences) != 2: + self.assertEqual( + tokenizer.num_special_tokens_to_add(pair=True), len(attached_sequences) - len(sequences) + ) + + def test_maximum_encoding_length_single_input(self): + tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20) + + sequence = tokenizer.encode(seq_0, add_special_tokens=False) + total_length = len(sequence) + + self.assertGreater( + total_length, 4, "Issue with the testing sequence, please update it, it's too short" + ) + + # Test with max model input length + model_max_length = tokenizer.model_max_length + self.assertEqual(model_max_length, 100) + seq_1 = seq_0 * model_max_length + + sequence1 = tokenizer(seq_1, add_special_tokens=False) + total_length1 = len(sequence1["input_ids"]) + self.assertGreater( + total_length1, + model_max_length, + "Issue with the testing sequence, please update it, it's too short", + ) + + # Simple + padding_strategies = ( + [False, True, "longest"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False] + ) + for padding_state in padding_strategies: + with self.subTest(f"Padding: {padding_state}"): + for truncation_state in [True, "longest_first", "only_first"]: + with self.subTest(f"Truncation: {truncation_state}"): + output = tokenizer(seq_1, padding=padding_state, truncation=truncation_state) + self.assertEqual(len(output["input_ids"]), model_max_length) + + output = tokenizer([seq_1], padding=padding_state, truncation=truncation_state) + self.assertEqual(len(output["input_ids"][0]), model_max_length) + + # Simple with no truncation + # Reset warnings + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer(seq_1, padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer([seq_1], padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"][0]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + # Overflowing tokens + stride = 2 + information = tokenizer( + seq_0, + max_length=total_length - 2, + add_special_tokens=False, + stride=stride, + truncation="longest_first", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + truncated_sequence = information["input_ids"][0] + overflowing_tokens = information["input_ids"][1] + self.assertEqual(len(information["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), total_length - 2) + self.assertEqual(truncated_sequence, sequence[:-2]) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :]) + else: + truncated_sequence = information["input_ids"] + overflowing_tokens = information["overflowing_tokens"] + + self.assertEqual(len(truncated_sequence), total_length - 2) + self.assertEqual(truncated_sequence, sequence[:-2]) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :]) + + def test_maximum_encoding_length_pair_input(self): + tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Build a sequence from our model's vocabulary + stride = 2 + seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20) + if len(ids) <= 2 + stride: + seq_0 = (seq_0 + " ") * (2 + stride) + ids = None + + seq0_tokens = tokenizer.encode(seq_0, add_special_tokens=False) + self.assertGreater(len(seq0_tokens), 2 + stride) + + seq_1 = "This is another sentence to be encoded." + seq1_tokens = tokenizer.encode(seq_1, add_special_tokens=False) + if abs(len(seq0_tokens) - len(seq1_tokens)) <= 2: + seq1_tokens = seq1_tokens + seq1_tokens + seq_1 = tokenizer.decode(seq1_tokens, clean_up_tokenization_spaces=False) + seq1_tokens = tokenizer.encode(seq_1, add_special_tokens=False) + + self.assertGreater(len(seq1_tokens), 2 + stride) + + smallest = seq1_tokens if len(seq0_tokens) > len(seq1_tokens) else seq0_tokens + + # We are not using the special tokens - a bit too hard to test all the tokenizers with this + # TODO try this again later + sequence = tokenizer.encode(seq_0, seq_1, add_special_tokens=False) # , add_prefix_space=False) + + # Test with max model input length + model_max_length = tokenizer.model_max_length + self.assertEqual(model_max_length, 100) + seq_2 = seq_0 * model_max_length + self.assertGreater(len(seq_2), model_max_length) + + sequence1 = tokenizer(seq_1, add_special_tokens=False) + total_length1 = len(sequence1["input_ids"]) + sequence2 = tokenizer(seq_2, seq_1, add_special_tokens=False) + total_length2 = len(sequence2["input_ids"]) + self.assertLess( + total_length1, model_max_length - 10, "Issue with the testing sequence, please update it." + ) + self.assertGreater( + total_length2, model_max_length, "Issue with the testing sequence, please update it." + ) + + # Simple + padding_strategies = ( + [False, True, "longest"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False] + ) + for padding_state in padding_strategies: + with self.subTest(f"{tokenizer.__class__.__name__} Padding: {padding_state}"): + for truncation_state in [True, "longest_first", "only_first"]: + with self.subTest(f"{tokenizer.__class__.__name__} Truncation: {truncation_state}"): + output = tokenizer(seq_2, seq_1, padding=padding_state, truncation=truncation_state) + self.assertEqual(len(output["input_ids"]), model_max_length) + + output = tokenizer( + [seq_2], [seq_1], padding=padding_state, truncation=truncation_state + ) + self.assertEqual(len(output["input_ids"][0]), model_max_length) + + # Simple + output = tokenizer(seq_1, seq_2, padding=padding_state, truncation="only_second") + self.assertEqual(len(output["input_ids"]), model_max_length) + + output = tokenizer([seq_1], [seq_2], padding=padding_state, truncation="only_second") + self.assertEqual(len(output["input_ids"][0]), model_max_length) + + # Simple with no truncation + # Reset warnings + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer(seq_1, seq_2, padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer([seq_1], [seq_2], padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"][0]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + truncated_first_sequence = tokenizer.encode(seq_0, add_special_tokens=False)[:-2] + tokenizer.encode( + seq_1, add_special_tokens=False + ) + truncated_second_sequence = ( + tokenizer.encode(seq_0, add_special_tokens=False) + + tokenizer.encode(seq_1, add_special_tokens=False)[:-2] + ) + truncated_longest_sequence = ( + truncated_first_sequence if len(seq0_tokens) > len(seq1_tokens) else truncated_second_sequence + ) + + overflow_first_sequence = tokenizer.encode(seq_0, add_special_tokens=False)[ + -(2 + stride) : + ] + tokenizer.encode(seq_1, add_special_tokens=False) + overflow_second_sequence = ( + tokenizer.encode(seq_0, add_special_tokens=False) + + tokenizer.encode(seq_1, add_special_tokens=False)[-(2 + stride) :] + ) + overflow_longest_sequence = ( + overflow_first_sequence if len(seq0_tokens) > len(seq1_tokens) else overflow_second_sequence + ) + + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + information = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation="longest_first", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + truncated_sequence = information["input_ids"][0] + overflowing_tokens = information["input_ids"][1] + self.assertEqual(len(information["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_longest_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride + len(smallest)) + self.assertEqual(overflowing_tokens, overflow_longest_sequence) + else: + # No overflowing tokens when using 'longest' in python tokenizers + with self.assertRaises(ValueError) as context: + information = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation="longest_first", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + + self.assertTrue( + context.exception.args[0].startswith( + "Not possible to return overflowing tokens for pair of sequences with the " + "`longest_first`. Please select another truncation strategy than `longest_first`, " + "for instance `only_second` or `only_first`." + ) + ) + + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + information = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation=True, + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + truncated_sequence = information["input_ids"][0] + overflowing_tokens = information["input_ids"][1] + self.assertEqual(len(information["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_longest_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride + len(smallest)) + self.assertEqual(overflowing_tokens, overflow_longest_sequence) + else: + # No overflowing tokens when using 'longest' in python tokenizers + with self.assertRaises(ValueError) as context: + information = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation=True, + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + + self.assertTrue( + context.exception.args[0].startswith( + "Not possible to return overflowing tokens for pair of sequences with the " + "`longest_first`. Please select another truncation strategy than `longest_first`, " + "for instance `only_second` or `only_first`." + ) + ) + + information_first_truncated = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation="only_first", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + truncated_sequence = information_first_truncated["input_ids"][0] + overflowing_tokens = information_first_truncated["input_ids"][1] + self.assertEqual(len(information_first_truncated["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_first_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride + len(seq1_tokens)) + self.assertEqual(overflowing_tokens, overflow_first_sequence) + else: + truncated_sequence = information_first_truncated["input_ids"] + overflowing_tokens = information_first_truncated["overflowing_tokens"] + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_first_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, seq0_tokens[-(2 + stride) :]) + + information_second_truncated = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation="only_second", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + truncated_sequence = information_second_truncated["input_ids"][0] + overflowing_tokens = information_second_truncated["input_ids"][1] + self.assertEqual(len(information_second_truncated["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_second_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride + len(seq0_tokens)) + self.assertEqual(overflowing_tokens, overflow_second_sequence) + else: + truncated_sequence = information_second_truncated["input_ids"] + overflowing_tokens = information_second_truncated["overflowing_tokens"] + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_second_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, seq1_tokens[-(2 + stride) :]) + + # def test_encode_input_type(self): + # tokenizers = self.get_tokenizers(do_lower_case=False) + # for tokenizer in tokenizers: + # with self.subTest(f"{tokenizer.__class__.__name__}"): + # sequence = "Let's encode this sequence" + + # tokens = sequence.split() # tokenizer.tokenize(sequence) + # # input_ids = tokenizer.convert_tokens_to_ids(tokens) + # formatted_input = tokenizer.encode(sequence, add_special_tokens=True, add_prefix_space=False) + + # self.assertEqual( + # tokenizer.encode(tokens, is_split_into_words=True, add_special_tokens=True), formatted_input + # ) + # # This is not supported with the Rust tokenizers + # # self.assertEqual(tokenizer.encode(input_ids, add_special_tokens=True), formatted_input) + + # def test_swap_special_token(self): + # tokenizers = self.get_tokenizers(do_lower_case=False) + # for tokenizer in tokenizers: + # with self.subTest(f"{tokenizer.__class__.__name__}"): + # # Our mask token + # mask = "" + # # We take a single word in the middle of the vocabulary + # all_tokens = sorted(tokenizer.get_vocab().keys()) + # word = tokenizer.decode(tokenizer.encode(all_tokens[len(all_tokens)//2], add_special_tokens=False)[:1]) + + # sequence_0 = "Encode " + word + " sequence" + # sequence_masked_0 = "Encode " + mask + " sequence" + + # sequence_1 = word + " this sequence" + # sequence_masked_1 = mask + " this sequence" + + # # Add tokens so that masked token isn't split + # # tokens = [AddedToken(t, lstrip=True, normalized=False) for t in sequence.split()] + # # tokenizer.add_tokens(tokens) + # tokenizer.add_special_tokens( + # {"mask_token": AddedToken(mask, normalized=False)} + # ) # Eat left space on Byte-level BPE tokenizers + # mask_ind = tokenizer.convert_tokens_to_ids(mask) + + # # Test first masked sequence + # encoded_0 = tokenizer.encode(sequence_0, add_special_tokens=False) + # encoded_masked = tokenizer.encode(sequence_masked_0, add_special_tokens=False) + # self.assertEqual(len(encoded_masked), len(encoded_0)) + # mask_loc = encoded_masked.index(mask_ind) + # encoded_masked[mask_loc] = encoded_0[mask_loc] + + # self.assertEqual(encoded_masked, encoded_0) + + # # Test second masked sequence + # encoded_1 = tokenizer.encode(sequence_1, add_special_tokens=False) + # encoded_masked = tokenizer.encode(sequence_masked_1, add_special_tokens=False) + # self.assertEqual(len(encoded_masked), len(encoded_1)) + # mask_loc = encoded_masked.index(mask_ind) + # encoded_masked[mask_loc] = encoded_1[mask_loc] + + # self.assertEqual(encoded_masked, encoded_1) + + def test_special_tokens_mask(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence_0 = "Encode this." + # Testing single inputs + encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False) + encoded_sequence_dict = tokenizer.encode_plus( + sequence_0, + add_special_tokens=True, + return_special_tokens_mask=True, # , add_prefix_space=False + ) + encoded_sequence_w_special = encoded_sequence_dict["input_ids"] + special_tokens_mask = encoded_sequence_dict["special_tokens_mask"] + self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special)) + + filtered_sequence = [x for i, x in enumerate(encoded_sequence_w_special) if not special_tokens_mask[i]] + self.assertEqual(encoded_sequence, filtered_sequence) + + def test_special_tokens_mask_input_pairs(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence_0 = "Encode this." + sequence_1 = "This one too please." + encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False) + encoded_sequence += tokenizer.encode(sequence_1, add_special_tokens=False) + encoded_sequence_dict = tokenizer.encode_plus( + sequence_0, + sequence_1, + add_special_tokens=True, + return_special_tokens_mask=True, + # add_prefix_space=False, + ) + encoded_sequence_w_special = encoded_sequence_dict["input_ids"] + special_tokens_mask = encoded_sequence_dict["special_tokens_mask"] + self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special)) + + filtered_sequence = [ + (x if not special_tokens_mask[i] else None) for i, x in enumerate(encoded_sequence_w_special) + ] + filtered_sequence = [x for x in filtered_sequence if x is not None] + self.assertEqual(encoded_sequence, filtered_sequence) + + def test_padding_side_in_kwargs(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + if self.test_rust_tokenizer: + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, padding_side="left", **kwargs + ) + self.assertEqual(tokenizer_r.padding_side, "left") + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, padding_side="right", **kwargs + ) + self.assertEqual(tokenizer_r.padding_side, "right") + + self.assertRaises( + ValueError, + self.rust_tokenizer_class.from_pretrained, + pretrained_name, + padding_side="unauthorized", + **kwargs, + ) + + if self.test_slow_tokenizer: + tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, padding_side="left", **kwargs) + self.assertEqual(tokenizer_p.padding_side, "left") + + tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, padding_side="right", **kwargs) + self.assertEqual(tokenizer_p.padding_side, "right") + + self.assertRaises( + ValueError, + self.tokenizer_class.from_pretrained, + pretrained_name, + padding_side="unauthorized", + **kwargs, + ) + + def test_truncation_side_in_kwargs(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + if self.test_rust_tokenizer: + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, truncation_side="left", **kwargs + ) + self.assertEqual(tokenizer_r.truncation_side, "left") + + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, truncation_side="right", **kwargs + ) + self.assertEqual(tokenizer_r.truncation_side, "right") + + self.assertRaises( + ValueError, + self.rust_tokenizer_class.from_pretrained, + pretrained_name, + truncation_side="unauthorized", + **kwargs, + ) + + if self.test_slow_tokenizer: + tokenizer_p = self.tokenizer_class.from_pretrained( + pretrained_name, truncation_side="left", **kwargs + ) + self.assertEqual(tokenizer_p.truncation_side, "left") + + tokenizer_p = self.tokenizer_class.from_pretrained( + pretrained_name, truncation_side="right", **kwargs + ) + self.assertEqual(tokenizer_p.truncation_side, "right") + + self.assertRaises( + ValueError, + self.tokenizer_class.from_pretrained, + pretrained_name, + truncation_side="unauthorized", + **kwargs, + ) + + def test_right_and_left_padding(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence = "Sequence" + padding_size = 10 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequence) + + padding_idx = tokenizer.pad_token_id + + # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "right" + encoded_sequence = tokenizer.encode(sequence) + sequence_length = len(encoded_sequence) + padded_sequence = tokenizer.encode( + sequence, max_length=sequence_length + padding_size, padding="max_length" + ) + padded_sequence_length = len(padded_sequence) + self.assertEqual(sequence_length + padding_size, padded_sequence_length) + self.assertEqual(encoded_sequence + [padding_idx] * padding_size, padded_sequence) + + # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "left" + encoded_sequence = tokenizer.encode(sequence) + sequence_length = len(encoded_sequence) + padded_sequence = tokenizer.encode( + sequence, max_length=sequence_length + padding_size, padding="max_length" + ) + padded_sequence_length = len(padded_sequence) + self.assertEqual(sequence_length + padding_size, padded_sequence_length) + self.assertEqual([padding_idx] * padding_size + encoded_sequence, padded_sequence) + + # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding' + encoded_sequence = tokenizer.encode(sequence) + sequence_length = len(encoded_sequence) + + tokenizer.padding_side = "right" + padded_sequence_right = tokenizer.encode(sequence, padding=True) + padded_sequence_right_length = len(padded_sequence_right) + self.assertEqual(sequence_length, padded_sequence_right_length) + self.assertEqual(encoded_sequence, padded_sequence_right) + + tokenizer.padding_side = "left" + padded_sequence_left = tokenizer.encode(sequence, padding="longest") + padded_sequence_left_length = len(padded_sequence_left) + self.assertEqual(sequence_length, padded_sequence_left_length) + self.assertEqual(encoded_sequence, padded_sequence_left) + + tokenizer.padding_side = "right" + padded_sequence_right = tokenizer.encode(sequence) + padded_sequence_right_length = len(padded_sequence_right) + self.assertEqual(sequence_length, padded_sequence_right_length) + self.assertEqual(encoded_sequence, padded_sequence_right) + + tokenizer.padding_side = "left" + padded_sequence_left = tokenizer.encode(sequence, padding=False) + padded_sequence_left_length = len(padded_sequence_left) + self.assertEqual(sequence_length, padded_sequence_left_length) + self.assertEqual(encoded_sequence, padded_sequence_left) + + def test_right_and_left_truncation(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence = "This is a test sequence" + + # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + truncation_size = 3 + tokenizer.truncation_side = "right" + encoded_sequence = tokenizer.encode(sequence, add_special_tokens=False) + sequence_length = len(encoded_sequence) + # Remove EOS/BOS tokens + truncated_sequence = tokenizer.encode( + sequence, max_length=sequence_length - truncation_size, truncation=True, add_special_tokens=False + ) + truncated_sequence_length = len(truncated_sequence) + self.assertEqual(sequence_length, truncated_sequence_length + truncation_size) + self.assertEqual(encoded_sequence[:-truncation_size], truncated_sequence) + + # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the truncation flag set to True + tokenizer.truncation_side = "left" + sequence_length = len(encoded_sequence) + truncated_sequence = tokenizer.encode( + sequence, max_length=sequence_length - truncation_size, truncation=True, add_special_tokens=False + ) + truncated_sequence_length = len(truncated_sequence) + self.assertEqual(sequence_length, truncated_sequence_length + truncation_size) + self.assertEqual(encoded_sequence[truncation_size:], truncated_sequence) + + # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_truncation' + sequence_length = len(encoded_sequence) + + tokenizer.truncation_side = "right" + truncated_sequence_right = tokenizer.encode(sequence, truncation=True, add_special_tokens=False) + truncated_sequence_right_length = len(truncated_sequence_right) + self.assertEqual(sequence_length, truncated_sequence_right_length) + self.assertEqual(encoded_sequence, truncated_sequence_right) + + tokenizer.truncation_side = "left" + truncated_sequence_left = tokenizer.encode( + sequence, truncation="longest_first", add_special_tokens=False + ) + truncated_sequence_left_length = len(truncated_sequence_left) + self.assertEqual(sequence_length, truncated_sequence_left_length) + self.assertEqual(encoded_sequence, truncated_sequence_left) + + tokenizer.truncation_side = "right" + truncated_sequence_right = tokenizer.encode(sequence, add_special_tokens=False) + truncated_sequence_right_length = len(truncated_sequence_right) + self.assertEqual(sequence_length, truncated_sequence_right_length) + self.assertEqual(encoded_sequence, truncated_sequence_right) + + tokenizer.truncation_side = "left" + truncated_sequence_left = tokenizer.encode(sequence, truncation=False, add_special_tokens=False) + truncated_sequence_left_length = len(truncated_sequence_left) + self.assertEqual(sequence_length, truncated_sequence_left_length) + self.assertEqual(encoded_sequence, truncated_sequence_left) + + def test_padding_to_max_length(self): + """We keep this test for backward compatibility but it should be remove when `pad_to_max_length` is deprecated.""" + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence = "Sequence" + padding_size = 10 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequence) + + padding_idx = tokenizer.pad_token_id + + # Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "right" + encoded_sequence = tokenizer.encode(sequence) + sequence_length = len(encoded_sequence) + # FIXME: the next line should be padding(max_length) to avoid warning + padded_sequence = tokenizer.encode( + sequence, max_length=sequence_length + padding_size, pad_to_max_length=True + ) + padded_sequence_length = len(padded_sequence) + self.assertEqual(sequence_length + padding_size, padded_sequence_length) + self.assertEqual(encoded_sequence + [padding_idx] * padding_size, padded_sequence) + + # Check that nothing is done when a maximum length is not specified + encoded_sequence = tokenizer.encode(sequence) + sequence_length = len(encoded_sequence) + + tokenizer.padding_side = "right" + padded_sequence_right = tokenizer.encode(sequence, pad_to_max_length=True) + padded_sequence_right_length = len(padded_sequence_right) + self.assertEqual(sequence_length, padded_sequence_right_length) + self.assertEqual(encoded_sequence, padded_sequence_right) + + def test_padding_to_multiple_of(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.pad_token is None: + self.skipTest("No padding token.") + else: + empty_tokens = tokenizer("", padding=True, pad_to_multiple_of=8) + normal_tokens = tokenizer("This is a sample input", padding=True, pad_to_multiple_of=8) + for key, value in empty_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + normal_tokens = tokenizer("This", pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # Should also work with truncation + normal_tokens = tokenizer("This", padding=True, truncation=True, pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # truncation to something which is not a multiple of pad_to_multiple_of raises an error + self.assertRaises( + ValueError, + tokenizer.__call__, + "This", + padding=True, + truncation=True, + max_length=12, + pad_to_multiple_of=8, + ) + + def test_padding_with_attention_mask(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.pad_token is None: + self.skipTest("No padding token.") + if "attention_mask" not in tokenizer.model_input_names: + self.skipTest("This model does not use attention mask.") + + features = [ + {"input_ids": [1, 2, 3, 4, 5, 6], "attention_mask": [1, 1, 1, 1, 1, 0]}, + {"input_ids": [1, 2, 3], "attention_mask": [1, 1, 0]}, + ] + padded_features = tokenizer.pad(features) + if tokenizer.padding_side == "right": + self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0]]) + else: + self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0]]) + + def test_encode_plus_with_padding(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence = "Sequence" + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequence) + + padding_size = 10 + padding_idx = tokenizer.pad_token_id + token_type_padding_idx = tokenizer.pad_token_type_id + + encoded_sequence = tokenizer.encode_plus(sequence, return_special_tokens_mask=True) + input_ids = encoded_sequence["input_ids"] + special_tokens_mask = encoded_sequence["special_tokens_mask"] + sequence_length = len(input_ids) + + # Test 'longest' and 'no_padding' don't do anything + tokenizer.padding_side = "right" + + not_padded_sequence = tokenizer.encode_plus( + sequence, + padding=True, + return_special_tokens_mask=True, + ) + not_padded_input_ids = not_padded_sequence["input_ids"] + + not_padded_special_tokens_mask = not_padded_sequence["special_tokens_mask"] + not_padded_sequence_length = len(not_padded_input_ids) + + self.assertEqual(sequence_length, not_padded_sequence_length) + self.assertEqual(input_ids, not_padded_input_ids) + self.assertEqual(special_tokens_mask, not_padded_special_tokens_mask) + + not_padded_sequence = tokenizer.encode_plus( + sequence, + padding=False, + return_special_tokens_mask=True, + ) + not_padded_input_ids = not_padded_sequence["input_ids"] + + not_padded_special_tokens_mask = not_padded_sequence["special_tokens_mask"] + not_padded_sequence_length = len(not_padded_input_ids) + + self.assertEqual(sequence_length, not_padded_sequence_length) + self.assertEqual(input_ids, not_padded_input_ids) + self.assertEqual(special_tokens_mask, not_padded_special_tokens_mask) + + # Test right padding + tokenizer.padding_side = "right" + + right_padded_sequence = tokenizer.encode_plus( + sequence, + max_length=sequence_length + padding_size, + padding="max_length", + return_special_tokens_mask=True, + ) + right_padded_input_ids = right_padded_sequence["input_ids"] + + right_padded_special_tokens_mask = right_padded_sequence["special_tokens_mask"] + right_padded_sequence_length = len(right_padded_input_ids) + + self.assertEqual(sequence_length + padding_size, right_padded_sequence_length) + self.assertEqual(input_ids + [padding_idx] * padding_size, right_padded_input_ids) + self.assertEqual(special_tokens_mask + [1] * padding_size, right_padded_special_tokens_mask) + + # Test left padding + tokenizer.padding_side = "left" + left_padded_sequence = tokenizer.encode_plus( + sequence, + max_length=sequence_length + padding_size, + padding="max_length", + return_special_tokens_mask=True, + ) + left_padded_input_ids = left_padded_sequence["input_ids"] + left_padded_special_tokens_mask = left_padded_sequence["special_tokens_mask"] + left_padded_sequence_length = len(left_padded_input_ids) + + self.assertEqual(sequence_length + padding_size, left_padded_sequence_length) + self.assertEqual([padding_idx] * padding_size + input_ids, left_padded_input_ids) + self.assertEqual([1] * padding_size + special_tokens_mask, left_padded_special_tokens_mask) + + if "token_type_ids" in tokenizer.model_input_names: + token_type_ids = encoded_sequence["token_type_ids"] + left_padded_token_type_ids = left_padded_sequence["token_type_ids"] + right_padded_token_type_ids = right_padded_sequence["token_type_ids"] + + self.assertEqual( + token_type_ids + [token_type_padding_idx] * padding_size, right_padded_token_type_ids + ) + self.assertEqual( + [token_type_padding_idx] * padding_size + token_type_ids, left_padded_token_type_ids + ) + + if "attention_mask" in tokenizer.model_input_names: + attention_mask = encoded_sequence["attention_mask"] + right_padded_attention_mask = right_padded_sequence["attention_mask"] + left_padded_attention_mask = left_padded_sequence["attention_mask"] + + self.assertEqual(attention_mask + [0] * padding_size, right_padded_attention_mask) + self.assertEqual([0] * padding_size + attention_mask, left_padded_attention_mask) + + def test_padding_warning_message_fast_tokenizer(self): + if not self.test_rust_tokenizer: + return + + sequence = "This is a text" + + tokenizer_fast = self.get_rust_tokenizer() + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer_fast, sequence) + + encoding_fast = tokenizer_fast(sequence) + + with self.assertLogs("transformers", level="WARNING") as cm: + tokenizer_fast.pad(encoding_fast) + self.assertEqual(len(cm.records), 1) + self.assertIn( + "Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to" + " encode the text followed by a call to the `pad` method to get a padded encoding.", + cm.records[0].message, + ) + + if not self.test_slow_tokenizer: + return + + tokenizer_slow = self.get_tokenizer() + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer_slow, sequence) + + encoding_slow = tokenizer_slow(sequence) + + with self.assertLogs(level="WARNING") as cm: + # We want to assert there are no warnings, but the 'assertLogs' method does not support that. + # Therefore, we are adding a dummy warning, and then we will assert it is the only warning. + logger.warning("Dummy warning") + tokenizer_slow.pad(encoding_slow) + self.assertEqual(len(cm.records), 1) + self.assertIn( + "Dummy warning", + cm.records[0].message, + ) + + def test_separate_tokenizers(self): + # This tests that tokenizers don't impact others. Unfortunately the case where it fails is when + # we're loading an S3 configuration from a pre-trained identifier, and we have no way of testing those today. + + tokenizers = self.get_tokenizers(random_argument=True) + new_tokenizers = self.get_tokenizers(random_argument=False) + + for tokenizer, new_tokenizer in zip(tokenizers, new_tokenizers): + with self.subTest(f"{tokenizer.__class__.__name__}"): + self.assertTrue(tokenizer.init_kwargs["random_argument"]) + self.assertTrue(tokenizer.init_kwargs["random_argument"]) + self.assertFalse(new_tokenizer.init_kwargs["random_argument"]) + + 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() + self.assertIsInstance(vocab_dict, dict) + self.assertGreaterEqual(len(tokenizer), len(vocab_dict)) + + vocab = [tokenizer.convert_ids_to_tokens(i) for i in range(len(tokenizer))] + self.assertEqual(len(vocab), len(tokenizer)) + + tokenizer.add_tokens(["asdfasdfasdfasdf"]) + vocab = [tokenizer.convert_ids_to_tokens(i) for i in range(len(tokenizer))] + self.assertEqual(len(vocab), len(tokenizer)) + + 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() + for word, ind in vocab.items(): + if word == tokenizer.unk_token: + continue + self.assertEqual(tokenizer.convert_tokens_to_ids(word), ind) + self.assertEqual(tokenizer.convert_ids_to_tokens(ind), word) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + # Test not batched + encoded_sequences_1 = tokenizer.encode_plus(sequences[0]) + encoded_sequences_2 = tokenizer(sequences[0]) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + # Test not batched pairs + encoded_sequences_1 = tokenizer.encode_plus(sequences[0], sequences[1]) + encoded_sequences_2 = tokenizer(sequences[0], sequences[1]) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + # Test batched + encoded_sequences_1 = tokenizer.batch_encode_plus(sequences) + encoded_sequences_2 = tokenizer(sequences) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + # Test batched pairs + encoded_sequences_1 = tokenizer.batch_encode_plus(list(zip(sequences, sequences))) + encoded_sequences_2 = tokenizer(sequences, sequences) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + def test_batch_encode_plus_batch_sequence_length(self): + # Tests that all encoded values have the correct size + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + encoded_sequences = [tokenizer.encode_plus(sequence) for sequence in sequences] + encoded_sequences_batch = tokenizer.batch_encode_plus(sequences, padding=False) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + maximum_length = len( + max([encoded_sequence["input_ids"] for encoded_sequence in encoded_sequences], key=len) + ) + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences_padded = [ + tokenizer.encode_plus(sequence, max_length=maximum_length, padding="max_length") + for sequence in sequences + ] + + encoded_sequences_batch_padded = tokenizer.batch_encode_plus(sequences, padding=True) + self.assertListEqual( + encoded_sequences_padded, + self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch_padded), + ) + + # check 'longest' is unsensitive to a max length + encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(sequences, padding=True) + encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus( + sequences, max_length=maximum_length + 10, padding="longest" + ) + for key in encoded_sequences_batch_padded_1.keys(): + self.assertListEqual( + encoded_sequences_batch_padded_1[key], + encoded_sequences_batch_padded_2[key], + ) + + # check 'no_padding' is unsensitive to a max length + encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(sequences, padding=False) + encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus( + sequences, max_length=maximum_length + 10, padding=False + ) + for key in encoded_sequences_batch_padded_1.keys(): + self.assertListEqual( + encoded_sequences_batch_padded_1[key], + encoded_sequences_batch_padded_2[key], + ) + + @require_tokenizers + def test_added_token_are_matched_longest_first(self): + if not self.test_slow_tokenizer: + self.skipTest("This test is only for slow tokenizers") + return + tokenizers = self.get_tokenizers(fast=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + try: + tokenizer.add_tokens([AddedToken("extra_id_1")]) + tokenizer.add_tokens([AddedToken("extra_id_100")]) + except Exception: + # Canine cannot add tokens which are not codepoints + self.skipTest("Cannot add those Added tokens") + + # XXX: This used to split on `extra_id_1` first we're matching + # longest first now. + tokens = tokenizer.tokenize("This is some extra_id_100") + self.assertIn("extra_id_100", tokens) + + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokenizer.add_tokens([AddedToken("extra_id_100")]) + tokenizer.add_tokens([AddedToken("extra_id_1")]) + + tokens = tokenizer.tokenize("This is some extra_id_100") + self.assertIn("extra_id_100", tokens) + + @require_tokenizers + def test_added_token_serializable(self): + # TODO this is tested 10_000 times.... + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + new_token = AddedToken("new_token", lstrip=True) + tokenizer.add_tokens([new_token]) + + with tempfile.TemporaryDirectory() as tmp_dir_name: + tokenizer.save_pretrained(tmp_dir_name) + tokenizer.from_pretrained(tmp_dir_name) + + def test_batch_encode_plus_padding(self): + # Test that padded sequences are equivalent between batch_encode_plus and encode_plus + + # Right padding tests + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + max_length = 100 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences = [ + tokenizer.encode_plus(sequence, max_length=max_length, padding="max_length") + for sequence in sequences + ] + encoded_sequences_batch = tokenizer.batch_encode_plus( + sequences, max_length=max_length, padding="max_length" + ) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + # Left padding tests + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokenizer.padding_side = "left" + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + max_length = 100 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences = [ + tokenizer.encode_plus(sequence, max_length=max_length, padding="max_length") + for sequence in sequences + ] + encoded_sequences_batch = tokenizer.batch_encode_plus( + sequences, max_length=max_length, padding="max_length" + ) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + def test_pretokenized_inputs(self): + # Test when inputs are pretokenized + + tokenizers = self.get_tokenizers(do_lower_case=False) # , add_prefix_space=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if hasattr(tokenizer, "add_prefix_space") and not tokenizer.add_prefix_space: + continue + + # Prepare a sequence from our tokenizer vocabulary + sequence, ids = self.get_clean_sequence(tokenizer, with_prefix_space=True, max_length=20) + # sequence = " " + sequence # To be sure the byte-level tokenizers are feeling good + token_sequence = sequence.split() + # sequence_no_prefix_space = sequence.strip() + + # Test encode for pretokenized inputs + output = tokenizer.encode(token_sequence, is_split_into_words=True, add_special_tokens=False) + output_sequence = tokenizer.encode(sequence, add_special_tokens=False) + self.assertEqual(output, output_sequence) + + output = tokenizer.encode(token_sequence, is_split_into_words=True, add_special_tokens=True) + output_sequence = tokenizer.encode(sequence, add_special_tokens=True) + self.assertEqual(output, output_sequence) + + # Test encode_plus for pretokenized inputs + output = tokenizer.encode_plus(token_sequence, is_split_into_words=True, add_special_tokens=False) + output_sequence = tokenizer.encode_plus(sequence, add_special_tokens=False) + for key in output.keys(): + self.assertEqual(output[key], output_sequence[key]) + output = tokenizer.encode_plus(token_sequence, is_split_into_words=True, add_special_tokens=True) + output_sequence = tokenizer.encode_plus(sequence, add_special_tokens=True) + for key in output.keys(): + self.assertEqual(output[key], output_sequence[key]) + + # Test batch_encode_plus for pretokenized inputs + sequence_batch = [sequence.strip()] * 2 + [sequence.strip() + " " + sequence.strip()] + token_sequence_batch = [s.split() for s in sequence_batch] + sequence_batch_cleaned_up_spaces = [" " + " ".join(s) for s in token_sequence_batch] + + output = tokenizer.batch_encode_plus( + token_sequence_batch, is_split_into_words=True, add_special_tokens=False + ) + output_sequence = tokenizer.batch_encode_plus( + sequence_batch_cleaned_up_spaces, add_special_tokens=False + ) + for key in output.keys(): + self.assertEqual(output[key], output_sequence[key]) + output = tokenizer.batch_encode_plus( + token_sequence_batch, is_split_into_words=True, add_special_tokens=True + ) + output_sequence = tokenizer.batch_encode_plus( + sequence_batch_cleaned_up_spaces, add_special_tokens=True + ) + for key in output.keys(): + self.assertEqual(output[key], output_sequence[key]) + + # Test encode for pretokenized inputs pairs + output = tokenizer.encode( + token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=False + ) + output_sequence = tokenizer.encode(sequence, sequence, add_special_tokens=False) + self.assertEqual(output, output_sequence) + output = tokenizer.encode( + token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=True + ) + output_sequence = tokenizer.encode(sequence, sequence, add_special_tokens=True) + self.assertEqual(output, output_sequence) + + # Test encode_plus for pretokenized inputs pairs + output = tokenizer.encode_plus( + token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=False + ) + output_sequence = tokenizer.encode_plus(sequence, sequence, add_special_tokens=False) + for key in output.keys(): + self.assertEqual(output[key], output_sequence[key]) + output = tokenizer.encode_plus( + token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=True + ) + output_sequence = tokenizer.encode_plus(sequence, sequence, add_special_tokens=True) + for key in output.keys(): + self.assertEqual(output[key], output_sequence[key]) + + # Test batch_encode_plus for pretokenized inputs pairs + sequence_pair_batch = [(sequence.strip(), sequence.strip())] * 2 + [ + (sequence.strip() + " " + sequence.strip(), sequence.strip()) + ] + token_sequence_pair_batch = [tuple(s.split() for s in pair) for pair in sequence_pair_batch] + sequence_pair_batch_cleaned_up_spaces = [ + tuple(" " + " ".join(s) for s in pair) for pair in token_sequence_pair_batch + ] + + output = tokenizer.batch_encode_plus( + token_sequence_pair_batch, is_split_into_words=True, add_special_tokens=False + ) + output_sequence = tokenizer.batch_encode_plus( + sequence_pair_batch_cleaned_up_spaces, add_special_tokens=False + ) + for key in output.keys(): + self.assertEqual(output[key], output_sequence[key]) + output = tokenizer.batch_encode_plus( + token_sequence_pair_batch, is_split_into_words=True, add_special_tokens=True + ) + output_sequence = tokenizer.batch_encode_plus( + sequence_pair_batch_cleaned_up_spaces, add_special_tokens=True + ) + for key in output.keys(): + self.assertEqual(output[key], output_sequence[key]) + + def test_prepare_for_model(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + string_sequence = "Testing the prepare_for_model method." + ids = tokenizer.encode(string_sequence, add_special_tokens=False) + prepared_input_dict = tokenizer.prepare_for_model(ids, add_special_tokens=True) + + input_dict = tokenizer.encode_plus(string_sequence, add_special_tokens=True) + + self.assertEqual(input_dict, prepared_input_dict) + + def test_batch_encode_plus_overflowing_tokens(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + string_sequences = ["Testing the prepare_for_model method.", "Test"] + + if tokenizer.pad_token is None: + tokenizer.add_special_tokens({"pad_token": "[PAD]"}) + + tokenizer.batch_encode_plus( + string_sequences, return_overflowing_tokens=True, truncation=True, padding=True, max_length=3 + ) + + @is_pt_tf_cross_test + def test_batch_encode_plus_tensors(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + # A Tensor cannot be build by sequences which are not the same size + self.assertRaises(ValueError, tokenizer.batch_encode_plus, sequences, return_tensors="pt") + self.assertRaises(ValueError, tokenizer.batch_encode_plus, sequences, return_tensors="tf") + + if tokenizer.pad_token_id is None: + self.assertRaises( + ValueError, + tokenizer.batch_encode_plus, + sequences, + padding=True, + return_tensors="pt", + ) + self.assertRaises( + ValueError, + tokenizer.batch_encode_plus, + sequences, + padding="longest", + return_tensors="tf", + ) + else: + pytorch_tensor = tokenizer.batch_encode_plus(sequences, padding=True, return_tensors="pt") + tensorflow_tensor = tokenizer.batch_encode_plus(sequences, padding="longest", return_tensors="tf") + encoded_sequences = tokenizer.batch_encode_plus(sequences, padding=True) + + for key in encoded_sequences.keys(): + pytorch_value = pytorch_tensor[key].tolist() + tensorflow_value = tensorflow_tensor[key].numpy().tolist() + encoded_value = encoded_sequences[key] + + self.assertEqual(pytorch_value, tensorflow_value, encoded_value) + + def _check_no_pad_token_padding(self, tokenizer, sequences): + # if tokenizer does not have pad_token_id, an error should be thrown + if tokenizer.pad_token_id is None: + with self.assertRaises(ValueError): + if isinstance(sequences, list): + tokenizer.batch_encode_plus(sequences, padding="longest") + else: + tokenizer.encode_plus(sequences, padding=True) + + # add pad_token_id to pass subsequent tests + tokenizer.add_special_tokens({"pad_token": ""}) + + @require_torch + @slow + def test_torch_encode_plus_sent_to_model(self): + import torch + + from transformers import MODEL_MAPPING, TOKENIZER_MAPPING + + MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING) + + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING: + return + + config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__] + config = config_class() + + if config.is_encoder_decoder or config.pad_token_id is None: + return + + model = model_class(config) + + # Make sure the model contains at least the full vocabulary size in its embedding matrix + is_using_common_embeddings = hasattr(model.get_input_embeddings(), "weight") + if is_using_common_embeddings: + self.assertGreaterEqual(model.get_input_embeddings().weight.shape[0], len(tokenizer)) + + # Build sequence + first_ten_tokens = list(tokenizer.get_vocab().keys())[:10] + sequence = " ".join(first_ten_tokens) + encoded_sequence = tokenizer.encode_plus(sequence, return_tensors="pt") + + # Ensure that the BatchEncoding.to() method works. + encoded_sequence.to(model.device) + + batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors="pt") + # This should not fail + + with torch.no_grad(): # saves some time + model(**encoded_sequence) + model(**batch_encoded_sequence) + + # if self.test_rust_tokenizer: + # fast_tokenizer = self.get_rust_tokenizer() + # encoded_sequence_fast = fast_tokenizer.encode_plus(sequence, return_tensors="pt") + # batch_encoded_sequence_fast = fast_tokenizer.batch_encode_plus([sequence, sequence], return_tensors="pt") + # # This should not fail + # model(**encoded_sequence_fast) + # model(**batch_encoded_sequence_fast) + + @require_tf + @slow + def test_tf_encode_plus_sent_to_model(self): + from transformers import TF_MODEL_MAPPING, TOKENIZER_MAPPING + + MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(TF_MODEL_MAPPING, TOKENIZER_MAPPING) + + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING: + return + + config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__] + config = config_class() + + if config.is_encoder_decoder or config.pad_token_id is None: + return + + model = model_class(config) + + # Make sure the model contains at least the full vocabulary size in its embedding matrix + self.assertGreaterEqual(model.config.vocab_size, len(tokenizer)) + + # Build sequence + first_ten_tokens = list(tokenizer.get_vocab().keys())[:10] + sequence = " ".join(first_ten_tokens) + encoded_sequence = tokenizer.encode_plus(sequence, return_tensors="tf") + batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors="tf") + + # This should not fail + model(encoded_sequence) + model(batch_encoded_sequence) + + # TODO: Check if require_torch is the best to test for numpy here ... Maybe move to require_flax when available + @require_torch + @slow + def test_np_encode_plus_sent_to_model(self): + from transformers import MODEL_MAPPING, TOKENIZER_MAPPING + + MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING) + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING: + return + + config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__] + config = config_class() + + if config.is_encoder_decoder or config.pad_token_id is None: + return + + # Build sequence + first_ten_tokens = list(tokenizer.get_vocab().keys())[:10] + sequence = " ".join(first_ten_tokens) + encoded_sequence = tokenizer.encode_plus(sequence, return_tensors="np") + batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors="np") + + # TODO: add forward through JAX/Flax when PR is merged + # This is currently here to make ruff happy ! + if encoded_sequence is None: + raise ValueError("Cannot convert list to numpy tensor on encode_plus()") + + if batch_encoded_sequence is None: + raise ValueError("Cannot convert list to numpy tensor on batch_encode_plus()") + + if self.test_rust_tokenizer: + fast_tokenizer = self.get_rust_tokenizer() + encoded_sequence_fast = fast_tokenizer.encode_plus(sequence, return_tensors="np") + batch_encoded_sequence_fast = fast_tokenizer.batch_encode_plus( + [sequence, sequence], return_tensors="np" + ) + + # TODO: add forward through JAX/Flax when PR is merged + # This is currently here to make ruff happy ! + if encoded_sequence_fast is None: + raise ValueError("Cannot convert list to numpy tensor on encode_plus() (fast)") + + if batch_encoded_sequence_fast is None: + raise ValueError("Cannot convert list to numpy tensor on batch_encode_plus() (fast)") + + @require_torch + def test_prepare_seq2seq_batch(self): + if not self.test_seq2seq: + return + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Longer text that will definitely require truncation. + src_text = [ + " UN Chief Says There Is No Military Solution in Syria", + " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for" + " Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons" + " will only worsen the violence and misery for millions of people.", + ] + tgt_text = [ + "Şeful ONU declară că nu există o soluţie militară în Siria", + "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al" + ' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi' + " că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", + ] + try: + batch = tokenizer.prepare_seq2seq_batch( + src_texts=src_text, + tgt_texts=tgt_text, + max_length=3, + max_target_length=10, + return_tensors="pt", + src_lang="en_XX", # this should be ignored (for all but mbart) but not cause an error + ) + except NotImplementedError: + return + self.assertEqual(batch.input_ids.shape[1], 3) + self.assertEqual(batch.labels.shape[1], 10) + # max_target_length will default to max_length if not specified + batch = tokenizer.prepare_seq2seq_batch( + src_text, tgt_texts=tgt_text, max_length=3, return_tensors="pt" + ) + self.assertEqual(batch.input_ids.shape[1], 3) + self.assertEqual(batch.labels.shape[1], 3) + + batch_encoder_only = tokenizer.prepare_seq2seq_batch( + src_texts=src_text, max_length=3, max_target_length=10, return_tensors="pt" + ) + self.assertEqual(batch_encoder_only.input_ids.shape[1], 3) + self.assertEqual(batch_encoder_only.attention_mask.shape[1], 3) + self.assertNotIn("decoder_input_ids", batch_encoder_only) + + def test_is_fast(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) + # Check is_fast is set correctly + self.assertTrue(tokenizer_r.is_fast) + + if self.test_slow_tokenizer: + tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs) + self.assertFalse(tokenizer_p.is_fast) + + def test_fast_only_inputs(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) + + # Ensure None raise an error + self.assertRaises(TypeError, tokenizer_r.tokenize, None) + self.assertRaises(TypeError, tokenizer_r.encode, None) + self.assertRaises(TypeError, tokenizer_r.encode_plus, None) + self.assertRaises(TypeError, tokenizer_r.batch_encode_plus, None) + + def test_alignement_methods(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) + + words = ["Wonderful", "no", "inspiration", "example", "with", "subtoken"] + text = " ".join(words) + batch_size = 3 + + encoding = tokenizer_r.encode_plus(text, add_special_tokens=False) + + batch_encoding = tokenizer_r.batch_encode_plus([text] * batch_size, add_special_tokens=False) + num_tokens = len(encoding["input_ids"]) + + last_word_index = len(words) - 1 + last_token_index = num_tokens - 1 + last_batch_index = batch_size - 1 + last_char_index = len(text) - 1 + + # words, tokens + self.assertEqual(len(encoding.words(0)), num_tokens) + self.assertEqual(max(encoding.words(0)), last_word_index) + self.assertEqual(min(encoding.words(0)), 0) + self.assertEqual(len(batch_encoding.words(last_batch_index)), num_tokens) + self.assertEqual(max(batch_encoding.words(last_batch_index)), last_word_index) + self.assertEqual(min(batch_encoding.words(last_batch_index)), 0) + self.assertEqual(len(encoding.tokens(0)), num_tokens) + + # Assert token_to_word + self.assertEqual(encoding.token_to_word(0), 0) + self.assertEqual(encoding.token_to_word(0, 0), 0) + self.assertEqual(encoding.token_to_word(last_token_index), last_word_index) + self.assertEqual(encoding.token_to_word(0, last_token_index), last_word_index) + self.assertEqual(batch_encoding.token_to_word(1, 0), 0) + self.assertEqual(batch_encoding.token_to_word(0, last_token_index), last_word_index) + self.assertEqual(batch_encoding.token_to_word(last_batch_index, last_token_index), last_word_index) + + # Assert word_to_tokens + self.assertEqual(encoding.word_to_tokens(0).start, 0) + self.assertEqual(encoding.word_to_tokens(0, 0).start, 0) + self.assertEqual(encoding.word_to_tokens(last_word_index).end, last_token_index + 1) + self.assertEqual(encoding.word_to_tokens(0, last_word_index).end, last_token_index + 1) + self.assertEqual(batch_encoding.word_to_tokens(1, 0).start, 0) + self.assertEqual(batch_encoding.word_to_tokens(0, last_word_index).end, last_token_index + 1) + self.assertEqual( + batch_encoding.word_to_tokens(last_batch_index, last_word_index).end, last_token_index + 1 + ) + + # Assert token_to_chars + self.assertEqual(encoding.token_to_chars(0).start, 0) + self.assertEqual(encoding.token_to_chars(0, 0).start, 0) + self.assertEqual(encoding.token_to_chars(last_token_index).end, last_char_index + 1) + self.assertEqual(encoding.token_to_chars(0, last_token_index).end, last_char_index + 1) + self.assertEqual(batch_encoding.token_to_chars(1, 0).start, 0) + self.assertEqual(batch_encoding.token_to_chars(0, last_token_index).end, last_char_index + 1) + self.assertEqual( + batch_encoding.token_to_chars(last_batch_index, last_token_index).end, last_char_index + 1 + ) + + # Assert char_to_token + self.assertEqual(encoding.char_to_token(0), 0) + self.assertEqual(encoding.char_to_token(0, 0), 0) + self.assertEqual(encoding.char_to_token(last_char_index), last_token_index) + self.assertEqual(encoding.char_to_token(0, last_char_index), last_token_index) + self.assertEqual(batch_encoding.char_to_token(1, 0), 0) + self.assertEqual(batch_encoding.char_to_token(0, last_char_index), last_token_index) + self.assertEqual(batch_encoding.char_to_token(last_batch_index, last_char_index), last_token_index) + + # Assert char_to_word + self.assertEqual(encoding.char_to_word(0), 0) + self.assertEqual(encoding.char_to_word(0, 0), 0) + self.assertEqual(encoding.char_to_word(last_char_index), last_word_index) + self.assertEqual(encoding.char_to_word(0, last_char_index), last_word_index) + self.assertEqual(batch_encoding.char_to_word(1, 0), 0) + self.assertEqual(batch_encoding.char_to_word(0, last_char_index), last_word_index) + self.assertEqual(batch_encoding.char_to_word(last_batch_index, last_char_index), last_word_index) + + # Assert word_to_chars + self.assertEqual(encoding.word_to_chars(0).start, 0) + self.assertEqual(encoding.word_to_chars(0, 0).start, 0) + self.assertEqual(encoding.word_to_chars(last_word_index).end, last_char_index + 1) + self.assertEqual(encoding.word_to_chars(0, last_word_index).end, last_char_index + 1) + self.assertEqual(batch_encoding.word_to_chars(1, 0).start, 0) + self.assertEqual(batch_encoding.word_to_chars(0, last_word_index).end, last_char_index + 1) + self.assertEqual( + batch_encoding.word_to_chars(last_batch_index, last_word_index).end, last_char_index + 1 + ) + + # Assert token_to_sequence + self.assertEqual(encoding.token_to_sequence(num_tokens // 2), 0) + self.assertEqual(encoding.token_to_sequence(0, num_tokens // 2), 0) + self.assertEqual(batch_encoding.token_to_sequence(1, num_tokens // 2), 0) + self.assertEqual(batch_encoding.token_to_sequence(0, num_tokens // 2), 0) + self.assertEqual(batch_encoding.token_to_sequence(last_batch_index, num_tokens // 2), 0) + + # Pair of input sequences + + words = ["Wonderful", "no", "inspiration", "example", "with", "subtoken"] + text = " ".join(words) + pair_words = ["Amazing", "example", "full", "of", "inspiration"] + pair_text = " ".join(pair_words) + batch_size = 3 + index_word_in_first_seq = words.index("inspiration") + index_word_in_pair_seq = pair_words.index("inspiration") + index_char_in_first_seq = text.find("inspiration") + index_char_in_pair_seq = pair_text.find("inspiration") + + pair_encoding = tokenizer_r.encode_plus(text, pair_text, add_special_tokens=False) + + pair_batch_encoding = tokenizer_r.batch_encode_plus( + [(text, pair_text)] * batch_size, add_special_tokens=False + ) + num_tokens = len(encoding["input_ids"]) + + last_word_index = len(words) - 1 + last_token_index = num_tokens - 1 + last_batch_index = batch_size - 1 + last_char_index = len(text) - 1 + + # Assert word_to_tokens + self.assertNotEqual( + pair_encoding.word_to_tokens(index_word_in_first_seq, sequence_index=0).start, + pair_encoding.word_to_tokens(index_word_in_pair_seq, sequence_index=1).start, + ) + self.assertEqual( + pair_encoding["input_ids"][ + pair_encoding.word_to_tokens(index_word_in_first_seq, sequence_index=0).start + ], + pair_encoding["input_ids"][ + pair_encoding.word_to_tokens(index_word_in_pair_seq, sequence_index=1).start + ], + ) + self.assertNotEqual( + pair_batch_encoding.word_to_tokens(1, index_word_in_first_seq, sequence_index=0).start, + pair_batch_encoding.word_to_tokens(1, index_word_in_pair_seq, sequence_index=1).start, + ) + self.assertEqual( + pair_batch_encoding["input_ids"][1][ + pair_batch_encoding.word_to_tokens(1, index_word_in_first_seq, sequence_index=0).start + ], + pair_batch_encoding["input_ids"][1][ + pair_batch_encoding.word_to_tokens(1, index_word_in_pair_seq, sequence_index=1).start + ], + ) + + # Assert char_to_token + self.assertNotEqual( + pair_encoding.char_to_token(index_char_in_first_seq, sequence_index=0), + pair_encoding.char_to_token(index_char_in_pair_seq, sequence_index=1), + ) + self.assertEqual( + pair_encoding["input_ids"][pair_encoding.char_to_token(index_char_in_first_seq, sequence_index=0)], + pair_encoding["input_ids"][pair_encoding.char_to_token(index_char_in_pair_seq, sequence_index=1)], + ) + self.assertNotEqual( + pair_batch_encoding.char_to_token(1, index_char_in_first_seq, sequence_index=0), + pair_batch_encoding.char_to_token(1, index_char_in_pair_seq, sequence_index=1), + ) + self.assertEqual( + pair_batch_encoding["input_ids"][1][ + pair_batch_encoding.char_to_token(1, index_char_in_first_seq, sequence_index=0) + ], + pair_batch_encoding["input_ids"][1][ + pair_batch_encoding.char_to_token(1, index_char_in_pair_seq, sequence_index=1) + ], + ) + + # Assert char_to_word + self.assertNotEqual( + pair_encoding.char_to_word(index_char_in_first_seq, sequence_index=0), + pair_encoding.char_to_word(index_char_in_pair_seq, sequence_index=1), + ) + self.assertEqual( + words[pair_encoding.char_to_word(index_char_in_first_seq, sequence_index=0)], + pair_words[pair_encoding.char_to_word(index_char_in_pair_seq, sequence_index=1)], + ) + self.assertNotEqual( + pair_batch_encoding.char_to_word(1, index_char_in_first_seq, sequence_index=0), + pair_batch_encoding.char_to_word(1, index_char_in_pair_seq, sequence_index=1), + ) + self.assertEqual( + words[pair_batch_encoding.char_to_word(1, index_char_in_first_seq, sequence_index=0)], + pair_words[pair_batch_encoding.char_to_word(1, index_char_in_pair_seq, sequence_index=1)], + ) + + # Assert word_to_chars + self.assertNotEqual( + pair_encoding.word_to_chars(index_word_in_first_seq, sequence_index=0).start, + pair_encoding.word_to_chars(index_word_in_pair_seq, sequence_index=1).start, + ) + self.assertEqual( + text[pair_encoding.word_to_chars(index_word_in_first_seq, sequence_index=0).start], + pair_text[pair_encoding.word_to_chars(index_word_in_pair_seq, sequence_index=1).start], + ) + self.assertNotEqual( + pair_batch_encoding.word_to_chars(1, index_word_in_first_seq, sequence_index=0).start, + pair_batch_encoding.word_to_chars(1, index_word_in_pair_seq, sequence_index=1).start, + ) + self.assertEqual( + text[pair_batch_encoding.word_to_chars(1, index_word_in_first_seq, sequence_index=0).start], + pair_text[pair_batch_encoding.word_to_chars(1, index_word_in_pair_seq, sequence_index=1).start], + ) + + # Assert token_to_sequence + pair_encoding = tokenizer_r.encode_plus(text, pair_text, add_special_tokens=True) + + pair_sequence_ids = [ + pair_encoding.token_to_sequence(i) for i in range(len(pair_encoding["input_ids"])) + ] + self.assertIn(0, pair_sequence_ids) + self.assertIn(1, pair_sequence_ids) + if tokenizer_r.num_special_tokens_to_add(pair=True): + self.assertIn(None, pair_sequence_ids) + + pair_batch_encoding = tokenizer_r.batch_encode_plus( + [(text, pair_text)] * batch_size, add_special_tokens=True + ) + pair_batch_sequence_ids = [ + pair_batch_encoding.token_to_sequence(1, i) + for i in range(len(pair_batch_encoding["input_ids"][0])) + ] + self.assertIn(0, pair_batch_sequence_ids) + self.assertIn(1, pair_batch_sequence_ids) + if tokenizer_r.num_special_tokens_to_add(pair=True): + self.assertIn(None, pair_batch_sequence_ids) + + def test_tokenization_python_rust_equals(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + + # Ensure basic input match + input_p = tokenizer_p.encode_plus(self._data) + input_r = tokenizer_r.encode_plus(self._data) + + for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()): + self.assertSequenceEqual(input_p[key], input_r[key]) + + input_pairs_p = tokenizer_p.encode_plus(self._data, self._data) + input_pairs_r = tokenizer_r.encode_plus(self._data, self._data) + + for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()): + self.assertSequenceEqual(input_pairs_p[key], input_pairs_r[key]) + + # Ensure truncation match + input_p = tokenizer_p.encode_plus(self._data, max_length=512, truncation=True) + input_r = tokenizer_r.encode_plus(self._data, max_length=512, truncation=True) + + for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()): + self.assertSequenceEqual(input_p[key], input_r[key]) + + # Ensure truncation with stride match + input_p = tokenizer_p.encode_plus( + self._data, max_length=512, truncation=True, stride=3, return_overflowing_tokens=True + ) + input_r = tokenizer_r.encode_plus( + self._data, max_length=512, truncation=True, stride=3, return_overflowing_tokens=True + ) + + for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()): + self.assertSequenceEqual(input_p[key], input_r[key][0]) + + def test_num_special_tokens_to_add_equal(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + + # Check we have the same number of added_tokens for both pair and non-pair inputs. + self.assertEqual( + tokenizer_r.num_special_tokens_to_add(False), tokenizer_p.num_special_tokens_to_add(False) + ) + self.assertEqual( + tokenizer_r.num_special_tokens_to_add(True), tokenizer_p.num_special_tokens_to_add(True) + ) + + def test_max_length_equal(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + + # Check we have the correct max_length for both pair and non-pair inputs. + self.assertEqual(tokenizer_r.max_len_single_sentence, tokenizer_p.max_len_single_sentence) + self.assertEqual(tokenizer_r.max_len_sentences_pair, tokenizer_p.max_len_sentences_pair) + + def test_special_tokens_map_equal(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + # sometimes the tokenizer saved online is not the same + tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + # Assert the set of special tokens match. + self.assertSequenceEqual( + tokenizer_p.special_tokens_map.items(), + tokenizer_r.special_tokens_map.items(), + ) + + def test_add_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) + + vocab_size = len(tokenizer_r) + self.assertEqual(tokenizer_r.add_tokens(""), 0) + self.assertEqual(tokenizer_r.add_tokens("testoken"), 1) + self.assertEqual(tokenizer_r.add_tokens(["testoken1", "testtoken2"]), 2) + self.assertEqual(len(tokenizer_r), vocab_size + 3) + + self.assertEqual(tokenizer_r.add_special_tokens({}), 0) + self.assertEqual(tokenizer_r.add_special_tokens({"bos_token": "[BOS]", "eos_token": "[EOS]"}), 2) + self.assertRaises( + AssertionError, tokenizer_r.add_special_tokens, {"additional_special_tokens": ""} + ) + self.assertEqual(tokenizer_r.add_special_tokens({"additional_special_tokens": [""]}), 1) + self.assertEqual( + tokenizer_r.add_special_tokens({"additional_special_tokens": ["", ""]}), 2 + ) + self.assertIn("", tokenizer_r.special_tokens_map["additional_special_tokens"]) + self.assertIsInstance(tokenizer_r.special_tokens_map["additional_special_tokens"], list) + self.assertGreaterEqual(len(tokenizer_r.special_tokens_map["additional_special_tokens"]), 2) + + self.assertEqual(len(tokenizer_r), vocab_size + 8) + + def test_offsets_mapping(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) + + text = "Wonderful no inspiration example with subtoken" + pair = "Along with an awesome pair" + + # No pair + tokens_with_offsets = tokenizer_r.encode_plus( + text, return_special_tokens_mask=True, return_offsets_mapping=True, add_special_tokens=True + ) + added_tokens = tokenizer_r.num_special_tokens_to_add(False) + offsets = tokens_with_offsets["offset_mapping"] + + # Assert there is the same number of tokens and offsets + self.assertEqual(len(offsets), len(tokens_with_offsets["input_ids"])) + + # Assert there is online added_tokens special_tokens + self.assertEqual(sum(tokens_with_offsets["special_tokens_mask"]), added_tokens) + + # Pairs + tokens_with_offsets = tokenizer_r.encode_plus( + text, pair, return_special_tokens_mask=True, return_offsets_mapping=True, add_special_tokens=True + ) + added_tokens = tokenizer_r.num_special_tokens_to_add(True) + offsets = tokens_with_offsets["offset_mapping"] + + # Assert there is the same number of tokens and offsets + self.assertEqual(len(offsets), len(tokens_with_offsets["input_ids"])) + + # Assert there is online added_tokens special_tokens + self.assertEqual(sum(tokens_with_offsets["special_tokens_mask"]), added_tokens) + + def test_batch_encode_dynamic_overflowing(self): + """ + When calling batch_encode with multiple sequence it can returns different number of + overflowing encoding for each sequence: + [ + Sequence 1: [Encoding 1, Encoding 2], + Sequence 2: [Encoding 1], + Sequence 3: [Encoding 1, Encoding 2, ... Encoding N] + ] + This needs to be padded so that it can represented as a tensor + """ + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name}, {tokenizer.__class__.__name__})"): + if is_torch_available(): + returned_tensor = "pt" + elif is_tf_available(): + returned_tensor = "tf" + elif is_flax_available(): + returned_tensor = "jax" + else: + return + + if not tokenizer.pad_token or tokenizer.pad_token_id < 0: + return + + tokens = tokenizer.encode_plus( + "HuggingFace is solving NLP one commit at a time", + max_length=6, + padding=True, + truncation=True, + return_tensors=returned_tensor, + return_overflowing_tokens=True, + ) + + for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()): + self.assertEqual(len(tokens[key].shape), 2) + + # Mono sample + tokens = tokenizer.batch_encode_plus( + ["HuggingFace is solving NLP one commit at a time"], + max_length=6, + padding=True, + truncation="only_first", + return_tensors=returned_tensor, + return_overflowing_tokens=True, + ) + + for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()): + self.assertEqual(len(tokens[key].shape), 2) + self.assertEqual(tokens[key].shape[-1], 6) + + # Multi sample + tokens = tokenizer.batch_encode_plus( + ["HuggingFace is solving NLP one commit at a time", "Very tiny input"], + max_length=6, + padding=True, + truncation="only_first", + return_tensors=returned_tensor, + return_overflowing_tokens=True, + ) + + for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()): + self.assertEqual(len(tokens[key].shape), 2) + self.assertEqual(tokens[key].shape[-1], 6) + + def test_compare_pretokenized_inputs(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + + if hasattr(tokenizer_p, "add_prefix_space") and not tokenizer_p.add_prefix_space: + continue # Too hard to test for now + + # Input string + pretokenized_input_simple = "This is a sample input".split() + pretokenized_input_pair = "This is a sample pair".split() + + # Test encode for pretokenized inputs + output_r = tokenizer_r.encode( + pretokenized_input_simple, is_split_into_words=True, add_special_tokens=False + ) + output_p = tokenizer_p.encode( + pretokenized_input_simple, is_split_into_words=True, add_special_tokens=False + ) + self.assertEqual(output_p, output_r) + + kwargs = { + "is_split_into_words": True, + # "return_token_type_ids": True, # Use the defaults for each tokenizers + # "return_attention_mask": True, # Use the defaults for each tokenizers + "return_overflowing_tokens": False, + "return_special_tokens_mask": True, + "return_offsets_mapping": False, # Not implemented in python tokenizers + # "add_special_tokens": False, + } + batch_kwargs = { + "is_split_into_words": True, + # "return_token_type_ids": True, # Use the defaults for each tokenizers + # "return_attention_mask": True, # Use the defaults for each tokenizers + "return_overflowing_tokens": False, + "return_special_tokens_mask": True, + "return_offsets_mapping": False, # Not implemented in python tokenizers + # "add_special_tokens": False, + } + # Test encode_plus for pretokenized inputs + output_r = tokenizer_r.encode_plus(pretokenized_input_simple, **kwargs) + output_p = tokenizer_p.encode_plus(pretokenized_input_simple, **kwargs) + for key in output_p.keys(): + self.assertEqual(output_p[key], output_r[key]) + + # Test batch_encode_plus for pretokenized inputs + input_batch = ([pretokenized_input_simple] * 2) + [pretokenized_input_simple + pretokenized_input_pair] + output_r = tokenizer_r.batch_encode_plus(input_batch, **batch_kwargs) + output_p = tokenizer_p.batch_encode_plus(input_batch, **batch_kwargs) + for key in output_p.keys(): + self.assertEqual(output_p[key], output_r[key]) + + # Test encode for pretokenized inputs pairs + output_r = tokenizer_r.encode( + pretokenized_input_simple, pretokenized_input_pair, is_split_into_words=True + ) + output_p = tokenizer_p.encode( + pretokenized_input_simple, pretokenized_input_pair, is_split_into_words=True + ) + self.assertEqual(output_p, output_r) + + # Test encode_plus for pretokenized inputs + output_r = tokenizer_r.encode_plus(pretokenized_input_simple, pretokenized_input_pair, **kwargs) + output_p = tokenizer_p.encode_plus(pretokenized_input_simple, pretokenized_input_pair, **kwargs) + for key in output_p.keys(): + self.assertEqual(output_p[key], output_r[key]) + + # Test batch_encode_plus for pretokenized inputs + input_batch_pair = ([pretokenized_input_simple, pretokenized_input_pair] * 2) + [ + pretokenized_input_simple + pretokenized_input_pair, + pretokenized_input_pair, + ] + output_r = tokenizer_r.batch_encode_plus(input_batch_pair, **batch_kwargs) + output_p = tokenizer_p.batch_encode_plus(input_batch_pair, **batch_kwargs) + for key in output_p.keys(): + self.assertEqual(output_p[key], output_r[key]) + + def test_create_token_type_ids(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + input_simple = [1, 2, 3] + input_pair = [1, 2, 3] + + # Generate output + output_r = tokenizer_r.create_token_type_ids_from_sequences(input_simple) + output_p = tokenizer_p.create_token_type_ids_from_sequences(input_simple) + self.assertEqual(output_p, output_r) + + # Generate pair output + output_r = tokenizer_r.create_token_type_ids_from_sequences(input_simple, input_pair) + output_p = tokenizer_p.create_token_type_ids_from_sequences(input_simple, input_pair) + self.assertEqual(output_p, output_r) + + def test_build_inputs_with_special_tokens(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + # # Input string + # input_simple = tokenizer_p.tokenize("This is a sample input", add_special_tokens=False) + # input_pair = tokenizer_p.tokenize("This is a sample pair", add_special_tokens=False) + + # # Generate output + # output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple) + # output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple) + # self.assertEqual(output_p, output_r) + + # # Generate pair output + # output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple, input_pair) + # output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple, input_pair) + # self.assertEqual(output_p, output_r) + + input_pairs = [ + ("", ""), + ("", "This is a sample pair"), + ("This is a sample input", ""), + ("This is a sample input", "This is a sample pair"), + ] + + for sample_input, sample_pair in input_pairs: + # Input tokens id + input_simple = tokenizer_p.encode(sample_input, add_special_tokens=False) + input_pair = tokenizer_p.encode(sample_pair, add_special_tokens=False) + + # Generate output + output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple) + output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple) + self.assertEqual(output_p, output_r) + + # Generate pair output + output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple, input_pair) + output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple, input_pair) + self.assertEqual(output_p, output_r) + + def test_padding(self, max_length=50): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + + self.assertEqual(tokenizer_p.pad_token_id, tokenizer_r.pad_token_id) + pad_token_id = tokenizer_p.pad_token_id + + # Encode - Simple input + input_r = tokenizer_r.encode("This is a simple input", max_length=max_length, pad_to_max_length=True) + input_p = tokenizer_p.encode("This is a simple input", max_length=max_length, pad_to_max_length=True) + self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id) + input_r = tokenizer_r.encode("This is a simple input", max_length=max_length, padding="max_length") + input_p = tokenizer_p.encode("This is a simple input", max_length=max_length, padding="max_length") + self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id) + + input_r = tokenizer_r.encode("This is a simple input", padding="longest") + input_p = tokenizer_p.encode("This is a simple input", padding=True) + self.assert_padded_input_match(input_r, input_p, len(input_r), pad_token_id) + + # Encode - Pair input + input_r = tokenizer_r.encode( + "This is a simple input", "This is a pair", max_length=max_length, pad_to_max_length=True + ) + input_p = tokenizer_p.encode( + "This is a simple input", "This is a pair", max_length=max_length, pad_to_max_length=True + ) + self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id) + input_r = tokenizer_r.encode( + "This is a simple input", "This is a pair", max_length=max_length, padding="max_length" + ) + input_p = tokenizer_p.encode( + "This is a simple input", "This is a pair", max_length=max_length, padding="max_length" + ) + self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id) + input_r = tokenizer_r.encode("This is a simple input", "This is a pair", padding=True) + input_p = tokenizer_p.encode("This is a simple input", "This is a pair", padding="longest") + self.assert_padded_input_match(input_r, input_p, len(input_r), pad_token_id) + + # Encode_plus - Simple input + input_r = tokenizer_r.encode_plus( + "This is a simple input", max_length=max_length, pad_to_max_length=True + ) + input_p = tokenizer_p.encode_plus( + "This is a simple input", max_length=max_length, pad_to_max_length=True + ) + self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id) + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + input_r = tokenizer_r.encode_plus( + "This is a simple input", max_length=max_length, padding="max_length" + ) + input_p = tokenizer_p.encode_plus( + "This is a simple input", max_length=max_length, padding="max_length" + ) + self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id) + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + + input_r = tokenizer_r.encode_plus("This is a simple input", padding="longest") + input_p = tokenizer_p.encode_plus("This is a simple input", padding=True) + self.assert_padded_input_match( + input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id + ) + + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + + # Encode_plus - Pair input + input_r = tokenizer_r.encode_plus( + "This is a simple input", "This is a pair", max_length=max_length, pad_to_max_length=True + ) + input_p = tokenizer_p.encode_plus( + "This is a simple input", "This is a pair", max_length=max_length, pad_to_max_length=True + ) + self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id) + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + input_r = tokenizer_r.encode_plus( + "This is a simple input", "This is a pair", max_length=max_length, padding="max_length" + ) + input_p = tokenizer_p.encode_plus( + "This is a simple input", "This is a pair", max_length=max_length, padding="max_length" + ) + self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id) + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + input_r = tokenizer_r.encode_plus("This is a simple input", "This is a pair", padding="longest") + input_p = tokenizer_p.encode_plus("This is a simple input", "This is a pair", padding=True) + self.assert_padded_input_match( + input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id + ) + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + + # Batch_encode_plus - Simple input + input_r = tokenizer_r.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + pad_to_max_length=True, + ) + input_p = tokenizer_p.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + pad_to_max_length=True, + ) + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + input_r = tokenizer_r.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + padding="max_length", + ) + input_p = tokenizer_p.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + padding="max_length", + ) + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + input_r = tokenizer_r.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + padding="longest", + ) + input_p = tokenizer_p.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + padding=True, + ) + self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id) + + input_r = tokenizer_r.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], padding="longest" + ) + input_p = tokenizer_p.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], padding=True + ) + self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id) + + # Batch_encode_plus - Pair input + input_r = tokenizer_r.batch_encode_plus( + [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ], + max_length=max_length, + truncation=True, + padding="max_length", + ) + input_p = tokenizer_p.batch_encode_plus( + [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ], + max_length=max_length, + truncation=True, + padding="max_length", + ) + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + input_r = tokenizer_r.batch_encode_plus( + [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ], + padding=True, + ) + input_p = tokenizer_p.batch_encode_plus( + [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ], + padding="longest", + ) + self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id) + + # Using pad on single examples after tokenization + input_r = tokenizer_r.encode_plus("This is a input 1") + input_r = tokenizer_r.pad(input_r) + + input_p = tokenizer_p.encode_plus("This is a input 1") + input_p = tokenizer_p.pad(input_p) + + self.assert_padded_input_match( + input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id + ) + + # Using pad on single examples after tokenization + input_r = tokenizer_r.encode_plus("This is a input 1") + input_r = tokenizer_r.pad(input_r, max_length=max_length, padding="max_length") + + input_p = tokenizer_p.encode_plus("This is a input 1") + input_p = tokenizer_p.pad(input_p, max_length=max_length, padding="max_length") + + self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id) + + # Using pad after tokenization + input_r = tokenizer_r.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_r = tokenizer_r.pad(input_r) + + input_p = tokenizer_p.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_p = tokenizer_p.pad(input_p) + + self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id) + + # Using pad after tokenization + input_r = tokenizer_r.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_r = tokenizer_r.pad(input_r, max_length=max_length, padding="max_length") + + input_p = tokenizer_p.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_p = tokenizer_p.pad(input_p, max_length=max_length, padding="max_length") + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + # Test padding nested empty lists (in some use-cases, there is no any token id in the `input_ids` list). + input_r = tokenizer_r.pad({"input_ids": [[], []]}, max_length=max_length, padding="max_length") + input_p = tokenizer_p.pad({"input_ids": [[], []]}, max_length=max_length, padding="max_length") + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + def test_padding_different_model_input_name(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + self.assertEqual(tokenizer_p.pad_token_id, tokenizer_r.pad_token_id) + pad_token_id = tokenizer_p.pad_token_id + + input_r = tokenizer_r.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_p = tokenizer_r.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + + # rename encoded batch to "inputs" + input_r["inputs"] = input_r[tokenizer_r.model_input_names[0]] + del input_r[tokenizer_r.model_input_names[0]] + + input_p["inputs"] = input_p[tokenizer_p.model_input_names[0]] + del input_p[tokenizer_p.model_input_names[0]] + + # Renaming `input_ids` to `inputs` + tokenizer_r.model_input_names = ["inputs"] + tokenizer_r.model_input_names[1:] + tokenizer_p.model_input_names = ["inputs"] + tokenizer_p.model_input_names[1:] + + input_r = tokenizer_r.pad(input_r, padding="longest") + input_p = tokenizer_r.pad(input_p, padding="longest") + + max_length = len(input_p["inputs"][0]) + self.assert_batch_padded_input_match( + input_r, input_p, max_length, pad_token_id, model_main_input_name="inputs" + ) + + def test_save_pretrained(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # make sure that all ".json" files are saved in the correct format + for file_path in tokenizer_r_files + tokenizer_p_files: + if os.path.exists(file_path) and file_path.endswith(".json"): + check_json_file_has_correct_format(file_path) + + # Checks it save with the same files + the tokenizer.json file for the fast one + self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files)) + tokenizer_r_files = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f) + self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) + # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) + + shutil.rmtree(tmpdirname2) + + # Save tokenizer rust, legacy_format=True + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=True) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # Checks it save with the same files + self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + + shutil.rmtree(tmpdirname2) + + # Save tokenizer rust, legacy_format=False + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=False) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # Checks it saved the tokenizer.json file + self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files)) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + + shutil.rmtree(tmpdirname2) + + def test_embeded_special_tokens(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs) + tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + sentence = "A, AllenNLP sentence." + tokens_r = tokenizer_r.encode_plus( + sentence, + add_special_tokens=True, + ) + tokens_p = tokenizer_p.encode_plus( + sentence, + add_special_tokens=True, + ) + + for key in tokens_p.keys(): + self.assertEqual(tokens_r[key], tokens_p[key]) + + if "token_type_ids" in tokens_r: + self.assertEqual(sum(tokens_r["token_type_ids"]), sum(tokens_p["token_type_ids"])) + + tokens_r = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"]) + tokens_p = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"]) + self.assertSequenceEqual(tokens_r, tokens_p) + + def test_compare_add_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) + + simple_num_special_tokens_to_add = tokenizer_r.num_special_tokens_to_add(pair=False) + # pair_num_special_tokens_to_add = tokenizer_r.num_special_tokens_to_add(pair=True) + + for text in ["", " "]: + # tokenize() + no_special_tokens = tokenizer_r.tokenize(text, add_special_tokens=False) + with_special_tokens = tokenizer_r.tokenize(text, add_special_tokens=True) + self.assertEqual( + len(no_special_tokens), len(with_special_tokens) - simple_num_special_tokens_to_add + ) + + # encode() + no_special_tokens = tokenizer_r.encode(text, add_special_tokens=False) + with_special_tokens = tokenizer_r.encode(text, add_special_tokens=True) + self.assertEqual( + len(no_special_tokens), len(with_special_tokens) - simple_num_special_tokens_to_add + ) + + # encode_plus() + no_special_tokens = tokenizer_r.encode_plus(text, add_special_tokens=False) + with_special_tokens = tokenizer_r.encode_plus(text, add_special_tokens=True) + for key in no_special_tokens.keys(): + self.assertEqual( + len(no_special_tokens[key]), + len(with_special_tokens[key]) - simple_num_special_tokens_to_add, + ) + + # # batch_encode_plus + no_special_tokens = tokenizer_r.batch_encode_plus([text, text], add_special_tokens=False) + with_special_tokens = tokenizer_r.batch_encode_plus([text, text], add_special_tokens=True) + for key in no_special_tokens.keys(): + for i_no, i_with in zip(no_special_tokens[key], with_special_tokens[key]): + self.assertEqual(len(i_no), len(i_with) - simple_num_special_tokens_to_add) + + def test_compare_prepare_for_model(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + return + + 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) + string_sequence = "Asserting that both tokenizers are equal" + python_output = tokenizer_p.prepare_for_model( + tokenizer_p.encode(string_sequence, add_special_tokens=False) + ) + rust_output = tokenizer_r.prepare_for_model( + tokenizer_r.encode(string_sequence, add_special_tokens=False) + ) + for key in python_output: + self.assertEqual(python_output[key], rust_output[key]) + + def test_special_tokens_initialization(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + added_tokens = [AddedToken("", lstrip=True)] + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, additional_special_tokens=added_tokens, **kwargs + ) + r_output = tokenizer_r.encode("Hey this is a token") + + special_token_id = tokenizer_r.encode("", add_special_tokens=False)[0] + + self.assertTrue(special_token_id in r_output) + + if self.test_slow_tokenizer: + # in rust fast, you lose the information of the AddedToken when initializing with `additional_special_tokens` + tokenizer_cr = self.rust_tokenizer_class.from_pretrained( + pretrained_name, additional_special_tokens=added_tokens, **kwargs, from_slow=True + ) + tokenizer_p = self.tokenizer_class.from_pretrained( + pretrained_name, additional_special_tokens=added_tokens, **kwargs + ) + + p_output = tokenizer_p.encode("Hey this is a token") + + cr_output = tokenizer_cr.encode("Hey this is a token") + + self.assertEqual(p_output, r_output) + self.assertEqual(cr_output, r_output) + self.assertTrue(special_token_id in p_output) + self.assertTrue(special_token_id in cr_output) + + def test_special_tokens_initialization_with_non_empty_additional_special_tokens(self): + # This test no longer support rust tokenizers, because the only file that should be looked + # at by the fast tokenizer with the new saving format is `tokenizer_config.json`. + # The previous behaviour is very strange too. Fast tokenizer should not save 3 files, but just one. Can never do slow from fast. + tokenizer_list = [] + if self.test_slow_tokenizer: + tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) + + for tokenizer_class, tokenizer_utils in tokenizer_list: + with tempfile.TemporaryDirectory() as tmp_dir: + tokenizer_utils.save_pretrained(tmp_dir) + # only legacy save will check this + tokenizer_path = "tokenizer_config.json" + with open(os.path.join(tmp_dir, tokenizer_path), encoding="utf-8") as json_file: + tokenizer_config = json.load(json_file) + + tokenizer_config["additional_special_tokens"] = ["an_additional_special_token"] + + with open(os.path.join(tmp_dir, tokenizer_path), "w", encoding="utf-8") as outfile: + json.dump(tokenizer_config, outfile) + + # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes + # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and + # "special_tokens_map.json" files + + # TODO ArthurZ ... Ok so for legacy we have to support this I guess..... (special_tokens_map + additional) + tokenizer_without_change_in_init = tokenizer_class.from_pretrained(tmp_dir) + self.assertIn( + "an_additional_special_token", tokenizer_without_change_in_init.additional_special_tokens + ) + 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( + tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"]) + ), + ) + + # Now we test that we can change the value of additional_special_tokens in the from_pretrained + new_added_tokens = [AddedToken("a_new_additional_special_token", lstrip=True)] + tokenizer = tokenizer_class.from_pretrained( + tmp_dir, + additional_special_tokens=new_added_tokens, + ) + + self.assertIn("a_new_additional_special_token", tokenizer.additional_special_tokens) + self.assertEqual( + ["a_new_additional_special_token"], + tokenizer.convert_ids_to_tokens( + tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"]) + ), + ) + + def test_training_new_tokenizer(self): + # This feature only exists for fast tokenizers + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_rust_tokenizer() + new_tokenizer = tokenizer.train_new_from_iterator(SMALL_TRAINING_CORPUS, 100) + + # Test we can use the new tokenizer with something not seen during training + inputs = new_tokenizer(["This is the first sentence", "This sentence is different 🤗."]) + self.assertEqual(len(inputs["input_ids"]), 2) + decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True) + expected_result = "This is the first sentence" + + if tokenizer.backend_tokenizer.normalizer is not None: + expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result) + self.assertEqual(expected_result, decoded_input) + + # We check that the parameters of the tokenizer remained the same + # Check we have the same number of added_tokens for both pair and non-pair inputs. + self.assertEqual(tokenizer.num_special_tokens_to_add(False), new_tokenizer.num_special_tokens_to_add(False)) + self.assertEqual(tokenizer.num_special_tokens_to_add(True), new_tokenizer.num_special_tokens_to_add(True)) + + # Check we have the correct max_length for both pair and non-pair inputs. + self.assertEqual(tokenizer.max_len_single_sentence, new_tokenizer.max_len_single_sentence) + self.assertEqual(tokenizer.max_len_sentences_pair, new_tokenizer.max_len_sentences_pair) + + # Assert the set of special tokens match as we didn't ask to change them + self.assertSequenceEqual( + tokenizer.all_special_tokens_extended, + new_tokenizer.all_special_tokens_extended, + ) + + self.assertDictEqual(tokenizer.special_tokens_map, new_tokenizer.special_tokens_map) + + def test_training_new_tokenizer_with_special_tokens_change(self): + # This feature only exists for fast tokenizers + if not self.test_rust_tokenizer: + return + + tokenizer = self.get_rust_tokenizer() + # Test with a special tokens map + class_signature = inspect.signature(tokenizer.__class__) + if "cls_token" in class_signature.parameters: + new_tokenizer = tokenizer.train_new_from_iterator( + SMALL_TRAINING_CORPUS, 100, special_tokens_map={tokenizer.cls_token: ""} + ) + cls_id = new_tokenizer.get_vocab()[""] + self.assertEqual(new_tokenizer.cls_token, "") + self.assertEqual(new_tokenizer.cls_token_id, cls_id) + + # Create a new mapping from the special tokens defined in the original tokenizer + special_tokens_list = SpecialTokensMixin.SPECIAL_TOKENS_ATTRIBUTES.copy() + special_tokens_list.remove("additional_special_tokens") + special_tokens_map = {} + for token in special_tokens_list: + # Get the private one to avoid unnecessary warnings. + if getattr(tokenizer, f"_{token}") is not None: + special_token = getattr(tokenizer, token) + special_tokens_map[special_token] = f"{special_token}a" + + # Train new tokenizer + new_tokenizer = tokenizer.train_new_from_iterator( + SMALL_TRAINING_CORPUS, 100, special_tokens_map=special_tokens_map + ) + + # Check the changes + for token in special_tokens_list: + # Get the private one to avoid unnecessary warnings. + if getattr(tokenizer, f"_{token}") is None: + continue + special_token = getattr(tokenizer, token) + if special_token in special_tokens_map: + new_special_token = getattr(new_tokenizer, token) + self.assertEqual(special_tokens_map[special_token], new_special_token) + + new_id = new_tokenizer.get_vocab()[new_special_token] + self.assertEqual(getattr(new_tokenizer, f"{token}_id"), new_id) + + # Check if the AddedToken / string format has been kept + for special_token in tokenizer.all_special_tokens_extended: + if isinstance(special_token, AddedToken) and special_token.content not in special_tokens_map: + # The special token must appear identically in the list of the new tokenizer. + self.assertTrue( + special_token in new_tokenizer.all_special_tokens_extended, + f"'{special_token}' should be in {new_tokenizer.all_special_tokens_extended}", + ) + elif isinstance(special_token, AddedToken): + # The special token must appear in the list of the new tokenizer as an object of type AddedToken with + # the same parameters as the old AddedToken except the content that the user has requested to change. + special_token_str = special_token.content + new_special_token_str = special_tokens_map[special_token_str] + + find = False + for candidate in new_tokenizer.all_special_tokens_extended: + if ( + isinstance(candidate, AddedToken) + and candidate.content == new_special_token_str + and candidate.lstrip == special_token.lstrip + and candidate.rstrip == special_token.rstrip + and candidate.normalized == special_token.normalized + and candidate.single_word == special_token.single_word + ): + find = True + break + special_token.content = new_special_token_str + self.assertTrue( + find, + f"'{special_token.__repr__()}' should appear as an `AddedToken` in the all_special_tokens_extended = " + f"{[k for k in new_tokenizer.all_special_tokens_extended if str(k)==new_special_token_str]} but it is missing" + ", this means that the new tokenizers did not keep the `rstrip`, `lstrip`, `normalized` etc attributes.", + ) + elif special_token not in special_tokens_map: + # The special token must appear identically in the list of the new tokenizer. + self.assertTrue( + special_token in new_tokenizer.all_special_tokens_extended, + f"'{special_token.__repr__()}' should be in {new_tokenizer.all_special_tokens_extended}", + ) + + else: + # The special token must appear in the list of the new tokenizer as an object of type string. + self.assertTrue(special_tokens_map[special_token] in new_tokenizer.all_special_tokens_extended) + + # Test we can use the new tokenizer with something not seen during training + inputs = new_tokenizer(["This is the first sentence", "This sentence is different 🤗."]) + self.assertEqual(len(inputs["input_ids"]), 2) + decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True) + expected_result = "This is the first sentence" + + if tokenizer.backend_tokenizer.normalizer is not None: + expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result) + self.assertEqual(expected_result, decoded_input) + + def test_tokenizer_mismatch_warning(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + with self.assertLogs("transformers", level="WARNING") as cm: + try: + if self.tokenizer_class == BertTokenizer: + AlbertTokenizer.from_pretrained(pretrained_name) + else: + BertTokenizer.from_pretrained(pretrained_name) + except EnvironmentError as e: + # Some tokenizer will raised an error before reaching the logged warning because there are no + # corresponding files to load + error_message = str(e) + except (TypeError, AttributeError): + # Some tokenizers cannot be loaded into the target tokenizer at all and errors are returned, + # here we just check that the warning has been logged before the error is raised + pass + finally: + logged_msg_target = ( + "The tokenizer class you load from this checkpoint is not the same type as the class " + "this function is called from." + ) + raised_error_msg_target = "Can't load tokenizer for" + self.assertTrue( + cm.records[0].message.startswith(logged_msg_target) + if len(cm.records) > 0 + else False or raised_error_msg_target in error_message + ) + try: + if self.rust_tokenizer_class == BertTokenizerFast: + AlbertTokenizerFast.from_pretrained(pretrained_name) + else: + BertTokenizerFast.from_pretrained(pretrained_name) + except (TypeError, AttributeError): + # Some tokenizers cannot be loaded into the target tokenizer at all and errors are returned, + # here we just check that the warning has been logged before the error is raised + pass + finally: + self.assertTrue( + cm.records[0].message.startswith( + "The tokenizer class you load from this checkpoint is not the same type as the class" + " this function is called from." + ) + ) + + @require_torch + def test_saving_tokenizer_trainer(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + with tempfile.TemporaryDirectory() as tmp_dir: + # Save the fast tokenizer files in a temporary directory + tokenizer_old = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs, use_fast=True) + tokenizer_old.save_pretrained(tmp_dir, legacy_format=False) # save only fast version + + # Initialize toy model for the trainer + model = nn.Module() + + # Load tokenizer from a folder without legacy files + tokenizer = self.rust_tokenizer_class.from_pretrained(tmp_dir) + training_args = TrainingArguments(output_dir=tmp_dir, do_train=True, no_cuda=True) + trainer = Trainer(model=model, args=training_args, tokenizer=tokenizer) + + # Should not raise an error + trainer.save_model(os.path.join(tmp_dir, "checkpoint")) + self.assertIn("tokenizer.json", os.listdir(os.path.join(tmp_dir, "checkpoint"))) + + def test_convert_tokens_to_string_format(self): + tokenizers = self.get_tokenizers(fast=True, do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokens = ["this", "is", "a", "test"] + string = tokenizer.convert_tokens_to_string(tokens) + + self.assertIsInstance(string, str) + + def test_save_slow_from_fast_and_reload_fast(self): + if not self.test_slow_tokenizer or not self.test_rust_tokenizer: + # we need both slow and fast versions + return + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + with tempfile.TemporaryDirectory() as tmp_dir_1: + # Here we check that even if we have initialized a fast tokenizer with a tokenizer_file we can + # still save only the slow version and use these saved files to rebuild a tokenizer + tokenizer_fast_old_1 = self.rust_tokenizer_class.from_pretrained( + pretrained_name, **kwargs, use_fast=True + ) + tokenizer_file = os.path.join(tmp_dir_1, "tokenizer.json") + tokenizer_fast_old_1.backend_tokenizer.save(tokenizer_file) + + tokenizer_fast_old_2 = self.rust_tokenizer_class.from_pretrained( + pretrained_name, **kwargs, use_fast=True, tokenizer_file=tokenizer_file + ) + + tokenizer_fast_old_2.save_pretrained(tmp_dir_1, legacy_format=True) # save only slow version + + tokenizer_slow = self.tokenizer_class.from_pretrained(tmp_dir_1) + with tempfile.TemporaryDirectory() as tmp_dir_2: + tokenizer_slow.save_pretrained(tmp_dir_2) + + # Should not raise an error + self.rust_tokenizer_class.from_pretrained(tmp_dir_2) + + # TODO This is ran for all models but only tests bert... + def test_clean_up_tokenization_spaces(self): + tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") + assert tokenizer.clean_up_tokenization_spaces is True + + tokens = tokenizer.encode("This shouldn't be! He'll go.") + decoded = tokenizer.decode(tokens) + assert decoded == "[CLS] this shouldn't be! he'll go. [SEP]" + + tokenizer.clean_up_tokenization_spaces = False + decoded = tokenizer.decode(tokens) + assert decoded == "[CLS] this shouldn ' t be ! he ' ll go . [SEP]" + assert decoded == tokenizer.decode(tokens, clean_up_tokenization_spaces=False) + + # Fast from slow + with tempfile.TemporaryDirectory() as tmp_dir_2: + tokenizer.save_pretrained(tmp_dir_2) + tokenizer_fast = BertTokenizerFast.from_pretrained(tmp_dir_2) + del tokenizer + + assert tokenizer_fast.clean_up_tokenization_spaces is False + decoded = tokenizer_fast.decode(tokens) + # fast and slow don't have the same output when we don't cleanup + # tokenization space. Here `be!` vs `be !` and `go.` vs `go .` + assert decoded == "[CLS] this shouldn ' t be! he ' ll go. [SEP]" + + tokenizer_fast.clean_up_tokenization_spaces = True + assert tokenizer_fast.clean_up_tokenization_spaces is True + + decoded = tokenizer_fast.decode(tokens) + assert decoded == "[CLS] this shouldn't be! he'll go. [SEP]" + + # Slow from fast + with tempfile.TemporaryDirectory() as tmp_dir_2: + tokenizer_fast.clean_up_tokenization_spaces = False + tokenizer_fast.save_pretrained(tmp_dir_2) + tokenizer = BertTokenizer.from_pretrained(tmp_dir_2) + + assert tokenizer.clean_up_tokenization_spaces is False + decoded = tokenizer.decode(tokens) + assert decoded == "[CLS] this shouldn ' t be ! he ' ll go . [SEP]" + + tokenizer.clean_up_tokenization_spaces = True + decoded = tokenizer.decode(tokens) + assert decoded == "[CLS] this shouldn't be! he'll go. [SEP]" + + def test_split_special_tokens(self): + if not self.test_slow_tokenizer: + return + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + special_token = "[SPECIAL_TOKEN]" + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + if not tokenizer.is_fast: + # bloom, gptneox etc only have a fast + tokenizer.add_special_tokens( + { + "additional_special_tokens": [ + AddedToken(special_token, rstrip=True, lstrip=True, normalized=True, special=True) + ] + } + ) + encoded_special_token = tokenizer.encode(special_token, add_special_tokens=False) + self.assertEqual(len(encoded_special_token), 1) + + encoded_split_special_token = tokenizer.encode( + special_token, add_special_tokens=False, split_special_tokens=True + ) + if len(encoded_split_special_token) == 1: + # if we have subword tokenization or special vocab + self.assertTrue( + encoded_split_special_token[0] != tokenizer.convert_tokens_to_ids(special_token) + ) + else: + self.assertTrue(len(encoded_split_special_token) > 1) + + def test_added_tokens_serialization(self): + # Utility to test the added vocab + def _test_added_vocab_and_eos(expected, tokenizer_class, expected_eos, temp_dir): + tokenizer = tokenizer_class.from_pretrained(temp_dir) + self.assertTrue(str(expected_eos) not in tokenizer.additional_special_tokens) + self.assertIn(new_eos, tokenizer.added_tokens_decoder.values()) + self.assertEqual(tokenizer.added_tokens_decoder[tokenizer.eos_token_id], new_eos) + self.assertDictEqual(expected, tokenizer.added_tokens_decoder) + return tokenizer + + new_eos = AddedToken("[NEW_EOS]", rstrip=False, lstrip=True, normalized=False, special=True) + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + # Load a slow tokenizer from the hub, init with the new token for fast to also include it + tokenizer = self.tokenizer_class.from_pretrained(pretrained_name, eos_token=new_eos) + EXPECTED_ADDED_TOKENS_DECODER = tokenizer.added_tokens_decoder + with self.subTest("Hub -> Slow: Test loading a slow tokenizer from the hub)"): + self.assertEqual(tokenizer._eos_token, new_eos) + self.assertIn(new_eos, list(tokenizer.added_tokens_decoder.values())) + + with tempfile.TemporaryDirectory() as tmp_dir_2: + tokenizer.save_pretrained(tmp_dir_2) + with self.subTest( + "Hub -> Slow -> Slow: Test saving this slow tokenizer and reloading it in the fast class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_2 + ) + + if self.rust_tokenizer_class is not None: + with self.subTest( + "Hub -> Slow -> Fast: Test saving this slow tokenizer and reloading it in the fast class" + ): + tokenizer_fast = _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_2 + ) + with tempfile.TemporaryDirectory() as tmp_dir_3: + tokenizer_fast.save_pretrained(tmp_dir_3) + with self.subTest( + "Hub -> Slow -> Fast -> Fast: Test saving this fast tokenizer and reloading it in the fast class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3 + ) + + with self.subTest( + "Hub -> Slow -> Fast -> Slow: Test saving this slow tokenizer and reloading it in the slow class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3 + ) + + with self.subTest("Hub -> Fast: Test loading a fast tokenizer from the hub)"): + if self.rust_tokenizer_class is not None: + tokenizer_fast = self.rust_tokenizer_class.from_pretrained(pretrained_name, eos_token=new_eos) + self.assertEqual(tokenizer_fast._eos_token, new_eos) + self.assertIn(new_eos, list(tokenizer_fast.added_tokens_decoder.values())) + # We can't test the following because for BC we kept the default rstrip lstrip in slow not fast. Will comment once normalization is alright + with self.subTest("Hub -> Fast == Hub -> Slow: make sure slow and fast tokenizer match"): + self.assertDictEqual(EXPECTED_ADDED_TOKENS_DECODER, tokenizer_fast.added_tokens_decoder) + + EXPECTED_ADDED_TOKENS_DECODER = tokenizer_fast.added_tokens_decoder + with tempfile.TemporaryDirectory() as tmp_dir_4: + tokenizer_fast.save_pretrained(tmp_dir_4) + with self.subTest("Hub -> Fast -> Fast: saving Fast1 locally and loading"): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_4 + ) + + with self.subTest("Hub -> Fast -> Slow: saving Fast1 locally and loading"): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_4 + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_tokenization_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_tokenization_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7f7249f97c40d8053f472a80f6664405f3d63a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/test_tokenization_utils.py @@ -0,0 +1,280 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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 os +import sys +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from huggingface_hub import HfFolder, delete_repo +from huggingface_hub.file_download import http_get +from requests.exceptions import HTTPError + +from transformers import ( + AlbertTokenizer, + AutoTokenizer, + BertTokenizer, + BertTokenizerFast, + GPT2TokenizerFast, + is_tokenizers_available, +) +from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers +from transformers.tokenization_utils import Trie + + +sys.path.append(str(Path(__file__).parent.parent / "utils")) + +from test_module.custom_tokenization import CustomTokenizer # noqa E402 + + +if is_tokenizers_available(): + from test_module.custom_tokenization_fast import CustomTokenizerFast + + +class TokenizerUtilTester(unittest.TestCase): + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Under the mock environment we get a 500 error when trying to reach the tokenizer. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") + # This check we did call the fake head request + mock_head.assert_called() + + @require_tokenizers + def test_cached_files_are_used_when_internet_is_down_missing_files(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = GPT2TokenizerFast.from_pretrained("gpt2") + + # Under the mock environment we get a 500 error when trying to reach the tokenizer. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = GPT2TokenizerFast.from_pretrained("gpt2") + # This check we did call the fake head request + mock_head.assert_called() + + def test_legacy_load_from_one_file(self): + # This test is for deprecated behavior and can be removed in v5 + try: + tmp_file = tempfile.mktemp() + with open(tmp_file, "wb") as f: + http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model", f) + + _ = AlbertTokenizer.from_pretrained(tmp_file) + finally: + os.remove(tmp_file) + + # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in + # the current folder and have the right name. + if os.path.isfile("tokenizer.json"): + # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. + return + try: + with open("tokenizer.json", "wb") as f: + http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json", f) + tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2") + # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 + self.assertEqual(tokenizer.vocab_size, 1000) + # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. + + finally: + os.remove("tokenizer.json") + + def test_legacy_load_from_url(self): + # This test is for deprecated behavior and can be removed in v5 + _ = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model") + + +@is_staging_test +class TokenizerPushToHubTester(unittest.TestCase): + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] + + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + try: + delete_repo(token=cls._token, repo_id="test-tokenizer") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="valid_org/test-tokenizer-org") + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="test-dynamic-tokenizer") + except HTTPError: + pass + + def test_push_to_hub(self): + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = BertTokenizer(vocab_file) + + tokenizer.push_to_hub("test-tokenizer", token=self._token) + new_tokenizer = BertTokenizer.from_pretrained(f"{USER}/test-tokenizer") + self.assertDictEqual(new_tokenizer.vocab, tokenizer.vocab) + + # Reset repo + delete_repo(token=self._token, repo_id="test-tokenizer") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + tokenizer.save_pretrained(tmp_dir, repo_id="test-tokenizer", push_to_hub=True, token=self._token) + + new_tokenizer = BertTokenizer.from_pretrained(f"{USER}/test-tokenizer") + self.assertDictEqual(new_tokenizer.vocab, tokenizer.vocab) + + def test_push_to_hub_in_organization(self): + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = BertTokenizer(vocab_file) + + tokenizer.push_to_hub("valid_org/test-tokenizer-org", token=self._token) + new_tokenizer = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org") + self.assertDictEqual(new_tokenizer.vocab, tokenizer.vocab) + + # Reset repo + delete_repo(token=self._token, repo_id="valid_org/test-tokenizer-org") + + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + tokenizer.save_pretrained( + tmp_dir, repo_id="valid_org/test-tokenizer-org", push_to_hub=True, token=self._token + ) + + new_tokenizer = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org") + self.assertDictEqual(new_tokenizer.vocab, tokenizer.vocab) + + @require_tokenizers + def test_push_to_hub_dynamic_tokenizer(self): + CustomTokenizer.register_for_auto_class() + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = CustomTokenizer(vocab_file) + + # No fast custom tokenizer + tokenizer.push_to_hub("test-dynamic-tokenizer", token=self._token) + + tokenizer = AutoTokenizer.from_pretrained(f"{USER}/test-dynamic-tokenizer", trust_remote_code=True) + # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module + self.assertEqual(tokenizer.__class__.__name__, "CustomTokenizer") + + # Fast and slow custom tokenizer + CustomTokenizerFast.register_for_auto_class() + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + + bert_tokenizer = BertTokenizerFast.from_pretrained(tmp_dir) + bert_tokenizer.save_pretrained(tmp_dir) + tokenizer = CustomTokenizerFast.from_pretrained(tmp_dir) + + tokenizer.push_to_hub("test-dynamic-tokenizer", token=self._token) + + tokenizer = AutoTokenizer.from_pretrained(f"{USER}/test-dynamic-tokenizer", trust_remote_code=True) + # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module + self.assertEqual(tokenizer.__class__.__name__, "CustomTokenizerFast") + tokenizer = AutoTokenizer.from_pretrained( + f"{USER}/test-dynamic-tokenizer", use_fast=False, trust_remote_code=True + ) + # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module + self.assertEqual(tokenizer.__class__.__name__, "CustomTokenizer") + + +class TrieTest(unittest.TestCase): + def test_trie(self): + trie = Trie() + trie.add("Hello 友達") + self.assertEqual(trie.data, {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}) + trie.add("Hello") + trie.data + self.assertEqual(trie.data, {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}) + + def test_trie_split(self): + trie = Trie() + self.assertEqual(trie.split("[CLS] This is a extra_id_100"), ["[CLS] This is a extra_id_100"]) + trie.add("[CLS]") + trie.add("extra_id_1") + trie.add("extra_id_100") + self.assertEqual(trie.split("[CLS] This is a extra_id_100"), ["[CLS]", " This is a ", "extra_id_100"]) + + def test_trie_single(self): + trie = Trie() + trie.add("A") + self.assertEqual(trie.split("ABC"), ["A", "BC"]) + self.assertEqual(trie.split("BCA"), ["BC", "A"]) + + def test_trie_final(self): + trie = Trie() + trie.add("TOKEN]") + trie.add("[SPECIAL_TOKEN]") + self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"), ["This is something ", "[SPECIAL_TOKEN]"]) + + def test_trie_subtokens(self): + trie = Trie() + trie.add("A") + trie.add("P") + trie.add("[SPECIAL_TOKEN]") + self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"), ["This is something ", "[SPECIAL_TOKEN]"]) + + def test_trie_suffix_tokens(self): + trie = Trie() + trie.add("AB") + trie.add("B") + trie.add("C") + self.assertEqual(trie.split("ABC"), ["AB", "C"]) + + def test_trie_skip(self): + trie = Trie() + trie.add("ABC") + trie.add("B") + trie.add("CD") + self.assertEqual(trie.split("ABCD"), ["ABC", "D"]) + + def test_cut_text_hardening(self): + # Even if the offsets are wrong, we necessarily output correct string + # parts. + trie = Trie() + parts = trie.cut_text("ABC", [0, 0, 2, 1, 2, 3]) + self.assertEqual(parts, ["AB", "C"]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tokenization/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tokenization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tokenization/test_tokenization_fast.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tokenization/test_tokenization_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..48ac31b97c41ca3e9fc55f355138d35614a241cb --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tokenization/test_tokenization_fast.py @@ -0,0 +1,242 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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 concurrent.futures +import json +import os +import shutil +import tempfile +import unittest + +from transformers import AutoTokenizer, PreTrainedTokenizerFast +from transformers.testing_utils import require_tokenizers + +from ..test_tokenization_common import TokenizerTesterMixin + + +@require_tokenizers +class PreTrainedTokenizationFastTest(TokenizerTesterMixin, unittest.TestCase): + rust_tokenizer_class = PreTrainedTokenizerFast + test_slow_tokenizer = False + test_rust_tokenizer = True + from_pretrained_vocab_key = "tokenizer_file" + + def setUp(self): + self.test_rust_tokenizer = False # because we don't have pretrained_vocab_files_map + super().setUp() + self.test_rust_tokenizer = True + + model_paths = ["robot-test/dummy-tokenizer-fast", "robot-test/dummy-tokenizer-wordlevel"] + self.bytelevel_bpe_model_name = "SaulLu/dummy-tokenizer-bytelevel-bpe" + + # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment) + self.tokenizers_list = [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths] + + tokenizer = PreTrainedTokenizerFast.from_pretrained(model_paths[0]) + tokenizer.save_pretrained(self.tmpdirname) + + def test_tokenizer_mismatch_warning(self): + # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any + # model + pass + + @unittest.skip( + "We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any model" + ) + def test_encode_decode_with_spaces(self): + pass + + @unittest.skip( + "We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any model" + ) + def test_added_tokens_serialization(self): + pass + + @unittest.skip( + "We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any model" + ) + def test_additional_special_tokens_serialization(self): + pass + + def test_pretrained_model_lists(self): + # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any + # model + pass + + def test_prepare_for_model(self): + # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any + # model + pass + + def test_rust_tokenizer_signature(self): + # PreTrainedTokenizerFast doesn't have tokenizer_file in its signature + pass + + def test_training_new_tokenizer(self): + tmpdirname_orig = self.tmpdirname + # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel. + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + try: + self.tmpdirname = tempfile.mkdtemp() + tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + tokenizer.save_pretrained(self.tmpdirname) + super().test_training_new_tokenizer() + finally: + # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer + # is restored + shutil.rmtree(self.tmpdirname) + self.tmpdirname = tmpdirname_orig + + def test_training_new_tokenizer_with_special_tokens_change(self): + tmpdirname_orig = self.tmpdirname + # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel. + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + try: + self.tmpdirname = tempfile.mkdtemp() + tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + tokenizer.save_pretrained(self.tmpdirname) + super().test_training_new_tokenizer_with_special_tokens_change() + finally: + # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer + # is restored + shutil.rmtree(self.tmpdirname) + self.tmpdirname = tmpdirname_orig + + def test_training_new_tokenizer_with_bytelevel(self): + tokenizer = self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name) + + toy_text_iterator = ("a" for _ in range(1000)) + new_tokenizer = tokenizer.train_new_from_iterator(text_iterator=toy_text_iterator, length=1000, vocab_size=50) + + encoding_ids = new_tokenizer.encode("a🤗") + self.assertEqual(encoding_ids, [64, 172, 253, 97, 245]) + + def test_init_from_tokenizers_model(self): + from tokenizers import Tokenizer + + sentences = ["Hello, y'all!", "How are you 😁 ? There should not be any issue right?"] + + tokenizer = Tokenizer.from_pretrained("t5-base") + # Enable padding + tokenizer.enable_padding(pad_id=0, pad_token="", length=512, pad_to_multiple_of=8) + self.assertEqual( + tokenizer.padding, + { + "length": 512, + "pad_to_multiple_of": 8, + "pad_id": 0, + "pad_token": "", + "pad_type_id": 0, + "direction": "right", + }, + ) + fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer) + tmpdirname = tempfile.mkdtemp() + fast_tokenizer.save_pretrained(tmpdirname) + fast_from_saved = PreTrainedTokenizerFast.from_pretrained(tmpdirname) + for tok in [fast_tokenizer, fast_from_saved]: + self.assertEqual(tok.pad_token_id, 0) + self.assertEqual(tok.padding_side, "right") + self.assertEqual(tok.pad_token, "") + self.assertEqual(tok.init_kwargs["max_length"], 512) + self.assertEqual(tok.init_kwargs["pad_to_multiple_of"], 8) + self.assertEqual(tok(sentences, padding = True), {'input_ids': [[8774, 6, 3, 63, 31, 1748, 55, 1, 0, 0, 0, 0,0, 0, 0, 0],[ 571, 33, 25, 3, 2, 3, 58, 290, 225, 59, 36, 136, 962, 269, 58, 1]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}) # fmt: skip + + tokenizer.enable_truncation(8, stride=0, strategy="longest_first", direction="right") + self.assertEqual( + tokenizer.truncation, {"max_length": 8, "stride": 0, "strategy": "longest_first", "direction": "right"} + ) + fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer) + tmpdirname = tempfile.mkdtemp() + fast_tokenizer.save_pretrained(tmpdirname) + fast_from_saved = PreTrainedTokenizerFast.from_pretrained(tmpdirname) + for tok in [fast_tokenizer, fast_from_saved]: + self.assertEqual(tok.truncation_side, "right") + self.assertEqual(tok.init_kwargs["truncation_strategy"], "longest_first") + self.assertEqual(tok.init_kwargs["max_length"], 8) + self.assertEqual(tok.init_kwargs["stride"], 0) + # NOTE even if the model has a default max_length, it is not used... + # thus tok(sentences, truncation = True) does nothing and does not warn either + self.assertEqual(tok(sentences, truncation = True, max_length = 8), {'input_ids': [[8774, 6, 3, 63, 31, 1748, 55, 1],[ 571, 33, 25, 3, 2, 3, 58, 1]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1]]}) # fmt: skip + + +@require_tokenizers +class TokenizerVersioningTest(unittest.TestCase): + def test_local_versioning(self): + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + json_tokenizer = json.loads(tokenizer._tokenizer.to_str()) + json_tokenizer["model"]["vocab"]["huggingface"] = len(tokenizer) + + with tempfile.TemporaryDirectory() as tmp_dir: + # Hack to save this in the tokenizer_config.json + tokenizer.init_kwargs["fast_tokenizer_files"] = ["tokenizer.4.0.0.json"] + tokenizer.save_pretrained(tmp_dir) + json.dump(json_tokenizer, open(os.path.join(tmp_dir, "tokenizer.4.0.0.json"), "w")) + + # This should pick the new tokenizer file as the version of Transformers is > 4.0.0 + new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir) + self.assertEqual(len(new_tokenizer), len(tokenizer) + 1) + json_tokenizer = json.loads(new_tokenizer._tokenizer.to_str()) + self.assertIn("huggingface", json_tokenizer["model"]["vocab"]) + + # Will need to be adjusted if we reach v42 and this test is still here. + # Should pick the old tokenizer file as the version of Transformers is < 4.0.0 + shutil.move(os.path.join(tmp_dir, "tokenizer.4.0.0.json"), os.path.join(tmp_dir, "tokenizer.42.0.0.json")) + tokenizer.init_kwargs["fast_tokenizer_files"] = ["tokenizer.42.0.0.json"] + tokenizer.save_pretrained(tmp_dir) + new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir) + self.assertEqual(len(new_tokenizer), len(tokenizer)) + json_tokenizer = json.loads(new_tokenizer._tokenizer.to_str()) + self.assertNotIn("huggingface", json_tokenizer["model"]["vocab"]) + + def test_repo_versioning(self): + # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower. + repo = "hf-internal-testing/test-two-tokenizers" + + # This should pick the new tokenizer file as the version of Transformers is > 4.0.0 + tokenizer = AutoTokenizer.from_pretrained(repo) + self.assertEqual(len(tokenizer), 28997) + json_tokenizer = json.loads(tokenizer._tokenizer.to_str()) + self.assertIn("huggingface", json_tokenizer["model"]["vocab"]) + + # Testing an older version by monkey-patching the version in the module it's used. + import transformers as old_transformers + + old_transformers.tokenization_utils_base.__version__ = "3.0.0" + old_tokenizer = old_transformers.models.auto.AutoTokenizer.from_pretrained(repo) + self.assertEqual(len(old_tokenizer), 28996) + json_tokenizer = json.loads(old_tokenizer._tokenizer.to_str()) + self.assertNotIn("huggingface", json_tokenizer["model"]["vocab"]) + + +@require_tokenizers +class ReduceMutableBorrowTests(unittest.TestCase): + def test_async_share_tokenizer(self): + # See https://github.com/huggingface/transformers/pull/12550 + # and https://github.com/huggingface/tokenizers/issues/537 + tokenizer = PreTrainedTokenizerFast.from_pretrained("robot-test/dummy-tokenizer-wordlevel") + text = "The Matrix is a 1999 science fiction action film." + + with concurrent.futures.ThreadPoolExecutor() as executor: + futures = [executor.submit(self.fetch, tokenizer, text) for i in range(10)] + return_value = [future.result() for future in futures] + self.assertEqual(return_value, [[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10)]) + + def fetch(self, tokenizer, text): + return tokenizer.encode(text, truncation="longest_first", padding="longest") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tokenization/test_tokenization_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tokenization/test_tokenization_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..186fabb7aea08601afe41d477b6f5c8e66c5af1b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tokenization/test_tokenization_utils.py @@ -0,0 +1,285 @@ +# coding=utf-8 +# Copyright 2018 HuggingFace Inc.. +# +# 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. +""" +isort:skip_file +""" +import os +import pickle +import tempfile +import unittest +from typing import Callable, Optional + +import numpy as np + +from transformers import ( + BatchEncoding, + BertTokenizer, + BertTokenizerFast, + PreTrainedTokenizer, + PreTrainedTokenizerFast, + TensorType, + TokenSpan, + is_tokenizers_available, +) +from transformers.models.gpt2.tokenization_gpt2 import GPT2Tokenizer +from transformers.testing_utils import CaptureStderr, require_flax, require_tf, require_tokenizers, require_torch, slow + + +if is_tokenizers_available(): + from tokenizers import Tokenizer + from tokenizers.models import WordPiece + + +class TokenizerUtilsTest(unittest.TestCase): + def check_tokenizer_from_pretrained(self, tokenizer_class): + s3_models = list(tokenizer_class.max_model_input_sizes.keys()) + for model_name in s3_models[:1]: + tokenizer = tokenizer_class.from_pretrained(model_name) + self.assertIsNotNone(tokenizer) + self.assertIsInstance(tokenizer, tokenizer_class) + self.assertIsInstance(tokenizer, PreTrainedTokenizer) + + for special_tok in tokenizer.all_special_tokens: + self.assertIsInstance(special_tok, str) + special_tok_id = tokenizer.convert_tokens_to_ids(special_tok) + self.assertIsInstance(special_tok_id, int) + + def assert_dump_and_restore(self, be_original: BatchEncoding, equal_op: Optional[Callable] = None): + batch_encoding_str = pickle.dumps(be_original) + self.assertIsNotNone(batch_encoding_str) + + be_restored = pickle.loads(batch_encoding_str) + + # Ensure is_fast is correctly restored + self.assertEqual(be_restored.is_fast, be_original.is_fast) + + # Ensure encodings are potentially correctly restored + if be_original.is_fast: + self.assertIsNotNone(be_restored.encodings) + else: + self.assertIsNone(be_restored.encodings) + + # Ensure the keys are the same + for original_v, restored_v in zip(be_original.values(), be_restored.values()): + if equal_op: + self.assertTrue(equal_op(restored_v, original_v)) + else: + self.assertEqual(restored_v, original_v) + + @slow + def test_pretrained_tokenizers(self): + self.check_tokenizer_from_pretrained(GPT2Tokenizer) + + def test_tensor_type_from_str(self): + self.assertEqual(TensorType("tf"), TensorType.TENSORFLOW) + self.assertEqual(TensorType("pt"), TensorType.PYTORCH) + self.assertEqual(TensorType("np"), TensorType.NUMPY) + + @require_tokenizers + def test_batch_encoding_pickle(self): + import numpy as np + + tokenizer_p = BertTokenizer.from_pretrained("bert-base-cased") + tokenizer_r = BertTokenizerFast.from_pretrained("bert-base-cased") + + # Python no tensor + with self.subTest("BatchEncoding (Python, return_tensors=None)"): + self.assert_dump_and_restore(tokenizer_p("Small example to encode")) + + with self.subTest("BatchEncoding (Python, return_tensors=NUMPY)"): + self.assert_dump_and_restore( + tokenizer_p("Small example to encode", return_tensors=TensorType.NUMPY), np.array_equal + ) + + with self.subTest("BatchEncoding (Rust, return_tensors=None)"): + self.assert_dump_and_restore(tokenizer_r("Small example to encode")) + + with self.subTest("BatchEncoding (Rust, return_tensors=NUMPY)"): + self.assert_dump_and_restore( + tokenizer_r("Small example to encode", return_tensors=TensorType.NUMPY), np.array_equal + ) + + @require_tf + @require_tokenizers + def test_batch_encoding_pickle_tf(self): + import tensorflow as tf + + def tf_array_equals(t1, t2): + return tf.reduce_all(tf.equal(t1, t2)) + + tokenizer_p = BertTokenizer.from_pretrained("bert-base-cased") + tokenizer_r = BertTokenizerFast.from_pretrained("bert-base-cased") + + with self.subTest("BatchEncoding (Python, return_tensors=TENSORFLOW)"): + self.assert_dump_and_restore( + tokenizer_p("Small example to encode", return_tensors=TensorType.TENSORFLOW), tf_array_equals + ) + + with self.subTest("BatchEncoding (Rust, return_tensors=TENSORFLOW)"): + self.assert_dump_and_restore( + tokenizer_r("Small example to encode", return_tensors=TensorType.TENSORFLOW), tf_array_equals + ) + + @require_torch + @require_tokenizers + def test_batch_encoding_pickle_pt(self): + import torch + + tokenizer_p = BertTokenizer.from_pretrained("bert-base-cased") + tokenizer_r = BertTokenizerFast.from_pretrained("bert-base-cased") + + with self.subTest("BatchEncoding (Python, return_tensors=PYTORCH)"): + self.assert_dump_and_restore( + tokenizer_p("Small example to encode", return_tensors=TensorType.PYTORCH), torch.equal + ) + + with self.subTest("BatchEncoding (Rust, return_tensors=PYTORCH)"): + self.assert_dump_and_restore( + tokenizer_r("Small example to encode", return_tensors=TensorType.PYTORCH), torch.equal + ) + + @require_tokenizers + def test_batch_encoding_is_fast(self): + tokenizer_p = BertTokenizer.from_pretrained("bert-base-cased") + tokenizer_r = BertTokenizerFast.from_pretrained("bert-base-cased") + + with self.subTest("Python Tokenizer"): + self.assertFalse(tokenizer_p("Small example to_encode").is_fast) + + with self.subTest("Rust Tokenizer"): + self.assertTrue(tokenizer_r("Small example to_encode").is_fast) + + @require_tokenizers + def test_batch_encoding_word_to_tokens(self): + tokenizer_r = BertTokenizerFast.from_pretrained("bert-base-cased") + encoded = tokenizer_r(["Test", "\xad", "test"], is_split_into_words=True) + + self.assertEqual(encoded.word_to_tokens(0), TokenSpan(start=1, end=2)) + self.assertEqual(encoded.word_to_tokens(1), None) + self.assertEqual(encoded.word_to_tokens(2), TokenSpan(start=2, end=3)) + + def test_batch_encoding_with_labels(self): + batch = BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}) + tensor_batch = batch.convert_to_tensors(tensor_type="np") + self.assertEqual(tensor_batch["inputs"].shape, (2, 3)) + self.assertEqual(tensor_batch["labels"].shape, (2,)) + # test converting the converted + with CaptureStderr() as cs: + tensor_batch = batch.convert_to_tensors(tensor_type="np") + self.assertFalse(len(cs.err), msg=f"should have no warning, but got {cs.err}") + + batch = BatchEncoding({"inputs": [1, 2, 3], "labels": 0}) + tensor_batch = batch.convert_to_tensors(tensor_type="np", prepend_batch_axis=True) + self.assertEqual(tensor_batch["inputs"].shape, (1, 3)) + self.assertEqual(tensor_batch["labels"].shape, (1,)) + + @require_torch + def test_batch_encoding_with_labels_pt(self): + batch = BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}) + tensor_batch = batch.convert_to_tensors(tensor_type="pt") + self.assertEqual(tensor_batch["inputs"].shape, (2, 3)) + self.assertEqual(tensor_batch["labels"].shape, (2,)) + # test converting the converted + with CaptureStderr() as cs: + tensor_batch = batch.convert_to_tensors(tensor_type="pt") + self.assertFalse(len(cs.err), msg=f"should have no warning, but got {cs.err}") + + batch = BatchEncoding({"inputs": [1, 2, 3], "labels": 0}) + tensor_batch = batch.convert_to_tensors(tensor_type="pt", prepend_batch_axis=True) + self.assertEqual(tensor_batch["inputs"].shape, (1, 3)) + self.assertEqual(tensor_batch["labels"].shape, (1,)) + + @require_tf + def test_batch_encoding_with_labels_tf(self): + batch = BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}) + tensor_batch = batch.convert_to_tensors(tensor_type="tf") + self.assertEqual(tensor_batch["inputs"].shape, (2, 3)) + self.assertEqual(tensor_batch["labels"].shape, (2,)) + # test converting the converted + with CaptureStderr() as cs: + tensor_batch = batch.convert_to_tensors(tensor_type="tf") + self.assertFalse(len(cs.err), msg=f"should have no warning, but got {cs.err}") + + batch = BatchEncoding({"inputs": [1, 2, 3], "labels": 0}) + tensor_batch = batch.convert_to_tensors(tensor_type="tf", prepend_batch_axis=True) + self.assertEqual(tensor_batch["inputs"].shape, (1, 3)) + self.assertEqual(tensor_batch["labels"].shape, (1,)) + + @require_flax + def test_batch_encoding_with_labels_jax(self): + batch = BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}) + tensor_batch = batch.convert_to_tensors(tensor_type="jax") + self.assertEqual(tensor_batch["inputs"].shape, (2, 3)) + self.assertEqual(tensor_batch["labels"].shape, (2,)) + # test converting the converted + with CaptureStderr() as cs: + tensor_batch = batch.convert_to_tensors(tensor_type="jax") + self.assertFalse(len(cs.err), msg=f"should have no warning, but got {cs.err}") + + batch = BatchEncoding({"inputs": [1, 2, 3], "labels": 0}) + tensor_batch = batch.convert_to_tensors(tensor_type="jax", prepend_batch_axis=True) + self.assertEqual(tensor_batch["inputs"].shape, (1, 3)) + self.assertEqual(tensor_batch["labels"].shape, (1,)) + + def test_padding_accepts_tensors(self): + features = [{"input_ids": np.array([0, 1, 2])}, {"input_ids": np.array([0, 1, 2, 3])}] + tokenizer = BertTokenizer.from_pretrained("bert-base-cased") + + batch = tokenizer.pad(features, padding=True) + self.assertTrue(isinstance(batch["input_ids"], np.ndarray)) + self.assertEqual(batch["input_ids"].tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + batch = tokenizer.pad(features, padding=True, return_tensors="np") + self.assertTrue(isinstance(batch["input_ids"], np.ndarray)) + self.assertEqual(batch["input_ids"].tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + + @require_torch + def test_padding_accepts_tensors_pt(self): + import torch + + features = [{"input_ids": torch.tensor([0, 1, 2])}, {"input_ids": torch.tensor([0, 1, 2, 3])}] + tokenizer = BertTokenizer.from_pretrained("bert-base-cased") + + batch = tokenizer.pad(features, padding=True) + self.assertTrue(isinstance(batch["input_ids"], torch.Tensor)) + self.assertEqual(batch["input_ids"].tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + batch = tokenizer.pad(features, padding=True, return_tensors="pt") + self.assertTrue(isinstance(batch["input_ids"], torch.Tensor)) + self.assertEqual(batch["input_ids"].tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + + @require_tf + def test_padding_accepts_tensors_tf(self): + import tensorflow as tf + + features = [{"input_ids": tf.constant([0, 1, 2])}, {"input_ids": tf.constant([0, 1, 2, 3])}] + tokenizer = BertTokenizer.from_pretrained("bert-base-cased") + + batch = tokenizer.pad(features, padding=True) + self.assertTrue(isinstance(batch["input_ids"], tf.Tensor)) + self.assertEqual(batch["input_ids"].numpy().tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + batch = tokenizer.pad(features, padding=True, return_tensors="tf") + self.assertTrue(isinstance(batch["input_ids"], tf.Tensor)) + self.assertEqual(batch["input_ids"].numpy().tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + + @require_tokenizers + def test_instantiation_from_tokenizers(self): + bert_tokenizer = Tokenizer(WordPiece(unk_token="[UNK]")) + PreTrainedTokenizerFast(tokenizer_object=bert_tokenizer) + + @require_tokenizers + def test_instantiation_from_tokenizers_json_file(self): + bert_tokenizer = Tokenizer(WordPiece(unk_token="[UNK]")) + with tempfile.TemporaryDirectory() as tmpdirname: + bert_tokenizer.save(os.path.join(tmpdirname, "tokenizer.json")) + PreTrainedTokenizerFast(tokenizer_file=os.path.join(tmpdirname, "tokenizer.json")) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_agent_types.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_agent_types.py new file mode 100644 index 0000000000000000000000000000000000000000..a1cc4f70cc653ec81937f087709c94da04c2e551 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_agent_types.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 os +import tempfile +import unittest +import uuid +from pathlib import Path + +from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision +from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText +from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available + + +if is_torch_available(): + import torch + +if is_soundfile_availble(): + import soundfile as sf + +if is_vision_available(): + from PIL import Image + + +def get_new_path(suffix="") -> str: + directory = tempfile.mkdtemp() + return os.path.join(directory, str(uuid.uuid4()) + suffix) + + +@require_soundfile +@require_torch +class AgentAudioTests(unittest.TestCase): + def test_from_tensor(self): + tensor = torch.rand(12, dtype=torch.float64) - 0.5 + agent_type = AgentAudio(tensor) + path = str(agent_type.to_string()) + + # Ensure that the tensor and the agent_type's tensor are the same + self.assertTrue(torch.allclose(tensor, agent_type.to_raw(), atol=1e-4)) + + del agent_type + + # Ensure the path remains even after the object deletion + self.assertTrue(os.path.exists(path)) + + # Ensure that the file contains the same value as the original tensor + new_tensor, _ = sf.read(path) + self.assertTrue(torch.allclose(tensor, torch.tensor(new_tensor), atol=1e-4)) + + def test_from_string(self): + tensor = torch.rand(12, dtype=torch.float64) - 0.5 + path = get_new_path(suffix=".wav") + sf.write(path, tensor, 16000) + + agent_type = AgentAudio(path) + + self.assertTrue(torch.allclose(tensor, agent_type.to_raw(), atol=1e-4)) + self.assertEqual(agent_type.to_string(), path) + + +@require_vision +@require_torch +class AgentImageTests(unittest.TestCase): + def test_from_tensor(self): + tensor = torch.randint(0, 256, (64, 64, 3)) + agent_type = AgentImage(tensor) + path = str(agent_type.to_string()) + + # Ensure that the tensor and the agent_type's tensor are the same + self.assertTrue(torch.allclose(tensor, agent_type._tensor, atol=1e-4)) + + self.assertIsInstance(agent_type.to_raw(), Image.Image) + + # Ensure the path remains even after the object deletion + del agent_type + self.assertTrue(os.path.exists(path)) + + def test_from_string(self): + path = Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png" + image = Image.open(path) + agent_type = AgentImage(path) + + self.assertTrue(path.samefile(agent_type.to_string())) + self.assertTrue(image == agent_type.to_raw()) + + # Ensure the path remains even after the object deletion + del agent_type + self.assertTrue(os.path.exists(path)) + + def test_from_image(self): + path = Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png" + image = Image.open(path) + agent_type = AgentImage(image) + + self.assertFalse(path.samefile(agent_type.to_string())) + self.assertTrue(image == agent_type.to_raw()) + + # Ensure the path remains even after the object deletion + del agent_type + self.assertTrue(os.path.exists(path)) + + +class AgentTextTests(unittest.TestCase): + def test_from_string(self): + string = "Hey!" + agent_type = AgentText(string) + + self.assertEqual(string, agent_type.to_string()) + self.assertEqual(string, agent_type.to_raw()) + self.assertEqual(string, agent_type) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_document_question_answering.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_document_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..1d77bcb470800478c5515340308b2f6171cab3ec --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_document_question_answering.py @@ -0,0 +1,56 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from datasets import load_dataset + +from transformers import load_tool + +from .test_tools_common import ToolTesterMixin + + +class DocumentQuestionAnsweringToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("document-question-answering") + self.tool.setup() + self.remote_tool = load_tool("document-question-answering", remote=True) + + def test_exact_match_arg(self): + dataset = load_dataset("hf-internal-testing/example-documents", split="test") + document = dataset[0]["image"] + + result = self.tool(document, "When is the coffee break?") + self.assertEqual(result, "11-14 to 11:39 a.m.") + + def test_exact_match_arg_remote(self): + dataset = load_dataset("hf-internal-testing/example-documents", split="test") + document = dataset[0]["image"] + + result = self.remote_tool(document, "When is the coffee break?") + self.assertEqual(result, "11-14 to 11:39 a.m.") + + def test_exact_match_kwarg(self): + dataset = load_dataset("hf-internal-testing/example-documents", split="test") + document = dataset[0]["image"] + + self.tool(document=document, question="When is the coffee break?") + + def test_exact_match_kwarg_remote(self): + dataset = load_dataset("hf-internal-testing/example-documents", split="test") + document = dataset[0]["image"] + + result = self.remote_tool(document=document, question="When is the coffee break?") + self.assertEqual(result, "11-14 to 11:39 a.m.") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_captioning.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_captioning.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd06eb44435afe433cca15401c2d1cdd307e6e2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_captioning.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest +from pathlib import Path + +from transformers import is_vision_available, load_tool +from transformers.testing_utils import get_tests_dir + +from .test_tools_common import ToolTesterMixin + + +if is_vision_available(): + from PIL import Image + + +class ImageCaptioningToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("image-captioning") + self.tool.setup() + self.remote_tool = load_tool("image-captioning", remote=True) + + def test_exact_match_arg(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.tool(image) + self.assertEqual(result, "two cats sleeping on a couch") + + def test_exact_match_arg_remote(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.remote_tool(image) + self.assertEqual(result, "two cats sleeping on a couch") + + def test_exact_match_kwarg(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.tool(image=image) + self.assertEqual(result, "two cats sleeping on a couch") + + def test_exact_match_kwarg_remote(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.remote_tool(image=image) + self.assertEqual(result, "two cats sleeping on a couch") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_question_answering.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..035b1b4fa045bd0d10a33619e2833979655419dc --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_question_answering.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest +from pathlib import Path + +from transformers import is_vision_available, load_tool +from transformers.testing_utils import get_tests_dir + +from .test_tools_common import ToolTesterMixin + + +if is_vision_available(): + from PIL import Image + + +class ImageQuestionAnsweringToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("image-question-answering") + self.tool.setup() + self.remote_tool = load_tool("image-question-answering", remote=True) + + def test_exact_match_arg(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.tool(image, "How many cats are sleeping on the couch?") + self.assertEqual(result, "2") + + def test_exact_match_arg_remote(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.remote_tool(image, "How many cats are sleeping on the couch?") + self.assertEqual(result, "2") + + def test_exact_match_kwarg(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.tool(image=image, question="How many cats are sleeping on the couch?") + self.assertEqual(result, "2") + + def test_exact_match_kwarg_remote(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.remote_tool(image=image, question="How many cats are sleeping on the couch?") + self.assertEqual(result, "2") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_segmentation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..2f003f2c8b91d1b499e5af0f34264cffcbb127e0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_image_segmentation.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest +from pathlib import Path + +from transformers import is_vision_available, load_tool +from transformers.testing_utils import get_tests_dir + +from .test_tools_common import ToolTesterMixin + + +if is_vision_available(): + from PIL import Image + + +class ImageSegmentationToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("image-segmentation") + self.tool.setup() + self.remote_tool = load_tool("image-segmentation", remote=True) + + def test_exact_match_arg(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.tool(image, "cat") + self.assertTrue(isinstance(result, Image.Image)) + + def test_exact_match_arg_remote(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.remote_tool(image, "cat") + self.assertTrue(isinstance(result, Image.Image)) + + def test_exact_match_kwarg(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.tool(image=image, label="cat") + self.assertTrue(isinstance(result, Image.Image)) + + def test_exact_match_kwarg_remote(self): + image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png") + result = self.remote_tool(image=image, label="cat") + self.assertTrue(isinstance(result, Image.Image)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_python_interpreter.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_python_interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a38b4a21f1383489951bcce3e42e3dfbc9fba9 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_python_interpreter.py @@ -0,0 +1,131 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers.testing_utils import CaptureStdout +from transformers.tools.python_interpreter import evaluate + + +# Fake function we will use as tool +def add_two(x): + return x + 2 + + +class PythonInterpreterTester(unittest.TestCase): + def test_evaluate_assign(self): + code = "x = 3" + state = {} + result = evaluate(code, {}, state=state) + assert result == 3 + self.assertDictEqual(state, {"x": 3}) + + code = "x = y" + state = {"y": 5} + result = evaluate(code, {}, state=state) + # evaluate returns the value of the last assignment. + assert result == 5 + self.assertDictEqual(state, {"x": 5, "y": 5}) + + def test_evaluate_call(self): + code = "y = add_two(x)" + state = {"x": 3} + result = evaluate(code, {"add_two": add_two}, state=state) + assert result == 5 + self.assertDictEqual(state, {"x": 3, "y": 5}) + + # Won't work without the tool + with CaptureStdout() as out: + result = evaluate(code, {}, state=state) + assert result is None + assert "tried to execute add_two" in out.out + + def test_evaluate_constant(self): + code = "x = 3" + state = {} + result = evaluate(code, {}, state=state) + assert result == 3 + self.assertDictEqual(state, {"x": 3}) + + def test_evaluate_dict(self): + code = "test_dict = {'x': x, 'y': add_two(x)}" + state = {"x": 3} + result = evaluate(code, {"add_two": add_two}, state=state) + self.assertDictEqual(result, {"x": 3, "y": 5}) + self.assertDictEqual(state, {"x": 3, "test_dict": {"x": 3, "y": 5}}) + + def test_evaluate_expression(self): + code = "x = 3\ny = 5" + state = {} + result = evaluate(code, {}, state=state) + # evaluate returns the value of the last assignment. + assert result == 5 + self.assertDictEqual(state, {"x": 3, "y": 5}) + + def test_evaluate_f_string(self): + code = "text = f'This is x: {x}.'" + state = {"x": 3} + result = evaluate(code, {}, state=state) + # evaluate returns the value of the last assignment. + assert result == "This is x: 3." + self.assertDictEqual(state, {"x": 3, "text": "This is x: 3."}) + + def test_evaluate_if(self): + code = "if x <= 3:\n y = 2\nelse:\n y = 5" + state = {"x": 3} + result = evaluate(code, {}, state=state) + # evaluate returns the value of the last assignment. + assert result == 2 + self.assertDictEqual(state, {"x": 3, "y": 2}) + + state = {"x": 8} + result = evaluate(code, {}, state=state) + # evaluate returns the value of the last assignment. + assert result == 5 + self.assertDictEqual(state, {"x": 8, "y": 5}) + + def test_evaluate_list(self): + code = "test_list = [x, add_two(x)]" + state = {"x": 3} + result = evaluate(code, {"add_two": add_two}, state=state) + self.assertListEqual(result, [3, 5]) + self.assertDictEqual(state, {"x": 3, "test_list": [3, 5]}) + + def test_evaluate_name(self): + code = "y = x" + state = {"x": 3} + result = evaluate(code, {}, state=state) + assert result == 3 + self.assertDictEqual(state, {"x": 3, "y": 3}) + + def test_evaluate_subscript(self): + code = "test_list = [x, add_two(x)]\ntest_list[1]" + state = {"x": 3} + result = evaluate(code, {"add_two": add_two}, state=state) + assert result == 5 + self.assertDictEqual(state, {"x": 3, "test_list": [3, 5]}) + + code = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" + state = {"x": 3} + result = evaluate(code, {"add_two": add_two}, state=state) + assert result == 5 + self.assertDictEqual(state, {"x": 3, "test_dict": {"x": 3, "y": 5}}) + + def test_evaluate_for(self): + code = "x = 0\nfor i in range(3):\n x = i" + state = {} + result = evaluate(code, {"range": range}, state=state) + assert result == 2 + self.assertDictEqual(state, {"x": 2, "i": 2}) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_speech_to_text.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..9383cf0465f83f8736bf5bc4bc8da1559ec4edd8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_speech_to_text.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers import is_torch_available, load_tool + +from .test_tools_common import ToolTesterMixin + + +if is_torch_available(): + import torch + + +class SpeechToTextToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("speech-to-text") + self.tool.setup() + + def test_exact_match_arg(self): + result = self.tool(torch.ones(3000)) + self.assertEqual(result, " you") + + def test_exact_match_kwarg(self): + result = self.tool(audio=torch.ones(3000)) + self.assertEqual(result, " you") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_classification.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..b40067490c613416cab7203b7e08c67501bfb1e8 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_classification.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers import load_tool + +from .test_tools_common import ToolTesterMixin + + +class TextClassificationToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("text-classification") + self.tool.setup() + self.remote_tool = load_tool("text-classification", remote=True) + + def test_exact_match_arg(self): + result = self.tool("That's quite cool", ["positive", "negative"]) + self.assertEqual(result, "positive") + + def test_exact_match_arg_remote(self): + result = self.remote_tool("That's quite cool", ["positive", "negative"]) + self.assertEqual(result, "positive") + + def test_exact_match_kwarg(self): + result = self.tool(text="That's quite cool", labels=["positive", "negative"]) + self.assertEqual(result, "positive") + + def test_exact_match_kwarg_remote(self): + result = self.remote_tool(text="That's quite cool", labels=["positive", "negative"]) + self.assertEqual(result, "positive") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_question_answering.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..aed2898f0153096cd4778007f12053b7b4cdf2e9 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_question_answering.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers import load_tool + +from .test_tools_common import ToolTesterMixin + + +TEXT = """ +Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning. + +In March 2021, Hugging Face raised $40 million in a Series B funding round.[3] + +On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5] +""" + + +class TextQuestionAnsweringToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("text-question-answering") + self.tool.setup() + self.remote_tool = load_tool("text-question-answering", remote=True) + + def test_exact_match_arg(self): + result = self.tool(TEXT, "What did Hugging Face do in April 2021?") + self.assertEqual(result, "launched the BigScience Research Workshop") + + def test_exact_match_arg_remote(self): + result = self.remote_tool(TEXT, "What did Hugging Face do in April 2021?") + self.assertEqual(result, "launched the BigScience Research Workshop") + + def test_exact_match_kwarg(self): + result = self.tool(text=TEXT, question="What did Hugging Face do in April 2021?") + self.assertEqual(result, "launched the BigScience Research Workshop") + + def test_exact_match_kwarg_remote(self): + result = self.remote_tool(text=TEXT, question="What did Hugging Face do in April 2021?") + self.assertEqual(result, "launched the BigScience Research Workshop") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_summarization.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_summarization.py new file mode 100644 index 0000000000000000000000000000000000000000..162443f373a40e903dba38f9fb7af26562e06c53 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_summarization.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers import load_tool + +from .test_tools_common import ToolTesterMixin + + +TEXT = """ +Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning. + +In March 2021, Hugging Face raised $40 million in a Series B funding round.[3] + +On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5] +""" + + +class TextSummarizationToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("summarization") + self.tool.setup() + self.remote_tool = load_tool("summarization", remote=True) + + def test_exact_match_arg(self): + result = self.tool(TEXT) + self.assertEqual( + result, + "Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.", + ) + + def test_exact_match_arg_remote(self): + result = self.remote_tool(TEXT) + self.assertEqual( + result, + "Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.", + ) + + def test_exact_match_kwarg(self): + result = self.tool(text=TEXT) + self.assertEqual( + result, + "Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.", + ) + + def test_exact_match_kwarg_remote(self): + result = self.remote_tool(text=TEXT) + self.assertEqual( + result, + "Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.", + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_to_speech.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_to_speech.py new file mode 100644 index 0000000000000000000000000000000000000000..a63017d27706df32f99a1bc2be9b6dcb73211d1e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_text_to_speech.py @@ -0,0 +1,58 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers import load_tool +from transformers.utils import is_torch_available + + +if is_torch_available(): + import torch + +from transformers.testing_utils import require_torch + +from .test_tools_common import ToolTesterMixin + + +@require_torch +class TextToSpeechToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("text-to-speech") + self.tool.setup() + + def test_exact_match_arg(self): + # SpeechT5 isn't deterministic + torch.manual_seed(0) + result = self.tool("hey") + resulting_tensor = result.to_raw() + self.assertTrue( + torch.allclose( + resulting_tensor[:3], + torch.tensor([-0.0005966668832115829, -0.0003657640190795064, -0.00013439502799883485]), + ) + ) + + def test_exact_match_kwarg(self): + # SpeechT5 isn't deterministic + torch.manual_seed(0) + result = self.tool("hey") + resulting_tensor = result.to_raw() + self.assertTrue( + torch.allclose( + resulting_tensor[:3], + torch.tensor([-0.0005966668832115829, -0.0003657640190795064, -0.00013439502799883485]), + ) + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_tools_common.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_tools_common.py new file mode 100644 index 0000000000000000000000000000000000000000..984edfcd8c60a5b8ca9841503b6f05c4a75f7471 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_tools_common.py @@ -0,0 +1,133 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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. + +from pathlib import Path +from typing import List + +from transformers import is_torch_available, is_vision_available +from transformers.testing_utils import get_tests_dir, is_tool_test +from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + +authorized_types = ["text", "image", "audio"] + + +def create_inputs(input_types: List[str]): + inputs = [] + + for input_type in input_types: + if input_type == "text": + inputs.append("Text input") + elif input_type == "image": + inputs.append( + Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png").resize((512, 512)) + ) + elif input_type == "audio": + inputs.append(torch.ones(3000)) + elif isinstance(input_type, list): + inputs.append(create_inputs(input_type)) + else: + raise ValueError(f"Invalid type requested: {input_type}") + + return inputs + + +def output_types(outputs: List): + output_types = [] + + for output in outputs: + if isinstance(output, (str, AgentText)): + output_types.append("text") + elif isinstance(output, (Image.Image, AgentImage)): + output_types.append("image") + elif isinstance(output, (torch.Tensor, AgentAudio)): + output_types.append("audio") + else: + raise ValueError(f"Invalid output: {output}") + + return output_types + + +@is_tool_test +class ToolTesterMixin: + def test_inputs_outputs(self): + self.assertTrue(hasattr(self.tool, "inputs")) + self.assertTrue(hasattr(self.tool, "outputs")) + + inputs = self.tool.inputs + for _input in inputs: + if isinstance(_input, list): + for __input in _input: + self.assertTrue(__input in authorized_types) + else: + self.assertTrue(_input in authorized_types) + + outputs = self.tool.outputs + for _output in outputs: + self.assertTrue(_output in authorized_types) + + def test_call(self): + inputs = create_inputs(self.tool.inputs) + outputs = self.tool(*inputs) + + # There is a single output + if len(self.tool.outputs) == 1: + outputs = [outputs] + + self.assertListEqual(output_types(outputs), self.tool.outputs) + + def test_common_attributes(self): + self.assertTrue(hasattr(self.tool, "description")) + self.assertTrue(hasattr(self.tool, "default_checkpoint")) + self.assertTrue(self.tool.description.startswith("This is a tool that")) + + def test_agent_types_outputs(self): + inputs = create_inputs(self.tool.inputs) + outputs = self.tool(*inputs) + + if not isinstance(outputs, list): + outputs = [outputs] + + self.assertEqual(len(outputs), len(self.tool.outputs)) + + for output, output_type in zip(outputs, self.tool.outputs): + agent_type = AGENT_TYPE_MAPPING[output_type] + self.assertTrue(isinstance(output, agent_type)) + + def test_agent_types_inputs(self): + inputs = create_inputs(self.tool.inputs) + + _inputs = [] + + for _input, input_type in zip(inputs, self.tool.inputs): + if isinstance(input_type, list): + _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input) for _input_type in input_type]) + else: + _inputs.append(AGENT_TYPE_MAPPING[input_type](_input)) + + # Should not raise an error + outputs = self.tool(*inputs) + + if not isinstance(outputs, list): + outputs = [outputs] + + self.assertEqual(len(outputs), len(self.tool.outputs)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_translation.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..15e1c8cd6ae4fa40e2eae93160f149ce358fc119 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/tools/test_translation.py @@ -0,0 +1,86 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +from transformers import load_tool +from transformers.tools.agent_types import AGENT_TYPE_MAPPING + +from .test_tools_common import ToolTesterMixin, output_types + + +class TranslationToolTester(unittest.TestCase, ToolTesterMixin): + def setUp(self): + self.tool = load_tool("translation") + self.tool.setup() + self.remote_tool = load_tool("translation", remote=True) + + def test_exact_match_arg(self): + result = self.tool("Hey, what's up?", src_lang="English", tgt_lang="French") + self.assertEqual(result, "- Hé, comment ça va?") + + def test_exact_match_arg_remote(self): + result = self.remote_tool("Hey, what's up?", src_lang="English", tgt_lang="French") + self.assertEqual(result, "- Hé, comment ça va?") + + def test_exact_match_kwarg(self): + result = self.tool(text="Hey, what's up?", src_lang="English", tgt_lang="French") + self.assertEqual(result, "- Hé, comment ça va?") + + def test_exact_match_kwarg_remote(self): + result = self.remote_tool(text="Hey, what's up?", src_lang="English", tgt_lang="French") + self.assertEqual(result, "- Hé, comment ça va?") + + def test_call(self): + inputs = ["Hey, what's up?", "English", "Spanish"] + outputs = self.tool(*inputs) + + # There is a single output + if len(self.tool.outputs) == 1: + outputs = [outputs] + + self.assertListEqual(output_types(outputs), self.tool.outputs) + + def test_agent_types_outputs(self): + inputs = ["Hey, what's up?", "English", "Spanish"] + outputs = self.tool(*inputs) + + if not isinstance(outputs, list): + outputs = [outputs] + + self.assertEqual(len(outputs), len(self.tool.outputs)) + + for output, output_type in zip(outputs, self.tool.outputs): + agent_type = AGENT_TYPE_MAPPING[output_type] + self.assertTrue(isinstance(output, agent_type)) + + def test_agent_types_inputs(self): + inputs = ["Hey, what's up?", "English", "Spanish"] + + _inputs = [] + + for _input, input_type in zip(inputs, self.tool.inputs): + if isinstance(input_type, list): + _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input) for _input_type in input_type]) + else: + _inputs.append(AGENT_TYPE_MAPPING[input_type](_input)) + + # Should not raise an error + outputs = self.tool(*inputs) + + if not isinstance(outputs, list): + outputs = [outputs] + + self.assertEqual(len(outputs), len(self.tool.outputs)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_data_collator.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_data_collator.py new file mode 100644 index 0000000000000000000000000000000000000000..f5104cd37507e01753741208c37f3b8956ed47b5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_data_collator.py @@ -0,0 +1,924 @@ +# 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 os +import shutil +import tempfile +import unittest + +import numpy as np + +from transformers import ( + BertTokenizer, + DataCollatorForLanguageModeling, + DataCollatorForPermutationLanguageModeling, + DataCollatorForTokenClassification, + DataCollatorForWholeWordMask, + DataCollatorWithPadding, + default_data_collator, + is_tf_available, + is_torch_available, + set_seed, +) +from transformers.testing_utils import require_tf, require_torch + + +if is_torch_available(): + import torch + +if is_tf_available(): + import tensorflow as tf + + +@require_torch +class DataCollatorIntegrationTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] + self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_default_with_dict(self): + features = [{"label": i, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) + + # With label_ids + features = [{"label_ids": [0, 1, 2], "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue(batch["labels"].equal(torch.tensor([[0, 1, 2]] * 8))) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) + + # Features can already be tensors + features = [{"label": i, "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 10])) + + # Labels can already be tensors + features = [{"label": torch.tensor(i), "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 10])) + + def test_default_classification_and_regression(self): + data_collator = default_data_collator + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": i} for i in range(4)] + batch = data_collator(features) + self.assertEqual(batch["labels"].dtype, torch.long) + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": float(i)} for i in range(4)] + batch = data_collator(features) + self.assertEqual(batch["labels"].dtype, torch.float) + + def test_default_with_no_labels(self): + features = [{"label": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) + + # With label_ids + features = [{"label_ids": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) + + def test_data_collator_with_padding(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + + data_collator = DataCollatorWithPadding(tokenizer) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) + + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) + + def test_data_collator_for_token_classification(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2], "labels": [0, 1, 2]}, + {"input_ids": [0, 1, 2, 3, 4, 5], "labels": [0, 1, 2, 3, 4, 5]}, + ] + + data_collator = DataCollatorForTokenClassification(tokenizer) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) + + data_collator = DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 10])) + + data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 8])) + + data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) + + for feature in features: + feature.pop("labels") + + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + def test_data_collator_for_token_classification_works_with_pt_tensors(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": torch.tensor([0, 1, 2]), "labels": torch.tensor([0, 1, 2])}, + {"input_ids": torch.tensor([0, 1, 2, 3, 4, 5]), "labels": torch.tensor([0, 1, 2, 3, 4, 5])}, + ] + + data_collator = DataCollatorForTokenClassification(tokenizer) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) + + data_collator = DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 10])) + + data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 8])) + + data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) + + for feature in features: + feature.pop("labels") + + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + def _test_no_pad_and_pad(self, no_pad_features, pad_features): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) + + tokenizer._pad_token = None + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False) + with self.assertRaises(ValueError): + # Expect error due to padding token missing + data_collator(pad_features) + + set_seed(42) # For reproducibility + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(torch.any(masked_tokens)) + self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(torch.any(masked_tokens)) + self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(torch.any(masked_tokens)) + self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(torch.any(masked_tokens)) + self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + def test_data_collator_for_language_modeling(self): + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + no_pad_features = [list(range(10)), list(range(10))] + pad_features = [list(range(5)), list(range(10))] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + def test_data_collator_for_whole_word_mask(self): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="pt") + + features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + # Features can already be tensors + features = [{"input_ids": np.arange(10)}, {"input_ids": np.arange(10)}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + def test_plm(self): + tokenizer = BertTokenizer(self.vocab_file) + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + + data_collator = DataCollatorForPermutationLanguageModeling(tokenizer) + + batch = data_collator(pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["perm_mask"].shape, torch.Size((2, 10, 10))) + self.assertEqual(batch["target_mapping"].shape, torch.Size((2, 10, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + batch = data_collator(no_pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["perm_mask"].shape, torch.Size((2, 10, 10))) + self.assertEqual(batch["target_mapping"].shape, torch.Size((2, 10, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + example = [np.random.randint(0, 5, [5])] + with self.assertRaises(ValueError): + # Expect error due to odd sequence length + data_collator(example) + + def test_nsp(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer) + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 5))) + self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 5))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 5))) + self.assertEqual(batch["next_sentence_label"].shape, torch.Size((2,))) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 8))) + self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 8))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 8))) + self.assertEqual(batch["next_sentence_label"].shape, torch.Size((2,))) + + def test_sop(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + { + "input_ids": torch.tensor([0, 1, 2, 3, 4]), + "token_type_ids": torch.tensor([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer) + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 5))) + self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 5))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 5))) + self.assertEqual(batch["sentence_order_label"].shape, torch.Size((2,))) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 8))) + self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 8))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 8))) + self.assertEqual(batch["sentence_order_label"].shape, torch.Size((2,))) + + +@require_tf +class TFDataCollatorIntegrationTest(unittest.TestCase): + def setUp(self): + super().setUp() + self.tmpdirname = tempfile.mkdtemp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] + self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_default_with_dict(self): + features = [{"label": i, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="tf") + self.assertEqual(batch["labels"].numpy().tolist(), list(range(8))) + self.assertEqual(batch["labels"].dtype, tf.int64) + self.assertEqual(batch["inputs"].shape.as_list(), [8, 6]) + + # With label_ids + features = [{"label_ids": [0, 1, 2], "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="tf") + self.assertEqual(batch["labels"].numpy().tolist(), ([[0, 1, 2]] * 8)) + self.assertEqual(batch["labels"].dtype, tf.int64) + self.assertEqual(batch["inputs"].shape.as_list(), [8, 6]) + + # Features can already be tensors + features = [{"label": i, "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features, return_tensors="tf") + self.assertEqual(batch["labels"].numpy().tolist(), (list(range(8)))) + self.assertEqual(batch["labels"].dtype, tf.int64) + self.assertEqual(batch["inputs"].shape.as_list(), [8, 10]) + + # Labels can already be tensors + features = [{"label": np.array(i), "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features, return_tensors="tf") + self.assertEqual(batch["labels"].dtype, tf.int64) + self.assertEqual(batch["labels"].numpy().tolist(), list(range(8))) + self.assertEqual(batch["labels"].dtype, tf.int64) + self.assertEqual(batch["inputs"].shape.as_list(), [8, 10]) + + def test_numpy_dtype_preservation(self): + data_collator = default_data_collator + + # Confirms that numpy inputs are handled correctly even when scalars + features = [{"input_ids": np.array([0, 1, 2, 3, 4]), "label": np.int64(i)} for i in range(4)] + batch = data_collator(features, return_tensors="tf") + self.assertEqual(batch["labels"].dtype, tf.int64) + + def test_default_classification_and_regression(self): + data_collator = default_data_collator + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": i} for i in range(4)] + batch = data_collator(features, return_tensors="tf") + self.assertEqual(batch["labels"].dtype, tf.int64) + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": float(i)} for i in range(4)] + batch = data_collator(features, return_tensors="tf") + self.assertEqual(batch["labels"].dtype, tf.float32) + + def test_default_with_no_labels(self): + features = [{"label": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="tf") + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape.as_list(), [8, 6]) + + # With label_ids + features = [{"label_ids": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="tf") + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape.as_list(), [8, 6]) + + def test_data_collator_with_padding(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + + data_collator = DataCollatorWithPadding(tokenizer, return_tensors="tf") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 6]) + self.assertEqual(batch["input_ids"][0].numpy().tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10, return_tensors="tf") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8, return_tensors="tf") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, [2, 8]) + + def test_data_collator_for_token_classification(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2], "labels": [0, 1, 2]}, + {"input_ids": [0, 1, 2, 3, 4, 5], "labels": [0, 1, 2, 3, 4, 5]}, + ] + + data_collator = DataCollatorForTokenClassification(tokenizer, return_tensors="tf") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 6]) + self.assertEqual(batch["input_ids"][0].numpy().tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape.as_list(), [2, 6]) + self.assertEqual(batch["labels"][0].numpy().tolist(), [0, 1, 2] + [-100] * 3) + + data_collator = DataCollatorForTokenClassification( + tokenizer, padding="max_length", max_length=10, return_tensors="tf" + ) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8, return_tensors="tf") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 8]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 8]) + + data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1, return_tensors="tf") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 6]) + self.assertEqual(batch["input_ids"][0].numpy().tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape.as_list(), [2, 6]) + self.assertEqual(batch["labels"][0].numpy().tolist(), [0, 1, 2] + [-1] * 3) + + def _test_no_pad_and_pad(self, no_pad_features, pad_features): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="tf") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + data_collator = DataCollatorForLanguageModeling( + tokenizer, mlm=False, pad_to_multiple_of=8, return_tensors="tf" + ) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 16]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 16]) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 16]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 16]) + + tokenizer._pad_token = None + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="tf") + with self.assertRaises(ValueError): + # Expect error due to padding token missing + data_collator(pad_features) + + set_seed(42) # For reproducibility + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="tf") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(tf.reduce_any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"].numpy()[~masked_tokens.numpy()].tolist())) + + batch = data_collator(pad_features, return_tensors="tf") + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(tf.reduce_any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"].numpy()[~masked_tokens.numpy()].tolist())) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="tf") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 16]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 16]) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(tf.reduce_any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"].numpy()[~masked_tokens.numpy()].tolist())) + + batch = data_collator(pad_features, return_tensors="tf") + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 16]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 16]) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(tf.reduce_any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"].numpy()[~masked_tokens.numpy()].tolist())) + + def test_data_collator_for_language_modeling(self): + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + no_pad_features = [list(range(10)), list(range(10))] + pad_features = [list(range(5)), list(range(10))] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + def test_data_collator_for_whole_word_mask(self): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="tf") + + features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + # Features can already be tensors + features = [{"input_ids": np.arange(10)}, {"input_ids": np.arange(10)}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + def test_plm(self): + tokenizer = BertTokenizer(self.vocab_file) + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + + data_collator = DataCollatorForPermutationLanguageModeling(tokenizer, return_tensors="tf") + + batch = data_collator(pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["perm_mask"].shape.as_list(), [2, 10, 10]) + self.assertEqual(batch["target_mapping"].shape.as_list(), [2, 10, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + batch = data_collator(no_pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 10]) + self.assertEqual(batch["perm_mask"].shape.as_list(), [2, 10, 10]) + self.assertEqual(batch["target_mapping"].shape.as_list(), [2, 10, 10]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 10]) + + example = [np.random.randint(0, 5, [5])] + with self.assertRaises(ValueError): + # Expect error due to odd sequence length + data_collator(example) + + def test_nsp(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="tf") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 5]) + self.assertEqual(batch["token_type_ids"].shape.as_list(), [2, 5]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 5]) + self.assertEqual(batch["next_sentence_label"].shape.as_list(), [2]) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="tf") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 8]) + self.assertEqual(batch["token_type_ids"].shape.as_list(), [2, 8]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 8]) + self.assertEqual(batch["next_sentence_label"].shape.as_list(), [2]) + + def test_sop(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + { + "input_ids": tf.convert_to_tensor([0, 1, 2, 3, 4]), + "token_type_ids": tf.convert_to_tensor([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="tf") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 5]) + self.assertEqual(batch["token_type_ids"].shape.as_list(), [2, 5]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 5]) + self.assertEqual(batch["sentence_order_label"].shape.as_list(), [2]) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="tf") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape.as_list(), [2, 8]) + self.assertEqual(batch["token_type_ids"].shape.as_list(), [2, 8]) + self.assertEqual(batch["labels"].shape.as_list(), [2, 8]) + self.assertEqual(batch["sentence_order_label"].shape.as_list(), [2]) + + +class NumpyDataCollatorIntegrationTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] + self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_default_with_dict(self): + features = [{"label": i, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].tolist(), list(range(8))) + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["inputs"].shape, (8, 6)) + + # With label_ids + features = [{"label_ids": [0, 1, 2], "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].tolist(), [[0, 1, 2]] * 8) + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["inputs"].shape, (8, 6)) + + # Features can already be tensors + features = [{"label": i, "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].tolist(), list(range(8))) + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["inputs"].shape, (8, 10)) + + # Labels can already be tensors + features = [{"label": np.array(i), "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["labels"].tolist(), (list(range(8)))) + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["inputs"].shape, (8, 10)) + + def test_default_classification_and_regression(self): + data_collator = default_data_collator + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": i} for i in range(4)] + batch = data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].dtype, np.int64) + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": float(i)} for i in range(4)] + batch = data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].dtype, np.float32) + + def test_default_with_no_labels(self): + features = [{"label": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape, (8, 6)) + + # With label_ids + features = [{"label_ids": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape, (8, 6)) + + def test_data_collator_with_padding(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + + data_collator = DataCollatorWithPadding(tokenizer, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 8)) + + def test_data_collator_for_token_classification(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2], "labels": [0, 1, 2]}, + {"input_ids": [0, 1, 2, 3, 4, 5], "labels": [0, 1, 2, 3, 4, 5]}, + ] + + data_collator = DataCollatorForTokenClassification(tokenizer, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, (2, 6)) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) + + data_collator = DataCollatorForTokenClassification( + tokenizer, padding="max_length", max_length=10, return_tensors="np" + ) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 8)) + self.assertEqual(batch["labels"].shape, (2, 8)) + + data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, (2, 6)) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) + + def _test_no_pad_and_pad(self, no_pad_features, pad_features): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="np") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + batch = data_collator(pad_features, return_tensors="np") + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + data_collator = DataCollatorForLanguageModeling( + tokenizer, mlm=False, pad_to_multiple_of=8, return_tensors="np" + ) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 16)) + self.assertEqual(batch["labels"].shape, (2, 16)) + + batch = data_collator(pad_features, return_tensors="np") + self.assertEqual(batch["input_ids"].shape, (2, 16)) + self.assertEqual(batch["labels"].shape, (2, 16)) + + tokenizer._pad_token = None + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="np") + with self.assertRaises(ValueError): + # Expect error due to padding token missing + data_collator(pad_features) + + set_seed(42) # For reproducibility + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(np.any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(np.any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 16)) + self.assertEqual(batch["labels"].shape, (2, 16)) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(np.any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 16)) + self.assertEqual(batch["labels"].shape, (2, 16)) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(np.any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + def test_data_collator_for_language_modeling(self): + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + no_pad_features = [list(range(10)), list(range(10))] + pad_features = [list(range(5)), list(range(10))] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + def test_data_collator_for_whole_word_mask(self): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="np") + + features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + # Features can already be tensors + features = [{"input_ids": np.arange(10)}, {"input_ids": np.arange(10)}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + def test_plm(self): + tokenizer = BertTokenizer(self.vocab_file) + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + + data_collator = DataCollatorForPermutationLanguageModeling(tokenizer, return_tensors="np") + + batch = data_collator(pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["perm_mask"].shape, (2, 10, 10)) + self.assertEqual(batch["target_mapping"].shape, (2, 10, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + batch = data_collator(no_pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["perm_mask"].shape, (2, 10, 10)) + self.assertEqual(batch["target_mapping"].shape, (2, 10, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + example = [np.random.randint(0, 5, [5])] + with self.assertRaises(ValueError): + # Expect error due to odd sequence length + data_collator(example) + + def test_nsp(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, (2, 5)) + self.assertEqual(batch["token_type_ids"].shape, (2, 5)) + self.assertEqual(batch["labels"].shape, (2, 5)) + self.assertEqual(batch["next_sentence_label"].shape, (2,)) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, (2, 8)) + self.assertEqual(batch["token_type_ids"].shape, (2, 8)) + self.assertEqual(batch["labels"].shape, (2, 8)) + self.assertEqual(batch["next_sentence_label"].shape, (2,)) + + def test_sop(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + { + "input_ids": np.array([0, 1, 2, 3, 4]), + "token_type_ids": np.array([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, (2, 5)) + self.assertEqual(batch["token_type_ids"].shape, (2, 5)) + self.assertEqual(batch["labels"].shape, (2, 5)) + self.assertEqual(batch["sentence_order_label"].shape, (2,)) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, (2, 8)) + self.assertEqual(batch["token_type_ids"].shape, (2, 8)) + self.assertEqual(batch["labels"].shape, (2, 8)) + self.assertEqual(batch["sentence_order_label"].shape, (2,)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..05f84bc00fa2afda3d3e2aa01bf4bb34055b9270 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer.py @@ -0,0 +1,3119 @@ +# coding=utf-8 +# Copyright 2018 the HuggingFace Inc. team. +# +# 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 dataclasses +import gc +import json +import math +import os +import random +import re +import subprocess +import sys +import tempfile +import unittest +from itertools import product +from pathlib import Path +from typing import Dict, List +from unittest.mock import Mock, patch + +import numpy as np +from huggingface_hub import HfFolder, delete_repo, list_repo_commits, list_repo_files +from parameterized import parameterized +from requests.exceptions import HTTPError + +from transformers import ( + AutoTokenizer, + IntervalStrategy, + PretrainedConfig, + TrainerCallback, + TrainingArguments, + get_polynomial_decay_schedule_with_warmup, + is_torch_available, + logging, +) +from transformers.hyperparameter_search import ALL_HYPERPARAMETER_SEARCH_BACKENDS +from transformers.testing_utils import ( + ENDPOINT_STAGING, + TOKEN, + USER, + CaptureLogger, + TestCasePlus, + backend_device_count, + execute_subprocess_async, + get_gpu_count, + get_tests_dir, + is_staging_test, + require_accelerate, + require_intel_extension_for_pytorch, + require_optuna, + require_ray, + require_safetensors, + require_sentencepiece, + require_sigopt, + require_tensorboard, + require_tokenizers, + require_torch, + require_torch_accelerator, + require_torch_bf16, + require_torch_gpu, + require_torch_multi_accelerator, + require_torch_non_multi_accelerator, + require_torch_non_multi_gpu, + require_torch_tensorrt_fx, + require_torch_tf32, + require_torch_up_to_2_accelerators, + require_torchdynamo, + require_wandb, + slow, + torch_device, +) +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR, HPSearchBackend, get_last_checkpoint +from transformers.training_args import OptimizerNames +from transformers.utils import ( + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + is_apex_available, + is_bitsandbytes_available, + is_safetensors_available, + is_torchdistx_available, +) +from transformers.utils.hp_naming import TrialShortNamer + + +if is_torch_available(): + import torch + from torch import nn + from torch.utils.data import IterableDataset + + import transformers.optimization + from transformers import ( + AutoModelForSequenceClassification, + EarlyStoppingCallback, + GlueDataset, + GlueDataTrainingArguments, + GPT2Config, + GPT2LMHeadModel, + LineByLineTextDataset, + PreTrainedModel, + Trainer, + TrainerState, + ) + from transformers.modeling_utils import unwrap_model + + if is_safetensors_available(): + import safetensors.torch + + +PATH_SAMPLE_TEXT = f"{get_tests_dir()}/fixtures/sample_text.txt" + + +class RegressionDataset: + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + np.random.seed(seed) + self.label_names = ["labels"] if label_names is None else label_names + self.length = length + self.x = np.random.normal(size=(length,)).astype(np.float32) + self.ys = [a * self.x + b + np.random.normal(scale=0.1, size=(length,)) for _ in self.label_names] + self.ys = [y.astype(np.float32) for y in self.ys] + + def __len__(self): + return self.length + + def __getitem__(self, i): + result = {name: y[i] for name, y in zip(self.label_names, self.ys)} + result["input_x"] = self.x[i] + return result + + +@dataclasses.dataclass +class RegressionTrainingArguments(TrainingArguments): + a: float = 0.0 + b: float = 0.0 + keep_report_to: bool = False + + def __post_init__(self): + super().__post_init__() + # save resources not dealing with reporting unless specified (also avoids the warning when it's not set) + # can be explicitly disabled via `keep_report_to` + if not self.keep_report_to: + self.report_to = [] + + +class RepeatDataset: + def __init__(self, x, length=64): + self.x = x + self.length = length + + def __len__(self): + return self.length + + def __getitem__(self, i): + return {"input_ids": self.x, "labels": self.x} + + +class DynamicShapesDataset: + def __init__(self, length=64, seed=42, batch_size=8): + self.length = length + np.random.seed(seed) + sizes = np.random.randint(1, 20, (length // batch_size,)) + # For easy batching, we make every batch_size consecutive samples the same size. + self.xs = [np.random.normal(size=(s,)) for s in sizes.repeat(batch_size)] + self.ys = [np.random.normal(size=(s,)) for s in sizes.repeat(batch_size)] + + def __len__(self): + return self.length + + def __getitem__(self, i): + return {"input_x": self.xs[i], "labels": self.ys[i]} + + +class AlmostAccuracy: + def __init__(self, thresh=0.25): + self.thresh = thresh + + def __call__(self, eval_pred): + predictions, labels = eval_pred + true = np.abs(predictions - labels) <= self.thresh + return {"accuracy": true.astype(np.float32).mean().item()} + + +class RegressionModelConfig(PretrainedConfig): + def __init__(self, a=0, b=0, double_output=False, random_torch=True, **kwargs): + super().__init__(**kwargs) + self.a = a + self.b = b + self.double_output = double_output + self.random_torch = random_torch + self.hidden_size = 1 + + +if is_torch_available(): + + class SampleIterableDataset(IterableDataset): + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + self.dataset = RegressionDataset(a=a, b=b, length=length, seed=seed, label_names=label_names) + + def __iter__(self): + for i in range(len(self.dataset)): + yield self.dataset[i] + + class FiniteIterableDataset(SampleIterableDataset): + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + super().__init__(a, b, length, seed, label_names) + self.current_sample = 0 + + def __iter__(self): + while self.current_sample < len(self.dataset): + yield self.dataset[self.current_sample] + self.current_sample += 1 + + class MultiLoader: + def __init__(self, loaders): + self.loaders = loaders + + def __len__(self): + return sum(len(loader) for loader in self.loaders) + + def __iter__(self): + for loader in self.loaders: + yield from loader + + class CustomDataloaderTrainer(Trainer): + def get_train_dataloader(self): + dataloaders = [super().get_train_dataloader(), super().get_train_dataloader()] + return MultiLoader(dataloaders) + + def get_eval_dataloader(self, eval_dataset): + dataloaders = [super().get_eval_dataloader(eval_dataset), super().get_eval_dataloader(eval_dataset)] + return MultiLoader(dataloaders) + + class RegressionModel(nn.Module): + def __init__(self, a=0, b=0, double_output=False): + super().__init__() + self.a = nn.Parameter(torch.tensor(a).float()) + self.b = nn.Parameter(torch.tensor(b).float()) + self.double_output = double_output + self.config = None + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + if labels is None: + return (y, y) if self.double_output else (y,) + loss = nn.functional.mse_loss(y, labels) + return (loss, y, y) if self.double_output else (loss, y) + + class RegressionDictModel(nn.Module): + def __init__(self, a=0, b=0): + super().__init__() + self.a = nn.Parameter(torch.tensor(a).float()) + self.b = nn.Parameter(torch.tensor(b).float()) + self.config = None + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + result = {"output": y} + if labels is not None: + result["loss"] = nn.functional.mse_loss(y, labels) + return result + + class RegressionPreTrainedModel(PreTrainedModel): + config_class = RegressionModelConfig + base_model_prefix = "regression" + + def __init__(self, config): + super().__init__(config) + self.a = nn.Parameter(torch.tensor(config.a).float()) + self.b = nn.Parameter(torch.tensor(config.b).float()) + self.double_output = config.double_output + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + if labels is None: + return (y, y) if self.double_output else (y,) + loss = nn.functional.mse_loss(y, labels) + return (loss, y, y) if self.double_output else (loss, y) + + class RegressionPreTrainedModelWithGradientCheckpointing(PreTrainedModel): + config_class = RegressionModelConfig + base_model_prefix = "regression" + supports_gradient_checkpointing = True + + def __init__(self, config): + super().__init__(config) + self.layers = nn.ModuleList([nn.Linear(config.hidden_size, config.hidden_size) for _ in range(4)]) + self.head = nn.Linear(config.hidden_size, 1) + self.gradient_checkpointing = False + self.double_output = config.double_output + + def forward(self, input_x, labels=None, **kwargs): + y = input_x.unsqueeze(0) + + for layer in self.layers: + if self.training and self.gradient_checkpointing: + outputs = self._gradient_checkpointing_func(layer.__call__, y) + else: + outputs = layer(y) + + y = outputs * 3 + + logits = self.head(y) + + if labels is None: + return (logits, logits) if self.double_output else (logits,) + + loss = nn.functional.mse_loss(logits, labels) + + return (loss, y, y) if self.double_output else (loss, y) + + class RegressionRandomPreTrainedModel(PreTrainedModel): + config_class = RegressionModelConfig + base_model_prefix = "regression" + + def __init__(self, config): + super().__init__(config) + self.a = nn.Parameter(torch.tensor(config.a).float()) + self.b = nn.Parameter(torch.tensor(config.b).float()) + self.random_torch = config.random_torch + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + if self.random_torch: + torch_rand = torch.randn(1).squeeze() + np_rand = np.random.rand() + rand_rand = random.random() + + if self.random_torch: + y += 0.05 * torch_rand + y += 0.05 * torch.tensor(np_rand + rand_rand) + + if labels is None: + return (y,) + loss = nn.functional.mse_loss(y, labels) + return (loss, y) + + class TstLayer(nn.Module): + def __init__(self, hidden_size): + super().__init__() + self.linear1 = nn.Linear(hidden_size, hidden_size) + self.ln1 = nn.LayerNorm(hidden_size) + self.linear2 = nn.Linear(hidden_size, hidden_size) + self.ln2 = nn.LayerNorm(hidden_size) + self.bias = nn.Parameter(torch.zeros(hidden_size)) + + def forward(self, x): + h = self.ln1(nn.functional.relu(self.linear1(x))) + h = nn.functional.relu(self.linear2(x)) + return self.ln2(x + h + self.bias) + + def get_regression_trainer( + a=0, b=0, double_output=False, train_len=64, eval_len=64, pretrained=True, keep_report_to=False, **kwargs + ): + label_names = kwargs.get("label_names", None) + gradient_checkpointing = kwargs.get("gradient_checkpointing", False) + train_dataset = RegressionDataset(length=train_len, label_names=label_names) + eval_dataset = RegressionDataset(length=eval_len, label_names=label_names) + + model_init = kwargs.pop("model_init", None) + if model_init is not None: + model = None + else: + if pretrained: + config = RegressionModelConfig(a=a, b=b, double_output=double_output) + # We infer the correct model class if one uses gradient_checkpointing or not + target_cls = ( + RegressionPreTrainedModel + if not gradient_checkpointing + else RegressionPreTrainedModelWithGradientCheckpointing + ) + model = target_cls(config) + else: + model = RegressionModel(a=a, b=b, double_output=double_output) + + compute_metrics = kwargs.pop("compute_metrics", None) + data_collator = kwargs.pop("data_collator", None) + optimizers = kwargs.pop("optimizers", (None, None)) + output_dir = kwargs.pop("output_dir", "./regression") + preprocess_logits_for_metrics = kwargs.pop("preprocess_logits_for_metrics", None) + + args = RegressionTrainingArguments(output_dir, a=a, b=b, keep_report_to=keep_report_to, **kwargs) + return Trainer( + model, + args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + compute_metrics=compute_metrics, + optimizers=optimizers, + model_init=model_init, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + +class TrainerIntegrationCommon: + def check_saved_checkpoints(self, output_dir, freq, total, is_pretrained=True, safe_weights=True): + weights_file = WEIGHTS_NAME if not safe_weights else SAFE_WEIGHTS_NAME + file_list = [weights_file, "training_args.bin", "optimizer.pt", "scheduler.pt", "trainer_state.json"] + if is_pretrained: + file_list.append("config.json") + for step in range(freq, total, freq): + checkpoint = os.path.join(output_dir, f"checkpoint-{step}") + self.assertTrue(os.path.isdir(checkpoint)) + for filename in file_list: + self.assertTrue(os.path.isfile(os.path.join(checkpoint, filename))) + + def check_best_model_has_been_loaded( + self, output_dir, freq, total, trainer, metric, greater_is_better=False, is_pretrained=True, safe_weights=True + ): + checkpoint = os.path.join(output_dir, f"checkpoint-{(total // freq) * freq}") + log_history = TrainerState.load_from_json(os.path.join(checkpoint, "trainer_state.json")).log_history + + values = [d[metric] for d in log_history] + best_value = max(values) if greater_is_better else min(values) + best_checkpoint = (values.index(best_value) + 1) * freq + checkpoint = os.path.join(output_dir, f"checkpoint-{best_checkpoint}") + if is_pretrained: + best_model = RegressionPreTrainedModel.from_pretrained(checkpoint) + best_model.to(trainer.args.device) + else: + best_model = RegressionModel() + if not safe_weights: + state_dict = torch.load(os.path.join(checkpoint, WEIGHTS_NAME)) + else: + state_dict = safetensors.torch.load_file(os.path.join(checkpoint, SAFE_WEIGHTS_NAME)) + best_model.load_state_dict(state_dict) + best_model.to(trainer.args.device) + self.assertTrue(torch.allclose(best_model.a, trainer.model.a)) + self.assertTrue(torch.allclose(best_model.b, trainer.model.b)) + + metrics = trainer.evaluate() + self.assertEqual(metrics[metric], best_value) + + def check_trainer_state_are_the_same(self, trainer_state, trainer_state1): + # We'll pop things so operate on copies. + state = trainer_state.copy() + state1 = trainer_state1.copy() + # Log history main contain different logs for the time metrics (after resuming a training). + log_history = state.pop("log_history", None) + log_history1 = state1.pop("log_history", None) + self.assertEqual(state, state1) + skip_log_keys = ["train_runtime", "train_samples_per_second", "train_steps_per_second", "train_loss"] + for log, log1 in zip(log_history, log_history1): + for key in skip_log_keys: + _ = log.pop(key, None) + _ = log1.pop(key, None) + self.assertEqual(log, log1) + + def convert_to_sharded_checkpoint(self, folder, save_safe=True, load_safe=True): + # Converts a checkpoint of a regression model to a sharded checkpoint. + if load_safe: + loader = safetensors.torch.load_file + weights_file = os.path.join(folder, SAFE_WEIGHTS_NAME) + else: + loader = torch.load + weights_file = os.path.join(folder, WEIGHTS_NAME) + + if save_safe: + extension = "safetensors" + saver = safetensors.torch.save_file + index_file = os.path.join(folder, SAFE_WEIGHTS_INDEX_NAME) + shard_name = SAFE_WEIGHTS_NAME + else: + extension = "bin" + saver = torch.save + index_file = os.path.join(folder, WEIGHTS_INDEX_NAME) + shard_name = WEIGHTS_NAME + + state_dict = loader(weights_file) + + os.remove(weights_file) + keys = list(state_dict.keys()) + + shard_files = [ + shard_name.replace(f".{extension}", f"-{idx+1:05d}-of-{len(keys):05d}.{extension}") + for idx in range(len(keys)) + ] + index = {"metadata": {}, "weight_map": {key: shard_files[i] for i, key in enumerate(keys)}} + + with open(index_file, "w", encoding="utf-8") as f: + content = json.dumps(index, indent=2, sort_keys=True) + "\n" + f.write(content) + + for param_name, shard_file in zip(keys, shard_files): + saver({param_name: state_dict[param_name]}, os.path.join(folder, shard_file)) + + +@require_torch +@require_sentencepiece +@require_tokenizers +class TrainerIntegrationPrerunTest(TestCasePlus, TrainerIntegrationCommon): + """ + Only tests that want to tap into the auto-pre-run 2 trainings: + - self.default_trained_model + - self.alternate_trained_model + directly, or via check_trained_model + """ + + def setUp(self): + super().setUp() + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + trainer = get_regression_trainer(learning_rate=0.1) + trainer.train() + self.default_trained_model = (trainer.model.a, trainer.model.b) + + trainer = get_regression_trainer(learning_rate=0.1, seed=314) + trainer.train() + self.alternate_trained_model = (trainer.model.a, trainer.model.b) + + def check_trained_model(self, model, alternate_seed=False): + # Checks a training seeded with learning_rate = 0.1 + (a, b) = self.alternate_trained_model if alternate_seed else self.default_trained_model + self.assertTrue(torch.allclose(model.a, a)) + self.assertTrue(torch.allclose(model.b, b)) + + def test_reproducible_training(self): + # Checks that training worked, model trained and seed made a reproducible training. + trainer = get_regression_trainer(learning_rate=0.1) + trainer.train() + self.check_trained_model(trainer.model) + + # Checks that a different seed gets different (reproducible) results. + trainer = get_regression_trainer(learning_rate=0.1, seed=314) + trainer.train() + self.check_trained_model(trainer.model, alternate_seed=True) + + def test_trainer_with_datasets(self): + import datasets + + np.random.seed(42) + x = np.random.normal(size=(64,)).astype(np.float32) + y = 2.0 * x + 3.0 + np.random.normal(scale=0.1, size=(64,)) + train_dataset = datasets.Dataset.from_dict({"input_x": x, "label": y}) + + # Base training. Should have the same results as test_reproducible_training + model = RegressionModel() + args = TrainingArguments("./regression", learning_rate=0.1) + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.train() + self.check_trained_model(trainer.model) + + # Can return tensors. + train_dataset.set_format(type="torch", dtype=torch.float32) + model = RegressionModel() + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.train() + self.check_trained_model(trainer.model) + + # Adding one column not used by the model should have no impact + z = np.random.normal(size=(64,)).astype(np.float32) + train_dataset = datasets.Dataset.from_dict({"input_x": x, "label": y, "extra": z}) + model = RegressionModel() + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.train() + self.check_trained_model(trainer.model) + + def test_model_init(self): + train_dataset = RegressionDataset() + args = TrainingArguments("./regression", learning_rate=0.1) + trainer = Trainer(args=args, train_dataset=train_dataset, model_init=lambda: RegressionModel()) + trainer.train() + self.check_trained_model(trainer.model) + + # Re-training should restart from scratch, thus lead the same results. + trainer.train() + self.check_trained_model(trainer.model) + + # Re-training should restart from scratch, thus lead the same results and new seed should be used. + trainer.args.seed = 314 + trainer.train() + self.check_trained_model(trainer.model, alternate_seed=True) + + def test_gradient_accumulation(self): + # Training with half the batch size but accumulation steps as 2 should give the same results. + trainer = get_regression_trainer( + gradient_accumulation_steps=2, per_device_train_batch_size=4, learning_rate=0.1 + ) + trainer.train() + self.check_trained_model(trainer.model) + + def test_gradient_checkpointing(self): + trainer = get_regression_trainer( + per_device_train_batch_size=1, + learning_rate=0.1, + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"use_reentrant": False}, + ) + previous_params = {k: v.detach().clone() for k, v in trainer.model.named_parameters()} + + trainer.train() + + # Check if model weights have been updated + for k, v in trainer.model.named_parameters(): + self.assertFalse( + torch.allclose(previous_params[k], v, rtol=1e-4, atol=1e-4), + f"Model weights for {k} have not been updated", + ) + + def test_training_loss(self): + n_gpus = max(1, backend_device_count(torch_device)) + + # With even logs + trainer = get_regression_trainer(logging_steps=64 / (8 * n_gpus)) + trainer.train() + log_history = trainer.state.log_history + + losses = [log["loss"] for log in log_history if "loss" in log] + train_loss = log_history[-1]["train_loss"] + self.assertAlmostEqual(sum(losses) / len(losses), train_loss, places=4) + + # With uneven logs + trainer = get_regression_trainer(logging_steps=5) + trainer.train() + log_history = trainer.state.log_history + + # Training loss should be the same as before + new_train_loss = log_history[-1]["train_loss"] + self.assertAlmostEqual(train_loss, new_train_loss, places=4) + + def test_custom_optimizer(self): + train_dataset = RegressionDataset() + args = TrainingArguments("./regression") + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=1.0) + lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda x: 1.0) + trainer = Trainer(model, args, train_dataset=train_dataset, optimizers=(optimizer, lr_scheduler)) + trainer.train() + + (a, b) = self.default_trained_model + self.assertFalse(torch.allclose(trainer.model.a, a)) + self.assertFalse(torch.allclose(trainer.model.b, b)) + self.assertEqual(trainer.optimizer.state_dict()["param_groups"][0]["lr"], 1.0) + + def test_lr_scheduler_kwargs(self): + # test scheduler kwargs passed via TrainingArguments + train_dataset = RegressionDataset() + model = RegressionModel() + num_steps, num_warmup_steps = 10, 2 + extra_kwargs = {"power": 5.0, "lr_end": 1e-5} # Non-default arguments + args = TrainingArguments( + "./regression", + lr_scheduler_type="polynomial", + lr_scheduler_kwargs=extra_kwargs, + learning_rate=0.2, + warmup_steps=num_warmup_steps, + ) + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.create_optimizer_and_scheduler(num_training_steps=num_steps) + + # Checking that the scheduler was created + self.assertIsNotNone(trainer.lr_scheduler) + + # Checking that the correct args were passed + sched1 = trainer.lr_scheduler + sched2 = get_polynomial_decay_schedule_with_warmup( + trainer.optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_steps, **extra_kwargs + ) + self.assertEqual(sched1.lr_lambdas[0].args, sched2.lr_lambdas[0].args) + self.assertEqual(sched1.lr_lambdas[0].keywords, sched2.lr_lambdas[0].keywords) + + def test_reduce_lr_on_plateau_args(self): + # test passed arguments for a custom ReduceLROnPlateau scheduler + train_dataset = RegressionDataset(length=64) + eval_dataset = RegressionDataset(length=64) + args = TrainingArguments( + "./regression", + evaluation_strategy="epoch", + metric_for_best_model="eval_loss", + ) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=1.0) + lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.2, patience=5, cooldown=2) + trainer = Trainer( + model, args, train_dataset=train_dataset, eval_dataset=eval_dataset, optimizers=(optimizer, lr_scheduler) + ) + trainer.train() + + self.assertIsInstance(trainer.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau) + self.assertEqual(trainer.lr_scheduler.factor, 0.2) + self.assertEqual(trainer.lr_scheduler.patience, 5) + self.assertEqual(trainer.lr_scheduler.cooldown, 2) + + def test_reduce_lr_on_plateau(self): + # test the ReduceLROnPlateau scheduler + + class TrainerWithLRLogs(Trainer): + def log(self, logs): + # the LR is computed after metrics and does not exist for the first epoch + if hasattr(self.lr_scheduler, "_last_lr"): + logs["learning_rate"] = self.lr_scheduler._last_lr[0] + super().log(logs) + + train_dataset = RegressionDataset(length=64) + eval_dataset = RegressionDataset(length=64) + + args = TrainingArguments( + "./regression", + lr_scheduler_type="reduce_lr_on_plateau", + evaluation_strategy="epoch", + metric_for_best_model="eval_loss", + num_train_epochs=10, + learning_rate=0.2, + ) + model = RegressionModel() + trainer = TrainerWithLRLogs(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + trainer.train() + + self.assertIsInstance(trainer.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau) + patience = trainer.lr_scheduler.patience + + logs = trainer.state.log_history[1:] + best_loss = logs[0]["eval_loss"] + bad_epochs = 0 + for i, log in enumerate(logs[:-1]): # Compare learning rate to next epoch's + loss = log["eval_loss"] + just_decreased = False + if loss > best_loss: + bad_epochs += 1 + if bad_epochs > patience: + self.assertLess(logs[i + 1]["learning_rate"], log["learning_rate"]) + just_decreased = True + bad_epochs = 0 + else: + best_loss = loss + bad_epochs = 0 + if not just_decreased: + self.assertEqual(logs[i + 1]["learning_rate"], log["learning_rate"]) + + def test_adafactor_lr_none(self): + # test the special case where lr=None, since Trainer can't not have lr_scheduler + + from transformers.optimization import Adafactor, AdafactorSchedule + + train_dataset = RegressionDataset() + args = TrainingArguments("./regression") + model = RegressionModel() + optimizer = Adafactor(model.parameters(), scale_parameter=True, relative_step=True, warmup_init=True, lr=None) + lr_scheduler = AdafactorSchedule(optimizer) + trainer = Trainer(model, args, train_dataset=train_dataset, optimizers=(optimizer, lr_scheduler)) + trainer.train() + + (a, b) = self.default_trained_model + self.assertFalse(torch.allclose(trainer.model.a, a)) + self.assertFalse(torch.allclose(trainer.model.b, b)) + self.assertGreater(trainer.optimizer.state_dict()["param_groups"][0]["lr"], 0) + + @require_torch_accelerator + @require_torch_bf16 + def test_mixed_bf16(self): + # very basic test + trainer = get_regression_trainer(learning_rate=0.1, bf16=True) + trainer.train() + self.check_trained_model(trainer.model) + + # --bf16 --half_precision_backend apex can't be used together + with self.assertRaises(ValueError): + trainer = get_regression_trainer(learning_rate=0.1, bf16=True, half_precision_backend="apex") + + # will add more specific tests once there are some bugs to fix + + @require_torch_gpu + @require_torch_tf32 + def test_tf32(self): + # very basic test + trainer = get_regression_trainer(learning_rate=0.1, tf32=True) + trainer.train() + self.check_trained_model(trainer.model) + + +@require_torch +@require_sentencepiece +@require_tokenizers +class TrainerIntegrationTest(TestCasePlus, TrainerIntegrationCommon): + def setUp(self): + super().setUp() + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_trainer_works_with_dict(self): + # Edge case because Apex with mode O2 will change our models to return dicts. This test checks it doesn't break + # anything. + train_dataset = RegressionDataset() + eval_dataset = RegressionDataset() + model = RegressionDictModel() + args = TrainingArguments("./regression") + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + trainer.train() + _ = trainer.evaluate() + _ = trainer.predict(eval_dataset) + + def test_evaluation_with_keys_to_drop(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + eval_dataset = RepeatDataset(x) + args = TrainingArguments("./test") + trainer = Trainer(tiny_gpt2, args, eval_dataset=eval_dataset) + # By default the past_key_values are removed + result = trainer.predict(eval_dataset) + self.assertTrue(isinstance(result.predictions, np.ndarray)) + # We can still get them by setting ignore_keys to [] + result = trainer.predict(eval_dataset, ignore_keys=[]) + self.assertTrue(isinstance(result.predictions, tuple)) + self.assertEqual(len(result.predictions), 2) + + def test_training_arguments_are_left_untouched(self): + trainer = get_regression_trainer() + trainer.train() + args = TrainingArguments("./regression", report_to=[]) + dict1, dict2 = args.to_dict(), trainer.args.to_dict() + for key in dict1.keys(): + # Logging dir can be slightly different as they default to something with the time. + if key != "logging_dir": + self.assertEqual(dict1[key], dict2[key]) + + def test_number_of_steps_in_training(self): + # Regular training has n_epochs * len(train_dl) steps + trainer = get_regression_trainer(learning_rate=0.1) + train_output = trainer.train() + self.assertEqual(train_output.global_step, self.n_epochs * 64 / self.batch_size) + + # Check passing num_train_epochs works (and a float version too): + trainer = get_regression_trainer(learning_rate=0.1, num_train_epochs=1.5) + train_output = trainer.train() + self.assertEqual(train_output.global_step, int(1.5 * 64 / self.batch_size)) + + # If we pass a max_steps, num_train_epochs is ignored + trainer = get_regression_trainer(learning_rate=0.1, max_steps=10) + train_output = trainer.train() + self.assertEqual(train_output.global_step, 10) + + @require_torch_bf16 + @require_intel_extension_for_pytorch + def test_number_of_steps_in_training_with_ipex(self): + for mix_bf16 in [True, False]: + # Regular training has n_epochs * len(train_dl) steps + trainer = get_regression_trainer(learning_rate=0.1, use_ipex=True, bf16=mix_bf16, use_cpu=True) + train_output = trainer.train() + self.assertEqual(train_output.global_step, self.n_epochs * 64 / trainer.args.train_batch_size) + + # Check passing num_train_epochs works (and a float version too): + trainer = get_regression_trainer( + learning_rate=0.1, num_train_epochs=1.5, use_ipex=True, bf16=mix_bf16, use_cpu=True + ) + train_output = trainer.train() + self.assertEqual(train_output.global_step, int(1.5 * 64 / trainer.args.train_batch_size)) + + # If we pass a max_steps, num_train_epochs is ignored + trainer = get_regression_trainer( + learning_rate=0.1, max_steps=10, use_ipex=True, bf16=mix_bf16, use_cpu=True + ) + train_output = trainer.train() + self.assertEqual(train_output.global_step, 10) + + def test_neftune(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + "./test", learning_rate=1e-9, logging_steps=5, logging_nan_inf_filter=False, neftune_noise_alpha=0.4 + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + trainer.model = trainer._activate_neftune(trainer.model) + + dummy_input = torch.LongTensor([[1, 0, 1]]).to(torch_device) + + emb1 = trainer.model.get_input_embeddings()(dummy_input) + emb2 = trainer.model.get_input_embeddings()(dummy_input) + + self.assertFalse(torch.allclose(emb1, emb2), "Neftune noise is not applied!") + + # redefine the model + tiny_gpt2 = GPT2LMHeadModel(config) + # Trainer without inf/nan filter + args = TrainingArguments( + "./test", learning_rate=1e-9, logging_steps=5, logging_nan_inf_filter=False, neftune_noise_alpha=0.4 + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + # Check that it trains without errors + trainer.train() + + # Make sure forward pass works fine + _ = trainer.model(dummy_input) + self.assertTrue(len(trainer.model.get_input_embeddings()._forward_hooks) == 0) + + trainer.model.eval() + + # Check that we get identical embeddings just in case + emb1 = trainer.model.get_input_embeddings()(dummy_input) + emb2 = trainer.model.get_input_embeddings()(dummy_input) + + self.assertTrue(torch.allclose(emb1, emb2), "Neftune noise is still applied!") + + def test_logging_inf_nan_filter(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments("./test", learning_rate=1e9, logging_steps=5, logging_nan_inf_filter=False) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + trainer.train() + log_history_no_filter = trainer.state.log_history + + # Trainer with inf/nan filter + args = TrainingArguments("./test", learning_rate=1e9, logging_steps=5, logging_nan_inf_filter=True) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + trainer.train() + log_history_filter = trainer.state.log_history + + def is_any_loss_nan_or_inf(log_history): + losses = [l["loss"] for l in log_history[:-1]] + return any(math.isnan(x) for x in losses) or any(math.isinf(x) for x in losses) + + self.assertTrue(is_any_loss_nan_or_inf(log_history_no_filter)) + self.assertFalse(is_any_loss_nan_or_inf(log_history_filter)) + + def test_train_and_eval_dataloaders(self): + n_gpu = max(1, backend_device_count(torch_device)) + trainer = get_regression_trainer(learning_rate=0.1, per_device_train_batch_size=16) + self.assertEqual(trainer.get_train_dataloader().total_batch_size, 16 * n_gpu) + trainer = get_regression_trainer(learning_rate=0.1, per_device_eval_batch_size=16) + self.assertEqual(trainer.get_eval_dataloader().total_batch_size, 16 * n_gpu) + + # Check drop_last works + trainer = get_regression_trainer( + train_len=66, eval_len=74, learning_rate=0.1, per_device_train_batch_size=16, per_device_eval_batch_size=32 + ) + self.assertEqual(len(trainer.get_train_dataloader()), 66 // (16 * n_gpu) + 1) + self.assertEqual(len(trainer.get_eval_dataloader()), 74 // (32 * n_gpu) + 1) + + trainer = get_regression_trainer( + train_len=66, + eval_len=74, + learning_rate=0.1, + per_device_train_batch_size=16, + per_device_eval_batch_size=32, + dataloader_drop_last=True, + ) + self.assertEqual(len(trainer.get_train_dataloader()), 66 // (16 * n_gpu)) + self.assertEqual(len(trainer.get_eval_dataloader()), 74 // (32 * n_gpu)) + + # Check passing a new dataset for evaluation works + new_eval_dataset = RegressionDataset(length=128) + self.assertEqual(len(trainer.get_eval_dataloader(new_eval_dataset)), 128 // (32 * n_gpu)) + + # tests that we do not require dataloader to have a .dataset attribute + def test_dataloader_without_dataset(self): + train_dataset = RegressionDataset(length=128) + trainer = CustomDataloaderTrainer( + model=RegressionModel(), train_dataset=train_dataset, eval_dataset=train_dataset + ) + trainer.train() + trainer.evaluate() + + @require_torch_multi_accelerator + def test_data_is_not_parallelized_when_model_is_parallel(self): + model = RegressionModel() + # Make the Trainer believe it's a parallelized model + model.is_parallelizable = True + model.model_parallel = True + args = TrainingArguments("./regression", per_device_train_batch_size=16, per_device_eval_batch_size=16) + trainer = Trainer(model, args, train_dataset=RegressionDataset(), eval_dataset=RegressionDataset()) + # Check the Trainer was fooled + self.assertTrue(trainer.is_model_parallel) + self.assertEqual(trainer.args.n_gpu, 1) + + # The batch size of the training and evaluation dataloaders should be 16, not 16 * n_gpu + self.assertEqual(trainer.get_train_dataloader().total_batch_size, 16) + self.assertEqual(len(trainer.get_train_dataloader()), 64 // 16) + self.assertEqual(trainer.get_eval_dataloader().total_batch_size, 16) + self.assertEqual(len(trainer.get_eval_dataloader()), 64 // 16) + + def test_evaluate(self): + trainer = get_regression_trainer(a=1.5, b=2.5, compute_metrics=AlmostAccuracy()) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer(a=1.5, b=2.5, eval_len=66, compute_metrics=AlmostAccuracy()) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With logits preprocess + trainer = get_regression_trainer( + a=1.5, + b=2.5, + compute_metrics=AlmostAccuracy(), + preprocess_logits_for_metrics=lambda logits, labels: logits + 1, + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred + 1, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + def test_evaluate_with_jit(self): + trainer = get_regression_trainer(a=1.5, b=2.5, compute_metrics=AlmostAccuracy(), jit_mode_eval=True) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer( + a=1.5, b=2.5, eval_len=66, compute_metrics=AlmostAccuracy(), jit_mode_eval=True + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With logits preprocess + trainer = get_regression_trainer( + a=1.5, + b=2.5, + compute_metrics=AlmostAccuracy(), + preprocess_logits_for_metrics=lambda logits, labels: logits + 1, + jit_mode_eval=True, + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred + 1, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + @require_torch_bf16 + @require_intel_extension_for_pytorch + def test_evaluate_with_ipex(self): + for mix_bf16 in [True, False]: + trainer = get_regression_trainer( + a=1.5, b=2.5, use_ipex=True, compute_metrics=AlmostAccuracy(), bf16=mix_bf16, use_cpu=True + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer( + a=1.5, + b=2.5, + use_ipex=True, + eval_len=66, + compute_metrics=AlmostAccuracy(), + bf16=mix_bf16, + use_cpu=True, + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With logits preprocess + trainer = get_regression_trainer( + a=1.5, + b=2.5, + use_ipex=True, + compute_metrics=AlmostAccuracy(), + preprocess_logits_for_metrics=lambda logits, labels: logits + 1, + bf16=mix_bf16, + use_cpu=True, + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred + 1, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + def test_predict(self): + trainer = get_regression_trainer(a=1.5, b=2.5) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer(a=1.5, b=2.5, eval_len=66) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With more than one output of the model + trainer = get_regression_trainer(a=1.5, b=2.5, double_output=True) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + + # With more than one output/label of the model + trainer = get_regression_trainer(a=1.5, b=2.5, double_output=True, label_names=["labels", "labels_2"]) + outputs = trainer.predict(trainer.eval_dataset) + preds = outputs.predictions + labels = outputs.label_ids + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + self.assertTrue(np.array_equal(labels[0], trainer.eval_dataset.ys[0])) + self.assertTrue(np.array_equal(labels[1], trainer.eval_dataset.ys[1])) + + def test_predict_with_jit(self): + trainer = get_regression_trainer(a=1.5, b=2.5, jit_mode_eval=True) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer(a=1.5, b=2.5, eval_len=66, jit_mode_eval=True) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With more than one output of the model + trainer = get_regression_trainer(a=1.5, b=2.5, double_output=True, jit_mode_eval=True) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + + # With more than one output/label of the model + trainer = get_regression_trainer( + a=1.5, b=2.5, double_output=True, label_names=["labels", "labels_2"], jit_mode_eval=True + ) + outputs = trainer.predict(trainer.eval_dataset) + preds = outputs.predictions + labels = outputs.label_ids + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + self.assertTrue(np.array_equal(labels[0], trainer.eval_dataset.ys[0])) + self.assertTrue(np.array_equal(labels[1], trainer.eval_dataset.ys[1])) + + @require_torch_bf16 + @require_intel_extension_for_pytorch + def test_predict_with_ipex(self): + for mix_bf16 in [True, False]: + trainer = get_regression_trainer(a=1.5, b=2.5, use_ipex=True, bf16=mix_bf16, use_cpu=True) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer(a=1.5, b=2.5, eval_len=66, use_ipex=True, bf16=mix_bf16, use_cpu=True) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With more than one output of the model + trainer = get_regression_trainer( + a=1.5, b=2.5, double_output=True, use_ipex=True, bf16=mix_bf16, use_cpu=True + ) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + + # With more than one output/label of the model + trainer = get_regression_trainer( + a=1.5, + b=2.5, + double_output=True, + label_names=["labels", "labels_2"], + use_ipex=True, + bf16=mix_bf16, + use_cpu=True, + ) + outputs = trainer.predict(trainer.eval_dataset) + preds = outputs.predictions + labels = outputs.label_ids + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + self.assertTrue(np.array_equal(labels[0], trainer.eval_dataset.ys[0])) + self.assertTrue(np.array_equal(labels[1], trainer.eval_dataset.ys[1])) + + def test_dynamic_shapes(self): + eval_dataset = DynamicShapesDataset(batch_size=self.batch_size) + model = RegressionModel(a=2, b=1) + args = TrainingArguments("./regression") + trainer = Trainer(model, args, eval_dataset=eval_dataset) + + # Check evaluation can run to completion + _ = trainer.evaluate() + + # Check predictions + preds = trainer.predict(eval_dataset) + for expected, seen in zip(eval_dataset.ys, preds.label_ids): + self.assertTrue(np.array_equal(expected, seen[: expected.shape[0]])) + self.assertTrue(np.all(seen[expected.shape[0] :] == -100)) + + for expected, seen in zip(eval_dataset.xs, preds.predictions): + self.assertTrue(np.array_equal(2 * expected + 1, seen[: expected.shape[0]])) + self.assertTrue(np.all(seen[expected.shape[0] :] == -100)) + + # Same tests with eval accumulation + args = TrainingArguments("./regression", eval_accumulation_steps=2) + trainer = Trainer(model, args, eval_dataset=eval_dataset) + + # Check evaluation can run to completion + _ = trainer.evaluate() + + # Check predictions + preds = trainer.predict(eval_dataset) + for expected, seen in zip(eval_dataset.ys, preds.label_ids): + self.assertTrue(np.array_equal(expected, seen[: expected.shape[0]])) + self.assertTrue(np.all(seen[expected.shape[0] :] == -100)) + + for expected, seen in zip(eval_dataset.xs, preds.predictions): + self.assertTrue(np.array_equal(2 * expected + 1, seen[: expected.shape[0]])) + self.assertTrue(np.all(seen[expected.shape[0] :] == -100)) + + def test_log_level(self): + # testing only --log_level (--log_level_replica requires multiple gpus and DDP and is tested elsewhere) + logger = logging.get_logger() + log_info_string = "Running training" + + # test with the default log_level - should be the same as before and thus we test depending on is_info + is_info = logging.get_verbosity() <= 20 + with CaptureLogger(logger) as cl: + trainer = get_regression_trainer() + trainer.train() + if is_info: + self.assertIn(log_info_string, cl.out) + else: + self.assertNotIn(log_info_string, cl.out) + + # test with low log_level - lower than info + with CaptureLogger(logger) as cl: + trainer = get_regression_trainer(log_level="debug") + trainer.train() + self.assertIn(log_info_string, cl.out) + + # test with high log_level - should be quiet + with CaptureLogger(logger) as cl: + trainer = get_regression_trainer(log_level="error") + trainer.train() + self.assertNotIn(log_info_string, cl.out) + + def test_save_checkpoints(self): + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer(output_dir=tmpdir, save_steps=5) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, int(self.n_epochs * 64 / self.batch_size)) + + # With a regular model that is not a PreTrainedModel + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer(output_dir=tmpdir, save_steps=5, pretrained=False) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, int(self.n_epochs * 64 / self.batch_size), False) + + def test_save_checkpoints_is_atomic(self): + class UnsaveableTokenizer(PreTrainedTokenizerBase): + def save_pretrained(self, *args, **kwargs): + raise OSError("simulated file write error") + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer(output_dir=tmpdir, save_steps=5) + # Attach unsaveable tokenizer to partially fail checkpointing + trainer.tokenizer = UnsaveableTokenizer() + with self.assertRaises(OSError) as _context: + trainer.train() + assert get_last_checkpoint(tmpdir) is None + + @require_safetensors + def test_safe_checkpoints(self): + for save_safetensors in [True, False]: + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer(output_dir=tmpdir, save_steps=5, save_safetensors=save_safetensors) + trainer.train() + self.check_saved_checkpoints( + tmpdir, 5, int(self.n_epochs * 64 / self.batch_size), safe_weights=save_safetensors + ) + + # With a regular model that is not a PreTrainedModel + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, save_steps=5, pretrained=False, save_safetensors=save_safetensors + ) + trainer.train() + self.check_saved_checkpoints( + tmpdir, 5, int(self.n_epochs * 64 / self.batch_size), False, safe_weights=save_safetensors + ) + + @require_torch_multi_accelerator + def test_run_seq2seq_double_train_wrap_once(self): + # test that we don't wrap the model more than once + # since wrapping primarily happens on multi-gpu setup we want multiple gpus to test for + # example DataParallel(DataParallel(model)) + + trainer = get_regression_trainer() + trainer.train() + model_wrapped_before = trainer.model_wrapped + trainer.train() + model_wrapped_after = trainer.model_wrapped + self.assertIs(model_wrapped_before, model_wrapped_after, "should be not wrapped twice") + + @require_torch_up_to_2_accelerators + def test_can_resume_training(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + with tempfile.TemporaryDirectory() as tmpdir: + kwargs = { + "output_dir": tmpdir, + "train_len": 128, + "save_steps": 5, + "learning_rate": 0.1, + "logging_steps": 5, + } + trainer = get_regression_trainer(**kwargs) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + + # Reinitialize trainer + trainer = get_regression_trainer(**kwargs) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + # Now check with a later checkpoint that it also works when we span over one epoch + checkpoint = os.path.join(tmpdir, "checkpoint-15") + + # Reinitialize trainer and load model + trainer = get_regression_trainer(**kwargs) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + # With a regular model that is not a PreTrainedModel + with tempfile.TemporaryDirectory() as tmpdir: + kwargs = { + "output_dir": tmpdir, + "train_len": 128, + "save_steps": 5, + "learning_rate": 0.1, + "pretrained": False, + } + + trainer = get_regression_trainer(**kwargs) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + + # Reinitialize trainer and load model + trainer = get_regression_trainer(**kwargs) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + # Now check with a later checkpoint that it also works when we span over one epoch + checkpoint = os.path.join(tmpdir, "checkpoint-15") + + # Reinitialize trainer and load model + trainer = get_regression_trainer(**kwargs) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + # Now check failures + + # 1. fail to find a bogus checkpoint + trainer = get_regression_trainer() + with self.assertRaises(Exception) as context: + trainer.train(resume_from_checkpoint=f"{checkpoint}-bogus") + self.assertTrue("Can't find a valid checkpoint at" in str(context.exception)) + + # 2. fail to find any checkpoint - due a fresh output_dir + output_dir2 = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(output_dir=output_dir2) + with self.assertRaises(Exception) as context: + trainer.train(resume_from_checkpoint=True) + self.assertTrue("No valid checkpoint found in output directory" in str(context.exception)) + + def test_resume_training_with_randomness(self): + # For more than 1 GPUs, since the randomness is introduced in the model and with DataParallel (which is used + # in this test for more than 2 GPUs), the calls to the torch RNG will happen in a random order (sometimes + # GPU 0 will call first and sometimes GPU 1). + random_torch = not torch.cuda.is_available() or torch.cuda.device_count() <= 1 + + if torch.cuda.is_available(): + torch.backends.cudnn.deterministic = True + train_dataset = RegressionDataset(length=128) + eval_dataset = RegressionDataset() + + with self.subTest("Test every step"): + config = RegressionModelConfig(a=0, b=2, random_torch=random_torch) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + args = RegressionTrainingArguments(tmp_dir, save_steps=5, learning_rate=0.1) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + + model = RegressionRandomPreTrainedModel(config) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + trainer.train(resume_from_checkpoint=os.path.join(tmp_dir, "checkpoint-15")) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + + self.assertAlmostEqual(a, a1, delta=1e-5) + self.assertAlmostEqual(b, b1, delta=1e-5) + + with self.subTest("Test every epoch"): + config = RegressionModelConfig(a=0, b=2, random_torch=random_torch) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + args = RegressionTrainingArguments(tmp_dir, save_strategy="epoch", learning_rate=0.1) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + + model = RegressionRandomPreTrainedModel(config) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + + checkpoints = [d for d in os.listdir(tmp_dir) if d.startswith("checkpoint-")] + # There should be one checkpoint per epoch. + self.assertEqual(len(checkpoints), 3) + checkpoint_dir = sorted(checkpoints, key=lambda x: int(x.replace("checkpoint-", "")))[0] + + trainer.train(resume_from_checkpoint=os.path.join(tmp_dir, checkpoint_dir)) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + + self.assertAlmostEqual(a, a1, delta=1e-5) + self.assertAlmostEqual(b, b1, delta=1e-5) + + @slow + @require_accelerate + @require_torch_non_multi_accelerator + def test_auto_batch_size_finder(self): + if torch.cuda.is_available(): + torch.backends.cudnn.deterministic = True + + SRC_DIR = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "..", "examples", "pytorch", "text-classification") + ) + sys.path.append(SRC_DIR) + import run_glue + + with tempfile.TemporaryDirectory() as tmpdir: + testargs = f""" + run_glue.py + --model_name_or_path distilbert-base-uncased + --task_name mrpc + --do_train + --do_eval + --max_seq_len 128 + --per_device_train_batch_size 4096 + --learning_rate 2e-5 + --num_train_epochs 1 + --output_dir {tmpdir} + --auto_find_batch_size 0 + """.split() + with self.assertRaises(RuntimeError): + with patch.object(sys, "argv", testargs): + run_glue.main() + + testargs[-1] = "1" + with patch.object(sys, "argv", testargs): + run_glue.main() + + def test_auto_batch_size_with_resume_from_checkpoint(self): + train_dataset = RegressionDataset(length=128) + + config = RegressionModelConfig(a=0, b=2) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + + class MockCudaOOMCallback(TrainerCallback): + def on_step_end(self, args, state, control, **kwargs): + # simulate OOM on the first step + if state.train_batch_size >= 16: + raise RuntimeError("CUDA out of memory.") + + args = RegressionTrainingArguments( + tmp_dir, + do_train=True, + max_steps=2, + save_steps=1, + per_device_train_batch_size=16, + auto_find_batch_size=True, + ) + trainer = Trainer(model, args, train_dataset=train_dataset, callbacks=[MockCudaOOMCallback()]) + trainer.train() + # After `auto_find_batch_size` is ran we should now be at 8 + self.assertEqual(trainer._train_batch_size, 8) + + # We can then make a new Trainer + trainer = Trainer(model, args, train_dataset=train_dataset) + # Check we are at 16 to start + self.assertEqual(trainer._train_batch_size, 16 * max(trainer.args.n_gpu, 1)) + trainer.train(resume_from_checkpoint=True) + # We should be back to 8 again, picking up based upon the last ran Trainer + self.assertEqual(trainer._train_batch_size, 8) + + # regression for this issue: https://github.com/huggingface/transformers/issues/12970 + def test_training_with_resume_from_checkpoint_false(self): + train_dataset = RegressionDataset(length=128) + eval_dataset = RegressionDataset() + + config = RegressionModelConfig(a=0, b=2) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + args = RegressionTrainingArguments(tmp_dir, save_steps=5, learning_rate=0.1) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + + trainer.train(resume_from_checkpoint=False) + + @require_torch_up_to_2_accelerators + def test_resume_training_with_shard_checkpoint(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer(output_dir=tmpdir, train_len=128, save_steps=5, learning_rate=0.1) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + self.convert_to_sharded_checkpoint(checkpoint) + + # Reinitialize trainer + trainer = get_regression_trainer(output_dir=tmpdir, train_len=128, save_steps=5, learning_rate=0.1) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + @require_safetensors + @require_torch_up_to_2_accelerators + def test_resume_training_with_safe_checkpoint(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + for initial_safe in [False, True]: + for loaded_safe in [False, True]: + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + save_steps=5, + learning_rate=0.1, + save_safetensors=initial_safe, + ) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + self.convert_to_sharded_checkpoint(checkpoint, load_safe=initial_safe, save_safe=loaded_safe) + + # Reinitialize trainer + trainer = get_regression_trainer( + output_dir=tmpdir, train_len=128, save_steps=5, learning_rate=0.1, save_safetensors=loaded_safe + ) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + @require_torch_up_to_2_accelerators + def test_resume_training_with_gradient_accumulation(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + gradient_accumulation_steps=2, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + + # Reinitialize trainer + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + gradient_accumulation_steps=2, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + @require_torch_up_to_2_accelerators + def test_resume_training_with_frozen_params(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + trainer.model.a.requires_grad_(False) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + + # Reinitialize trainer + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + trainer.model.a.requires_grad_(False) + + trainer.train(resume_from_checkpoint=checkpoint) + + self.assertFalse(trainer.model.a.requires_grad) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + def test_load_best_model_at_end(self): + total = int(self.n_epochs * 64 / self.batch_size) + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_steps=5, + evaluation_strategy="steps", + save_steps=5, + load_best_model_at_end=True, + ) + self.assertFalse(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, total) + self.check_best_model_has_been_loaded(tmpdir, 5, total, trainer, "eval_loss") + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_steps=5, + evaluation_strategy="steps", + save_steps=5, + load_best_model_at_end=True, + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + ) + self.assertTrue(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, total) + self.check_best_model_has_been_loaded(tmpdir, 5, total, trainer, "eval_accuracy", greater_is_better=True) + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + evaluation_strategy="epoch", + save_strategy="epoch", + load_best_model_at_end=True, + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + ) + self.assertTrue(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 64 // self.batch_size, total) + self.check_best_model_has_been_loaded( + tmpdir, 64 // self.batch_size, total, trainer, "eval_accuracy", greater_is_better=True + ) + + # Test this works with a non PreTrainedModel + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + learning_rate=0.1, + eval_steps=5, + evaluation_strategy="steps", + save_steps=5, + load_best_model_at_end=True, + pretrained=False, + ) + self.assertFalse(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, total, is_pretrained=False) + self.check_best_model_has_been_loaded(tmpdir, 5, total, trainer, "eval_loss", is_pretrained=False) + + @require_safetensors + def test_load_best_model_from_safetensors(self): + total = int(self.n_epochs * 64 / self.batch_size) + for save_safetensors, pretrained in product([False, True], [False, True]): + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_steps=5, + evaluation_strategy="steps", + save_steps=5, + load_best_model_at_end=True, + save_safetensors=save_safetensors, + pretrained=pretrained, + ) + self.assertFalse(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, total, is_pretrained=pretrained, safe_weights=save_safetensors) + self.check_best_model_has_been_loaded( + tmpdir, 5, total, trainer, "eval_loss", is_pretrained=pretrained, safe_weights=save_safetensors + ) + + @slow + def test_trainer_eval_mrpc(self): + MODEL_ID = "bert-base-cased-finetuned-mrpc" + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) + model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID) + data_args = GlueDataTrainingArguments( + task_name="mrpc", data_dir=f"{get_tests_dir()}/fixtures/tests_samples/MRPC", overwrite_cache=True + ) + eval_dataset = GlueDataset(data_args, tokenizer=tokenizer, mode="dev") + + training_args = TrainingArguments(output_dir="./examples", use_cpu=True) + trainer = Trainer(model=model, args=training_args, eval_dataset=eval_dataset) + result = trainer.evaluate() + self.assertLess(result["eval_loss"], 0.2) + + @slow + def test_trainer_eval_lm(self): + MODEL_ID = "distilroberta-base" + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) + dataset = LineByLineTextDataset( + tokenizer=tokenizer, + file_path=PATH_SAMPLE_TEXT, + block_size=tokenizer.max_len_single_sentence, + ) + self.assertEqual(len(dataset), 31) + + def test_training_iterable_dataset(self): + config = RegressionModelConfig() + model = RegressionPreTrainedModel(config) + # Adding one column not used by the model should have no impact + train_dataset = SampleIterableDataset(label_names=["labels", "extra"]) + + args = RegressionTrainingArguments(output_dir="./examples", max_steps=4) + trainer = Trainer(model=model, args=args, train_dataset=train_dataset) + trainer.train() + self.assertEqual(trainer.state.global_step, 4) + + loader = trainer.get_train_dataloader() + self.assertIsInstance(loader, torch.utils.data.DataLoader) + self.assertIsInstance(loader.sampler, torch.utils.data.dataloader._InfiniteConstantSampler) + + def test_evaluation_iterable_dataset(self): + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + # Adding one column not used by the model should have no impact + eval_dataset = SampleIterableDataset(label_names=["labels", "extra"]) + + args = RegressionTrainingArguments(output_dir="./examples") + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset, compute_metrics=AlmostAccuracy()) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.dataset.x, trainer.eval_dataset.dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + eval_dataset = SampleIterableDataset(length=66) + results = trainer.evaluate(eval_dataset) + + x, y = eval_dataset.dataset.x, eval_dataset.dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + def test_predict_iterable_dataset(self): + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + + args = RegressionTrainingArguments(output_dir="./examples") + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset, compute_metrics=AlmostAccuracy()) + + preds = trainer.predict(trainer.eval_dataset).predictions + x = eval_dataset.dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With a number of elements not a round multiple of the batch size + # Adding one column not used by the model should have no impact + test_dataset = SampleIterableDataset(length=66, label_names=["labels", "extra"]) + preds = trainer.predict(test_dataset).predictions + x = test_dataset.dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + def test_num_train_epochs_in_training(self): + # len(train_dl) < gradient_accumulation_steps shouldn't give ``ZeroDivisionError`` when ``max_steps`` is given. + # It should give 1 update step for each epoch. + trainer = get_regression_trainer( + max_steps=3, train_len=64, per_device_train_batch_size=16, gradient_accumulation_steps=5 + ) + train_output = trainer.train() + self.assertEqual(train_output.global_step, 3) + + # Even ``max_steps`` is not specified, we still expect 1 update step for each epoch if + # len(train_dl) < gradient_accumulation_steps. + trainer = get_regression_trainer(train_len=64, per_device_train_batch_size=16, gradient_accumulation_steps=5) + train_output = trainer.train() + self.assertEqual(train_output.global_step, int(self.n_epochs)) + + def test_early_stopping_callback(self): + # early stopping stops training before num_training_epochs + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + num_train_epochs=20, + gradient_accumulation_steps=1, + per_device_train_batch_size=16, + load_best_model_at_end=True, + evaluation_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + compute_metrics=AlmostAccuracy(), + metric_for_best_model="accuracy", + ) + trainer.add_callback(EarlyStoppingCallback(1, 0.0001)) + train_output = trainer.train() + self.assertLess(train_output.global_step, 20 * 64 / 16) + + # Invalid inputs to trainer with early stopping callback result in assertion error + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + num_train_epochs=20, + gradient_accumulation_steps=1, + per_device_train_batch_size=16, + evaluation_strategy=IntervalStrategy.EPOCH, + compute_metrics=AlmostAccuracy(), + metric_for_best_model="accuracy", + ) + trainer.add_callback(EarlyStoppingCallback(1)) + self.assertEqual(trainer.state.global_step, 0) + try: + trainer.train() + except AssertionError: + self.assertEqual(trainer.state.global_step, 0) + + def test_flos_extraction(self): + trainer = get_regression_trainer(learning_rate=0.1) + + def assert_flos_extraction(trainer, wrapped_model_to_check): + self.assertEqual(trainer.model, unwrap_model(wrapped_model_to_check)) + self.assertGreaterEqual(getattr(unwrap_model(wrapped_model_to_check).config, "total_flos", 0), 0) + + # with plain model + assert_flos_extraction(trainer, trainer.model) + + # with enforced DataParallel + assert_flos_extraction(trainer, nn.DataParallel(trainer.model)) + + trainer.train() + self.assertTrue(isinstance(trainer.state.total_flos, float)) + + def check_checkpoint_deletion(self, trainer, output_dir, expected): + # Make fake checkpoints + for n in [5, 10, 15, 20, 25]: + os.makedirs(os.path.join(output_dir, f"{PREFIX_CHECKPOINT_DIR}-{n}"), exist_ok=True) + trainer._rotate_checkpoints(output_dir=output_dir) + glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{PREFIX_CHECKPOINT_DIR}-*")] + values = [int(re.match(f".*{PREFIX_CHECKPOINT_DIR}-([0-9]+)", d).groups()[0]) for d in glob_checkpoints] + self.assertSetEqual(set(values), set(expected)) + + def test_checkpoint_rotation(self): + with tempfile.TemporaryDirectory() as tmp_dir: + # Without best model at end + trainer = get_regression_trainer(output_dir=tmp_dir, save_total_limit=2) + self.check_checkpoint_deletion(trainer, tmp_dir, [20, 25]) + + # With best model at end + trainer = get_regression_trainer( + output_dir=tmp_dir, evaluation_strategy="steps", load_best_model_at_end=True, save_total_limit=2 + ) + trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-5") + self.check_checkpoint_deletion(trainer, tmp_dir, [5, 25]) + + # Edge case: we don't always honor save_total_limit=1 if load_best_model_at_end=True to be able to resume + # from checkpoint + trainer = get_regression_trainer( + output_dir=tmp_dir, evaluation_strategy="steps", load_best_model_at_end=True, save_total_limit=1 + ) + trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-25") + self.check_checkpoint_deletion(trainer, tmp_dir, [25]) + + trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-5") + self.check_checkpoint_deletion(trainer, tmp_dir, [5, 25]) + + def check_mem_metrics(self, trainer, check_func): + metrics = trainer.train().metrics + check_func("init_mem_cpu_alloc_delta", metrics) + check_func("train_mem_cpu_alloc_delta", metrics) + if backend_device_count(torch_device) > 0: + check_func("init_mem_gpu_alloc_delta", metrics) + check_func("train_mem_gpu_alloc_delta", metrics) + + metrics = trainer.evaluate() + check_func("eval_mem_cpu_alloc_delta", metrics) + if backend_device_count(torch_device) > 0: + check_func("eval_mem_gpu_alloc_delta", metrics) + + metrics = trainer.predict(RegressionDataset()).metrics + check_func("test_mem_cpu_alloc_delta", metrics) + if backend_device_count(torch_device) > 0: + check_func("test_mem_gpu_alloc_delta", metrics) + + def test_mem_metrics(self): + # with mem metrics enabled + trainer = get_regression_trainer(skip_memory_metrics=False) + self.check_mem_metrics(trainer, self.assertIn) + + # with mem metrics disabled + trainer = get_regression_trainer(skip_memory_metrics=True) + self.check_mem_metrics(trainer, self.assertNotIn) + + @require_torch_accelerator + def test_fp16_full_eval(self): + # this is a sensitive test so let's keep debugging printouts in place for quick diagnosis. + # it's using pretty large safety margins, but small enough to detect broken functionality. + debug = 0 + n_gpus = backend_device_count(torch_device) + + bs = 8 + eval_len = 16 * n_gpus + # make the params somewhat big so that there will be enough RAM consumed to be able to + # measure things. We should get about 64KB for a+b in fp32 + a = torch.ones(1000, bs) + 0.001 + b = torch.ones(1000, bs) - 0.001 + + # 1. with fp16_full_eval disabled + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len, skip_memory_metrics=False) + metrics = trainer.evaluate() + del trainer + gc.collect() + + fp32_init = metrics["init_mem_gpu_alloc_delta"] + fp32_eval = metrics["eval_mem_gpu_alloc_delta"] + + if debug: + print(f"fp32_init {fp32_init}") + print(f"fp32_eval {fp32_eval}") + + # here we expect the model to be preloaded in trainer.__init__ and consume around 64K gpu ram. + # perfect world: fp32_init == 64<<10 + self.assertGreater(fp32_init, 59_000) + # after eval should be no extra memory allocated - with a small margin (other than the peak + # memory consumption for the forward calculation that gets recovered) + # perfect world: fp32_eval == close to zero + self.assertLess(fp32_eval, 5_000) + + # 2. with fp16_full_eval enabled + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len, fp16_full_eval=True, skip_memory_metrics=False) + metrics = trainer.evaluate() + fp16_init = metrics["init_mem_gpu_alloc_delta"] + fp16_eval = metrics["eval_mem_gpu_alloc_delta"] + + if debug: + print(f"fp16_init {fp16_init}") + print(f"fp16_eval {fp16_eval}") + + # here we expect the model to not be preloaded in trainer.__init__, so with a small margin it should be close to 0 + # perfect world: fp16_init == close to zero + self.assertLess(fp16_init, 5_000) + # here we put the model on device in eval and only `half()` of it, i.e. about 32K,(again we ignore the peak margin which gets returned back) + # perfect world: fp32_init == 32<<10 + self.assertGreater(fp16_eval, 27_000) + + # 3. relative comparison fp32 vs full fp16 + # should be about half of fp16_init + # perfect world: fp32_init/2 == fp16_eval + self.assertAlmostEqual(fp16_eval, fp32_init / 2, delta=5_000) + + @require_torch_non_multi_gpu + @require_torchdynamo + @require_torch_tensorrt_fx + def test_torchdynamo_full_eval(self): + import torchdynamo + + # torchdynamo at the moment doesn't support DP/DDP, therefore require a single gpu + n_gpus = get_gpu_count() + + bs = 8 + eval_len = 16 * n_gpus + # make the params are somewhat big so that there will be enough RAM consumed to be able to + # measure things. We should get about 64KB for a+b in fp32 + a = torch.ones(1000, bs) + 0.001 + b = torch.ones(1000, bs) - 0.001 + + # 1. Default - without TorchDynamo + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len) + metrics = trainer.evaluate() + original_eval_loss = metrics["eval_loss"] + del trainer + + # 2. TorchDynamo eager + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len, torchdynamo="eager") + metrics = trainer.evaluate() + self.assertAlmostEqual(metrics["eval_loss"], original_eval_loss) + del trainer + torchdynamo.reset() + + # 3. TorchDynamo nvfuser + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len, torchdynamo="nvfuser") + metrics = trainer.evaluate() + self.assertAlmostEqual(metrics["eval_loss"], original_eval_loss) + torchdynamo.reset() + + # 4. TorchDynamo fx2trt + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len, torchdynamo="fx2trt") + metrics = trainer.evaluate() + self.assertAlmostEqual(metrics["eval_loss"], original_eval_loss) + torchdynamo.reset() + + @unittest.skip("torch 2.0.0 gives `ModuleNotFoundError: No module named 'torchdynamo'`.") + @require_torch_non_multi_gpu + @require_torchdynamo + def test_torchdynamo_memory(self): + # torchdynamo at the moment doesn't support DP/DDP, therefore require a single gpu + import torchdynamo + + class CustomTrainer(Trainer): + def compute_loss(self, model, inputs, return_outputs=False): + x = inputs["x"] + output = model(x) + if self.args.n_gpu == 1: + return output.mean() + return output + + class MyModule(torch.nn.Module): + """Simple module that does aggressive fusion""" + + def __init__(self): + super().__init__() + + def forward(self, x): + for _ in range(20): + x = torch.cos(x) + return x + + mod = MyModule() + + # 1. without TorchDynamo (eager baseline) + a = torch.ones(1024, 1024, device="cuda", requires_grad=True) + a.grad = None + trainer = CustomTrainer(model=mod) + # warmup + for _ in range(10): + orig_loss = trainer.training_step(mod, {"x": a}) + + # resets + gc.collect() + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + + orig_loss = trainer.training_step(mod, {"x": a}) + orig_peak_mem = torch.cuda.max_memory_allocated() + torchdynamo.reset() + del trainer + + # 2. TorchDynamo nvfuser + a = torch.ones(1024, 1024, device="cuda", requires_grad=True) + a.grad = None + args = TrainingArguments(output_dir="None", torchdynamo="nvfuser") + trainer = CustomTrainer(model=mod, args=args) + # warmup + for _ in range(10): + loss = trainer.training_step(mod, {"x": a}) + + # resets + gc.collect() + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + + loss = trainer.training_step(mod, {"x": a}) + peak_mem = torch.cuda.max_memory_allocated() + torchdynamo.reset() + del trainer + + # Functional check + self.assertAlmostEqual(loss, orig_loss) + + # AOT Autograd recomputaion and nvfuser recomputation optimization + # aggressively fuses the operations and reduce the memory footprint. + self.assertGreater(orig_peak_mem, peak_mem * 2) + + @require_torch_accelerator + @require_torch_bf16 + def test_bf16_full_eval(self): + # note: most of the logic is the same as test_fp16_full_eval + + # this is a sensitive test so let's keep debugging printouts in place for quick diagnosis. + # it's using pretty large safety margins, but small enough to detect broken functionality. + debug = 0 + n_gpus = backend_device_count(torch_device) + + bs = 8 + eval_len = 16 * n_gpus + # make the params somewhat big so that there will be enough RAM consumed to be able to + # measure things. We should get about 64KB for a+b in fp32 + a = torch.ones(1000, bs) + 0.001 + b = torch.ones(1000, bs) - 0.001 + + # 1. with bf16_full_eval disabled + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len, skip_memory_metrics=False) + metrics = trainer.evaluate() + del trainer + gc.collect() + + fp32_init = metrics["init_mem_gpu_alloc_delta"] + fp32_eval = metrics["eval_mem_gpu_alloc_delta"] + + if debug: + print(f"fp32_init {fp32_init}") + print(f"fp32_eval {fp32_eval}") + + # here we expect the model to be preloaded in trainer.__init__ and consume around 64K gpu ram. + # perfect world: fp32_init == 64<<10 + self.assertGreater(fp32_init, 59_000) + # after eval should be no extra memory allocated - with a small margin (other than the peak + # memory consumption for the forward calculation that gets recovered) + # perfect world: fp32_eval == close to zero + self.assertLess(fp32_eval, 5_000) + + # 2. with bf16_full_eval enabled + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len, bf16_full_eval=True, skip_memory_metrics=False) + metrics = trainer.evaluate() + bf16_init = metrics["init_mem_gpu_alloc_delta"] + bf16_eval = metrics["eval_mem_gpu_alloc_delta"] + + if debug: + print(f"bf16_init {bf16_init}") + print(f"bf16_eval {bf16_eval}") + + # here we expect the model to not be preloaded in trainer.__init__, so with a small margin it should be close to 0 + # perfect world: bf16_init == close to zero + self.assertLess(bf16_init, 5_000) + # here we put the model on device in eval and only `half()` of it, i.e. about 32K,(again we ignore the peak margin which gets returned back) + # perfect world: fp32_init == 32<<10 + self.assertGreater(bf16_eval, 27_000) + + # 3. relative comparison fp32 vs full bf16 + # should be about half of bf16_init + # perfect world: fp32_init/2 == bf16_eval + self.assertAlmostEqual(bf16_eval, fp32_init / 2, delta=5_000) + + def test_no_wd_param_group(self): + model = nn.Sequential(TstLayer(128), nn.ModuleList([TstLayer(128), TstLayer(128)])) + trainer = Trainer(model=model) + trainer.create_optimizer_and_scheduler(10) + wd_names = ['0.linear1.weight', '0.linear2.weight', '1.0.linear1.weight', '1.0.linear2.weight', '1.1.linear1.weight', '1.1.linear2.weight'] # fmt: skip + wd_params = [p for n, p in model.named_parameters() if n in wd_names] + no_wd_params = [p for n, p in model.named_parameters() if n not in wd_names] + self.assertListEqual(trainer.optimizer.param_groups[0]["params"], wd_params) + self.assertListEqual(trainer.optimizer.param_groups[1]["params"], no_wd_params) + + @slow + @require_torch_multi_accelerator + def test_end_to_end_example(self): + # Tests that `translation.py` will run without issues + script_path = os.path.abspath( + os.path.join( + os.path.dirname(__file__), "..", "..", "examples", "pytorch", "translation", "run_translation.py" + ) + ) + + with tempfile.TemporaryDirectory() as tmpdir: + command = [ + "accelerate", + "launch", + script_path, + "--model_name_or_path", + "t5-small", + "--per_device_train_batch_size", + "1", + "--output_dir", + tmpdir, + "--overwrite_output_dir", + "--do_train", + "--max_train_samples", + "64", + "--num_train_epochs", + "1", + "--dataset_name", + "wmt16", + "--dataset_config", + "ro-en", + "--source_lang", + "en", + "--target_lang", + "ro", + "--do_predict", + "--max_predict_samples", + "64", + "--predict_with_generate", + "--ddp_timeout", + "60", + ] + execute_subprocess_async(command) + # successful return here == success - any errors would have caused an error or a timeout in the sub-call + + +@require_torch +@is_staging_test +class TrainerIntegrationWithHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @classmethod + def tearDownClass(cls): + for model in ["test-trainer", "test-trainer-epoch", "test-trainer-step", "test-trainer-tensorboard"]: + try: + delete_repo(token=cls._token, repo_id=model) + except HTTPError: + pass + + try: + delete_repo(token=cls._token, repo_id="valid_org/test-trainer-org") + except HTTPError: + pass + + def test_push_to_hub(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, "test-trainer"), + push_to_hub=True, + hub_token=self._token, + ) + url = trainer.push_to_hub() + + # Extract repo_name from the url + re_search = re.search(ENDPOINT_STAGING + r"/([^/]+/[^/]+)/", url) + self.assertTrue(re_search is not None) + repo_name = re_search.groups()[0] + + self.assertEqual(repo_name, f"{USER}/test-trainer") + + model = RegressionPreTrainedModel.from_pretrained(repo_name) + self.assertEqual(model.a.item(), trainer.model.a.item()) + self.assertEqual(model.b.item(), trainer.model.b.item()) + + def test_push_to_hub_in_organization(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(output_dir=tmp_dir) + trainer.save_model() + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, "test-trainer-org"), + push_to_hub=True, + hub_model_id="valid_org/test-trainer-org", + hub_token=self._token, + ) + url = trainer.push_to_hub() + + # Extract repo_name from the url + re_search = re.search(ENDPOINT_STAGING + r"/([^/]+/[^/]+)/", url) + self.assertTrue(re_search is not None) + repo_name = re_search.groups()[0] + self.assertEqual(repo_name, "valid_org/test-trainer-org") + + model = RegressionPreTrainedModel.from_pretrained("valid_org/test-trainer-org") + self.assertEqual(model.a.item(), trainer.model.a.item()) + self.assertEqual(model.b.item(), trainer.model.b.item()) + + def get_commit_history(self, repo): + commit_logs = subprocess.run( + "git log".split(), + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + check=True, + encoding="utf-8", + cwd=repo, + ).stdout + commits = commit_logs.split("\n\n")[1::2] + return [commit.strip() for commit in commits] + + def test_push_to_hub_with_saves_each_epoch(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, "test-trainer-epoch"), + push_to_hub=True, + hub_token=self._token, + # To avoid any flakiness if the training goes faster than the uploads. + hub_always_push=True, + save_strategy="epoch", + ) + trainer.train() + + commits = list_repo_commits(f"{USER}/test-trainer-epoch", token=self._token) + commits = [c.title for c in commits] + self.assertIn("initial commit", commits) + for i in range(1, 4): + self.assertIn(f"Training in progress, epoch {i}", commits) + + def test_push_to_hub_with_saves_each_n_steps(self): + num_gpus = max(1, backend_device_count(torch_device)) + if num_gpus > 2: + return + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, "test-trainer-step"), + push_to_hub=True, + hub_token=self._token, + # To avoid any flakiness if the training goes faster than the uploads. + hub_always_push=True, + save_strategy="steps", + save_steps=5, + ) + trainer.train() + + commits = list_repo_commits(f"{USER}/test-trainer-step", token=self._token) + commits = [c.title for c in commits] + self.assertIn("initial commit", commits) + + # max_steps depend on the number of available GPUs + max_steps = math.ceil(trainer.args.num_train_epochs * len(trainer.get_train_dataloader())) + for i in range(5, max_steps, 5): + self.assertIn(f"Training in progress, step {i}", commits) + + @require_tensorboard + def test_push_to_hub_with_tensorboard_logs(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, "test-trainer-tensorboard"), + hub_token=self._token, + save_strategy="epoch", + report_to=["tensorboard"], + keep_report_to=True, + ) + trainer.train() + # Push the runs via `push_to_hub()` + trainer.push_to_hub() + + files = list_repo_files(f"{USER}/test-trainer-tensorboard", token=self._token) + found_log = False + for f in files: + if len(f.split("runs")) > 1 and "events.out.tfevents" in f: + found_log = True + + assert found_log is True, "No tensorboard log found in repo" + + +@require_torch +@require_optuna +class TrainerHyperParameterOptunaIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + return {} + + def model_init(trial): + if trial is not None: + a = trial.suggest_int("a", -4, 4) + b = trial.suggest_int("b", -4, 4) + else: + a = 0 + b = 0 + config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(config) + + def hp_name(trial): + return MyTrialShortNamer.shortname(trial.params) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + evaluation_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=4, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + ) + trainer.hyperparameter_search(direction="minimize", hp_space=hp_space, hp_name=hp_name, n_trials=4) + + +@require_torch +@require_optuna +class TrainerHyperParameterMultiObjectOptunaIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + return {} + + def model_init(trial): + if trial is not None: + a = trial.suggest_int("a", -4, 4) + b = trial.suggest_int("b", -4, 4) + else: + a = 0 + b = 0 + config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(config) + + def hp_name(trial): + return MyTrialShortNamer.shortname(trial.params) + + def compute_objective(metrics: Dict[str, float]) -> List[float]: + return metrics["eval_loss"], metrics["eval_accuracy"] + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + evaluation_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=10, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + compute_metrics=AlmostAccuracy(), + ) + trainer.hyperparameter_search( + direction=["minimize", "maximize"], + hp_space=hp_space, + hp_name=hp_name, + n_trials=4, + compute_objective=compute_objective, + ) + + +@require_torch +@require_ray +class TrainerHyperParameterRayIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def ray_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + from ray import tune + + return { + "a": tune.randint(-4, 4), + "b": tune.randint(-4, 4), + } + + def model_init(config): + if config is None: + a = 0 + b = 0 + else: + a = config["a"] + b = config["b"] + model_config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(model_config) + + def hp_name(params): + return MyTrialShortNamer.shortname(params) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + evaluation_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=4, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + ) + trainer.hyperparameter_search( + direction="minimize", hp_space=hp_space, hp_name=hp_name, backend="ray", n_trials=4 + ) + + def test_hyperparameter_search(self): + self.ray_hyperparameter_search() + + def test_hyperparameter_search_ray_client(self): + import ray + from ray.util.client.ray_client_helpers import ray_start_client_server + + with ray_start_client_server(): + assert ray.util.client.ray.is_connected() + self.ray_hyperparameter_search() + + +@slow +@require_torch +@require_sigopt +class TrainerHyperParameterSigOptIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + return [ + {"bounds": {"min": -4, "max": 4}, "name": "a", "type": "int"}, + {"bounds": {"min": -4, "max": 4}, "name": "b", "type": "int"}, + ] + + def model_init(trial): + if trial is not None: + a = trial.assignments["a"] + b = trial.assignments["b"] + else: + a = 0 + b = 0 + config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(config) + + def hp_name(trial): + return MyTrialShortNamer.shortname(trial.assignments) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + evaluation_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=4, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + ) + trainer.hyperparameter_search( + direction="minimize", hp_space=hp_space, hp_name=hp_name, backend="sigopt", n_trials=4 + ) + + +optim_test_params = [] +if is_torch_available(): + default_adam_kwargs = { + "betas": (TrainingArguments.adam_beta1, TrainingArguments.adam_beta2), + "eps": TrainingArguments.adam_epsilon, + "lr": TrainingArguments.learning_rate, + } + + default_lion_kwargs = { + "betas": (TrainingArguments.adam_beta1, TrainingArguments.adam_beta2), + "lr": TrainingArguments.learning_rate, + } + + default_anyprecision_kwargs = { + "use_kahan_summation": False, + "momentum_dtype": torch.float32, + "variance_dtype": torch.float32, + "compensation_buffer_dtype": torch.bfloat16, + } + + optim_test_params = [ + ( + TrainingArguments(optim=OptimizerNames.ADAMW_HF, output_dir="None"), + transformers.optimization.AdamW, + default_adam_kwargs, + ), + ( + TrainingArguments(optim=OptimizerNames.ADAMW_HF.value, output_dir="None"), + transformers.optimization.AdamW, + default_adam_kwargs, + ), + ( + TrainingArguments(optim=OptimizerNames.ADAMW_TORCH, output_dir="None"), + torch.optim.AdamW, + default_adam_kwargs, + ), + ( + TrainingArguments(optim=OptimizerNames.ADAFACTOR, output_dir="None"), + transformers.optimization.Adafactor, + { + "scale_parameter": False, + "relative_step": False, + "lr": TrainingArguments.learning_rate, + }, + ), + ] + + if is_apex_available(): + import apex + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.ADAMW_APEX_FUSED, output_dir="None"), + apex.optimizers.FusedAdam, + default_adam_kwargs, + ) + ) + + if is_bitsandbytes_available(): + import bitsandbytes as bnb + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.ADAMW_BNB, output_dir="None"), + bnb.optim.AdamW, + default_adam_kwargs, + ) + ) + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.ADAMW_8BIT, output_dir="None"), + bnb.optim.AdamW, + default_adam_kwargs, + ) + ) + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.PAGED_ADAMW, output_dir="None"), + bnb.optim.AdamW, + default_adam_kwargs, + ) + ) + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.PAGED_ADAMW_8BIT, output_dir="None"), + bnb.optim.AdamW, + default_adam_kwargs, + ) + ) + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.LION, output_dir="None"), + bnb.optim.Lion, + default_lion_kwargs, + ) + ) + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.LION_8BIT, output_dir="None"), + bnb.optim.Lion, + default_lion_kwargs, + ) + ) + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.PAGED_LION_8BIT, output_dir="None"), + bnb.optim.Lion, + default_lion_kwargs, + ) + ) + + if is_torchdistx_available(): + import torchdistx + + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.ADAMW_ANYPRECISION, output_dir="None"), + torchdistx.optimizers.AnyPrecisionAdamW, + dict(default_adam_kwargs, **default_anyprecision_kwargs), + ) + ) + + +@require_torch +class TrainerOptimizerChoiceTest(unittest.TestCase): + def check_optim_and_kwargs(self, training_args: TrainingArguments, expected_cls, expected_kwargs): + actual_cls, optim_kwargs = Trainer.get_optimizer_cls_and_kwargs(training_args) + self.assertEqual(expected_cls, actual_cls) + self.assertIsNotNone(optim_kwargs) + + for p, v in expected_kwargs.items(): + self.assertTrue(p in optim_kwargs) + actual_v = optim_kwargs[p] + self.assertTrue(actual_v == v, f"Failed check for {p}. Expected {v}, but got {actual_v}.") + + @parameterized.expand(optim_test_params, skip_on_empty=True) + def test_optim_supported(self, training_args: TrainingArguments, expected_cls, expected_kwargs): + # exercises all the valid --optim options + self.check_optim_and_kwargs(training_args, expected_cls, expected_kwargs) + + trainer = get_regression_trainer(**training_args.to_dict()) + trainer.train() + + def test_fused_adam(self): + # Pretend that apex is installed and mock apex.optimizers.FusedAdam exists. + # Trainer.get_optimizer_cls_and_kwargs does not use FusedAdam. It only has to return the + # class given, so mocking apex.optimizers.FusedAdam should be fine for testing and allow + # the test to run without requiring an apex installation. + mock = Mock() + modules = { + "apex": mock, + "apex.optimizers": mock.optimizers, + "apex.optimizers.FusedAdam": mock.optimizers.FusedAdam, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADAMW_APEX_FUSED, output_dir="None"), + mock.optimizers.FusedAdam, + default_adam_kwargs, + ) + + def test_fused_adam_no_apex(self): + args = TrainingArguments(optim=OptimizerNames.ADAMW_APEX_FUSED, output_dir="None") + + # Pretend that apex does not exist, even if installed. By setting apex to None, importing + # apex will fail even if apex is installed. + with patch.dict("sys.modules", {"apex.optimizers": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_adam8bit(self): + # Pretend that Bits and Bytes is installed and mock bnb.optim.Adam8bit exists. + # Trainer.get_optimizer_cls_and_kwargs does not use Adam8bit. It only has to return the + # class given, so mocking bnb.optim.Adam8bit should be fine for testing and allow + # the test to run without requiring a bnb installation. + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdamW": mock.optim.AdamW, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADAMW_BNB, output_dir="None"), + mock.optim.AdamW, + default_adam_kwargs, + ) + + def test_bnb_paged_adam8bit_alias(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdamW": mock.optim.AdamW, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADAMW_8BIT, output_dir="None"), + mock.optim.AdamW, + default_adam_kwargs, + ) + + def test_bnb_paged_adam(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdamW": mock.optim.AdamW, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_ADAMW, output_dir="None"), + mock.optim.AdamW, + default_adam_kwargs, + ) + + def test_bnb_paged_adam8bit(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdamW": mock.optim.AdamW, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_ADAMW_8BIT, output_dir="None"), + mock.optim.AdamW, + default_adam_kwargs, + ) + + def test_bnb_lion(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.Lion": mock.optim.Lion, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.LION, output_dir="None"), + mock.optim.Lion, + default_lion_kwargs, + ) + + def test_bnb_lion8bit(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.Lion": mock.optim.Lion, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.LION_8BIT, output_dir="None"), + mock.optim.Lion, + default_lion_kwargs, + ) + + def test_bnb_paged_lion8bit(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.Lion": mock.optim.Lion, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_LION_8BIT, output_dir="None"), + mock.optim.Lion, + default_lion_kwargs, + ) + + def test_bnb_paged_lion(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.Lion": mock.optim.Lion, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_LION, output_dir="None"), + mock.optim.Lion, + default_lion_kwargs, + ) + + def test_bnb_adam8bit_no_bnb(self): + args = TrainingArguments(optim=OptimizerNames.ADAMW_BNB, output_dir="None") + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if bnb is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_adam_no_bnb(self): + args = TrainingArguments(optim=OptimizerNames.PAGED_ADAMW, output_dir="None") + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if bnb is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_adam8bit_no_bnb(self): + args = TrainingArguments(optim=OptimizerNames.PAGED_ADAMW_8BIT, output_dir="None") + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if bnb is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_lion_no_bnb(self): + args = TrainingArguments(optim=OptimizerNames.PAGED_LION, output_dir="None") + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if bnb is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_lion8bit_no_bnb(self): + args = TrainingArguments(optim=OptimizerNames.PAGED_LION_8BIT, output_dir="None") + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if bnb is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_anyprecision_adamw(self): + # Pretend that torchdistx is installed and mock torchdistx.optimizers.AnyPrecisionAdamW exists. + # Trainer.get_optimizer_cls_and_kwargs does not use AnyPrecisioinAdamW. It only has to return the + # class given, so mocking torchdistx.optimizers.AnyPrecisionAdamW should be fine for testing and allow + # the test to run without requiring a bnb installation. + mock = Mock() + modules = { + "torchdistx": mock, + "torchdistx.optimizers": mock.optimizers, + "torchdistx.optimizers.AnyPrecisionAdamW.": mock.optimizers.AnyPrecisionAdamW, + } + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADAMW_ANYPRECISION, output_dir="None"), + mock.optimizers.AnyPrecisionAdamW, + dict(default_adam_kwargs, **default_anyprecision_kwargs), + ) + + def test_no_torchdistx_anyprecision_adamw(self): + args = TrainingArguments(optim=OptimizerNames.ADAMW_ANYPRECISION, output_dir="None") + + # Pretend that torchdistx does not exist, even if installed. By setting torchdistx to None, importing + # torchdistx.optimizers will fail even if torchdistx is installed. + with patch.dict("sys.modules", {"torchdistx.optimizers": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + +@require_torch +@require_wandb +class TrainerHyperParameterWandbIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + return { + "method": "random", + "metric": {}, + "parameters": { + "a": {"distribution": "uniform", "min": 1e-6, "max": 1e-4}, + "b": {"distribution": "int_uniform", "min": 1, "max": 6}, + }, + } + + def model_init(config): + if config is None: + a = 0 + b = 0 + else: + a = config["a"] + b = config["b"] + model_config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(model_config) + + def hp_name(params): + return MyTrialShortNamer.shortname(params) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + evaluation_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=4, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + ) + trainer.hyperparameter_search( + direction="minimize", hp_space=hp_space, hp_name=hp_name, backend="wandb", n_trials=4, anonymous="must" + ) + + +class HyperParameterSearchBackendsTest(unittest.TestCase): + def test_hyperparameter_search_backends(self): + self.assertEqual( + list(ALL_HYPERPARAMETER_SEARCH_BACKENDS.keys()), + list(HPSearchBackend), + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_callback.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..8e851132c2daabc7d86631e242d2a6a460cbad3e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_callback.py @@ -0,0 +1,245 @@ +# 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 shutil +import tempfile +import unittest +from unittest.mock import patch + +from transformers import ( + DefaultFlowCallback, + IntervalStrategy, + PrinterCallback, + ProgressCallback, + Trainer, + TrainerCallback, + TrainingArguments, + is_torch_available, +) +from transformers.testing_utils import require_torch + + +if is_torch_available(): + from transformers.trainer import DEFAULT_CALLBACKS + + from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel + + +class MyTestTrainerCallback(TrainerCallback): + "A callback that registers the events that goes through." + + def __init__(self): + self.events = [] + + def on_init_end(self, args, state, control, **kwargs): + self.events.append("on_init_end") + + def on_train_begin(self, args, state, control, **kwargs): + self.events.append("on_train_begin") + + def on_train_end(self, args, state, control, **kwargs): + self.events.append("on_train_end") + + def on_epoch_begin(self, args, state, control, **kwargs): + self.events.append("on_epoch_begin") + + def on_epoch_end(self, args, state, control, **kwargs): + self.events.append("on_epoch_end") + + def on_step_begin(self, args, state, control, **kwargs): + self.events.append("on_step_begin") + + def on_step_end(self, args, state, control, **kwargs): + self.events.append("on_step_end") + + def on_evaluate(self, args, state, control, **kwargs): + self.events.append("on_evaluate") + + def on_predict(self, args, state, control, **kwargs): + self.events.append("on_predict") + + def on_save(self, args, state, control, **kwargs): + self.events.append("on_save") + + def on_log(self, args, state, control, **kwargs): + self.events.append("on_log") + + def on_prediction_step(self, args, state, control, **kwargs): + self.events.append("on_prediction_step") + + +@require_torch +class TrainerCallbackTest(unittest.TestCase): + def setUp(self): + self.output_dir = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self.output_dir) + + def get_trainer(self, a=0, b=0, train_len=64, eval_len=64, callbacks=None, disable_tqdm=False, **kwargs): + # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure + # its set to False since the tests later on depend on its value. + train_dataset = RegressionDataset(length=train_len) + eval_dataset = RegressionDataset(length=eval_len) + config = RegressionModelConfig(a=a, b=b) + model = RegressionPreTrainedModel(config) + + args = TrainingArguments(self.output_dir, disable_tqdm=disable_tqdm, report_to=[], **kwargs) + return Trainer( + model, + args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + callbacks=callbacks, + ) + + def check_callbacks_equality(self, cbs1, cbs2): + self.assertEqual(len(cbs1), len(cbs2)) + + # Order doesn't matter + cbs1 = sorted(cbs1, key=lambda cb: cb.__name__ if isinstance(cb, type) else cb.__class__.__name__) + cbs2 = sorted(cbs2, key=lambda cb: cb.__name__ if isinstance(cb, type) else cb.__class__.__name__) + + for cb1, cb2 in zip(cbs1, cbs2): + if isinstance(cb1, type) and isinstance(cb2, type): + self.assertEqual(cb1, cb2) + elif isinstance(cb1, type) and not isinstance(cb2, type): + self.assertEqual(cb1, cb2.__class__) + elif not isinstance(cb1, type) and isinstance(cb2, type): + self.assertEqual(cb1.__class__, cb2) + else: + self.assertEqual(cb1, cb2) + + def get_expected_events(self, trainer): + expected_events = ["on_init_end", "on_train_begin"] + step = 0 + train_dl_len = len(trainer.get_eval_dataloader()) + evaluation_events = ["on_prediction_step"] * len(trainer.get_eval_dataloader()) + ["on_log", "on_evaluate"] + for _ in range(trainer.state.num_train_epochs): + expected_events.append("on_epoch_begin") + for _ in range(train_dl_len): + step += 1 + expected_events += ["on_step_begin", "on_step_end"] + if step % trainer.args.logging_steps == 0: + expected_events.append("on_log") + if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: + expected_events += evaluation_events.copy() + if step % trainer.args.save_steps == 0: + expected_events.append("on_save") + expected_events.append("on_epoch_end") + if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: + expected_events += evaluation_events.copy() + expected_events += ["on_log", "on_train_end"] + return expected_events + + def test_init_callback(self): + trainer = self.get_trainer() + expected_callbacks = DEFAULT_CALLBACKS.copy() + [ProgressCallback] + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + # Callbacks passed at init are added to the default callbacks + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback]) + expected_callbacks.append(MyTestTrainerCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback + trainer = self.get_trainer(disable_tqdm=True) + expected_callbacks = DEFAULT_CALLBACKS.copy() + [PrinterCallback] + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + def test_add_remove_callback(self): + expected_callbacks = DEFAULT_CALLBACKS.copy() + [ProgressCallback] + trainer = self.get_trainer() + + # We can add, pop, or remove by class name + trainer.remove_callback(DefaultFlowCallback) + expected_callbacks.remove(DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + trainer = self.get_trainer() + cb = trainer.pop_callback(DefaultFlowCallback) + self.assertEqual(cb.__class__, DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + trainer.add_callback(DefaultFlowCallback) + expected_callbacks.insert(0, DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + # We can also add, pop, or remove by instance + trainer = self.get_trainer() + cb = trainer.callback_handler.callbacks[0] + trainer.remove_callback(cb) + expected_callbacks.remove(DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + trainer = self.get_trainer() + cb1 = trainer.callback_handler.callbacks[0] + cb2 = trainer.pop_callback(cb1) + self.assertEqual(cb1, cb2) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + trainer.add_callback(cb1) + expected_callbacks.insert(0, DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + def test_event_flow(self): + import warnings + + # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested + warnings.simplefilter(action="ignore", category=UserWarning) + + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback]) + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + # Independent log/save/eval + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback], logging_steps=5) + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback], save_steps=5) + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback], eval_steps=5, evaluation_strategy="steps") + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback], evaluation_strategy="epoch") + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + # A bit of everything + trainer = self.get_trainer( + callbacks=[MyTestTrainerCallback], + logging_steps=3, + save_steps=10, + eval_steps=5, + evaluation_strategy="steps", + ) + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + # warning should be emitted for duplicated callbacks + with patch("transformers.trainer_callback.logger.warning") as warn_mock: + trainer = self.get_trainer( + callbacks=[MyTestTrainerCallback, MyTestTrainerCallback], + ) + assert str(MyTestTrainerCallback) in warn_mock.call_args[0][0] diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_distributed.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..2850d6c40b4e1c45bc607bb8a5a5587f94689cc2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_distributed.py @@ -0,0 +1,263 @@ +# 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. + +from pathlib import Path +from typing import Dict + +import numpy as np + +from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available +from transformers.testing_utils import ( + TestCasePlus, + execute_subprocess_async, + get_torch_dist_unique_port, + require_torch_multi_gpu, + require_torch_multi_xpu, + require_torch_neuroncore, + require_torch_npu, +) +from transformers.training_args import ParallelMode +from transformers.utils import logging + + +logger = logging.get_logger(__name__) + + +if is_torch_available(): + import torch + from torch import nn + from torch.utils.data import Dataset, IterableDataset + + from transformers import Trainer + + class DummyDataset(Dataset): + def __init__(self, length: int = 101): + self.length = length + + def __len__(self): + return self.length + + def __getitem__(self, i) -> int: + return i + + class DummyDataCollator: + def __call__(self, features): + return {"input_ids": torch.tensor(features), "labels": torch.tensor(features)} + + class DummyModel(nn.Module): + def __init__(self): + super().__init__() + # Add some (unused) params otherwise DDP will complain. + self.fc = nn.Linear(120, 80) + + def forward(self, input_ids, labels=None): + if labels is not None: + return torch.tensor(0.0, device=input_ids.device), input_ids + else: + return input_ids + + class RegressionModel(nn.Module): + def __init__(self, a=0, b=0, double_output=False): + super().__init__() + self.a = nn.Parameter(torch.tensor(a).float()) + self.b = nn.Parameter(torch.tensor(b).float()) + self.double_output = double_output + self.config = None + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + if labels is None: + return (y, y) if self.double_output else (y,) + loss = nn.functional.mse_loss(y, labels) + return (loss, y, y) if self.double_output else (loss, y) + + class SampleIterableDataset(IterableDataset): + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + self.dataset = RegressionDataset(a=a, b=b, length=length, seed=seed, label_names=label_names) + + def __iter__(self): + for i in range(len(self.dataset)): + yield self.dataset[i] + + class FiniteIterableDataset(SampleIterableDataset): + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + super().__init__(a, b, length, seed, label_names) + self.current_sample = 0 + + def __iter__(self): + while self.current_sample < len(self.dataset): + yield self.dataset[self.current_sample] + self.current_sample += 1 + + class RegressionDataset: + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + np.random.seed(seed) + self.label_names = ["labels"] if label_names is None else label_names + self.length = length + self.x = np.random.normal(size=(length,)).astype(np.float32) + self.ys = [a * self.x + b + np.random.normal(scale=0.1, size=(length,)) for _ in self.label_names] + self.ys = [y.astype(np.float32) for y in self.ys] + + def __len__(self): + return self.length + + def __getitem__(self, i): + result = {name: y[i] for name, y in zip(self.label_names, self.ys)} + result["input_x"] = self.x[i] + return result + + +class TestTrainerDistributedNeuronCore(TestCasePlus): + @require_torch_neuroncore + def test_trainer(self): + distributed_args = f"""--nproc_per_node=2 + --master_port={get_torch_dist_unique_port()} + {self.test_file_dir}/test_trainer_distributed.py + """.split() + output_dir = self.get_auto_remove_tmp_dir() + args = f"--output_dir {output_dir}".split() + cmd = ["torchrun"] + distributed_args + args + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +class TestTrainerDistributedNPU(TestCasePlus): + @require_torch_npu + def test_trainer(self): + distributed_args = f"""--nproc_per_node=2 + --master_port={get_torch_dist_unique_port()} + {self.test_file_dir}/test_trainer_distributed.py + """.split() + output_dir = self.get_auto_remove_tmp_dir() + args = f"--output_dir {output_dir}".split() + cmd = ["torchrun"] + distributed_args + args + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +class TestTrainerDistributed(TestCasePlus): + @require_torch_multi_gpu + def test_trainer(self): + distributed_args = f"""--nproc_per_node={torch.cuda.device_count()} + --master_port={get_torch_dist_unique_port()} + {self.test_file_dir}/test_trainer_distributed.py + """.split() + output_dir = self.get_auto_remove_tmp_dir() + args = f"--output_dir {output_dir}".split() + cmd = ["torchrun"] + distributed_args + args + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +@require_torch_multi_xpu +class TestTrainerDistributedXPU(TestCasePlus): + def test_trainer(self): + distributed_args = f"""--nproc_per_node={torch.xpu.device_count()} + --master_port={get_torch_dist_unique_port()} + {self.test_file_dir}/test_trainer_distributed.py + """.split() + output_dir = self.get_auto_remove_tmp_dir() + args = f"--output_dir {output_dir}".split() + cmd = ["torchrun"] + distributed_args + args + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +if __name__ == "__main__": + # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs: + # + # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py + + parser = HfArgumentParser((TrainingArguments,)) + training_args = parser.parse_args_into_dataclasses()[0] + + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " + f"distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}" + ) + + # Essentially, what we want to verify in the distributed case is that we get all samples back, + # in the right order. (this is crucial for prediction for instance) + for dataset_length in [101, 40, 7]: + dataset = DummyDataset(dataset_length) + + def compute_metrics(p: EvalPrediction) -> Dict: + sequential = list(range(len(dataset))) + success = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential + if not success and training_args.local_rank == 0: + logger.warning( + "Predictions and/or labels do not match expected results:\n - predictions: " + f"{p.predictions.tolist()}\n - labels: {p.label_ids.tolist()}\n - expected: {sequential}" + ) + return {"success": success} + + trainer = Trainer( + model=DummyModel(), + args=training_args, + data_collator=DummyDataCollator(), + eval_dataset=dataset, + compute_metrics=compute_metrics, + ) + metrics = trainer.evaluate() + logger.info(metrics) + if metrics["eval_success"] is not True: + logger.error(metrics) + exit(1) + + p = trainer.predict(dataset) + logger.info(p.metrics) + if p.metrics["test_success"] is not True: + logger.error(p.metrics) + exit(1) + + trainer.args.eval_accumulation_steps = 2 + + metrics = trainer.evaluate() + logger.info(metrics) + if metrics["eval_success"] is not True: + logger.error(metrics) + exit(1) + + p = trainer.predict(dataset) + logger.info(p.metrics) + if p.metrics["test_success"] is not True: + logger.error(p.metrics) + exit(1) + + trainer.args.eval_accumulation_steps = None + + # Check that saving does indeed work with temp dir rotation + # If this fails, will see a FileNotFoundError + model = RegressionModel() + training_args.max_steps = 1 + opt = torch.optim.Adam(model.parameters(), lr=1e-3) + sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda x: 1) + trainer = Trainer( + model, training_args, optimizers=(opt, sched), data_collator=DummyDataCollator(), eval_dataset=dataset + ) + trainer._save_checkpoint(model=None, trial=None) + # Check that the temp folder does not exist + assert not (Path(training_args.output_dir) / "tmp-checkpoint-0").exists() + assert (Path(training_args.output_dir) / "checkpoint-0").exists() + + # Check that `dispatch_batches=False` will work on a finite iterable dataset + + train_dataset = FiniteIterableDataset(label_names=["labels", "extra"], length=1) + + model = RegressionModel() + training_args.per_device_train_batch_size = 1 + training_args.max_steps = 1 + training_args.dispatch_batches = False + trainer = Trainer(model, training_args, train_dataset=train_dataset) + trainer.train() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_seq2seq.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_seq2seq.py new file mode 100644 index 0000000000000000000000000000000000000000..3f875e6d36573a9ce0d89c8f1363869af575ee4b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_seq2seq.py @@ -0,0 +1,183 @@ +# coding=utf-8 +# Copyright 2020 the HuggingFace Inc. team. +# +# 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. +from transformers import ( + AutoModelForSeq2SeqLM, + BertTokenizer, + DataCollatorForSeq2Seq, + EncoderDecoderModel, + GenerationConfig, + Seq2SeqTrainer, + Seq2SeqTrainingArguments, + T5Tokenizer, +) +from transformers.testing_utils import TestCasePlus, require_torch, slow +from transformers.utils import is_datasets_available + + +if is_datasets_available(): + import datasets + + +class Seq2seqTrainerTester(TestCasePlus): + @slow + @require_torch + def test_finetune_bert2bert(self): + bert2bert = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny", "prajjwal1/bert-tiny") + tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") + + bert2bert.config.vocab_size = bert2bert.config.encoder.vocab_size + bert2bert.config.eos_token_id = tokenizer.sep_token_id + bert2bert.config.decoder_start_token_id = tokenizer.cls_token_id + bert2bert.config.max_length = 128 + + train_dataset = datasets.load_dataset("cnn_dailymail", "3.0.0", split="train[:1%]") + val_dataset = datasets.load_dataset("cnn_dailymail", "3.0.0", split="validation[:1%]") + + train_dataset = train_dataset.select(range(32)) + val_dataset = val_dataset.select(range(16)) + + batch_size = 4 + + def _map_to_encoder_decoder_inputs(batch): + # Tokenizer will automatically set [BOS] [EOS] + inputs = tokenizer(batch["article"], padding="max_length", truncation=True, max_length=512) + outputs = tokenizer(batch["highlights"], padding="max_length", truncation=True, max_length=128) + batch["input_ids"] = inputs.input_ids + batch["attention_mask"] = inputs.attention_mask + + batch["decoder_input_ids"] = outputs.input_ids + batch["labels"] = outputs.input_ids.copy() + batch["labels"] = [ + [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] + ] + batch["decoder_attention_mask"] = outputs.attention_mask + + assert all(len(x) == 512 for x in inputs.input_ids) + assert all(len(x) == 128 for x in outputs.input_ids) + + return batch + + def _compute_metrics(pred): + labels_ids = pred.label_ids + pred_ids = pred.predictions + + # all unnecessary tokens are removed + pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True) + label_str = tokenizer.batch_decode(labels_ids, skip_special_tokens=True) + + accuracy = sum([int(pred_str[i] == label_str[i]) for i in range(len(pred_str))]) / len(pred_str) + + return {"accuracy": accuracy} + + # map train dataset + train_dataset = train_dataset.map( + _map_to_encoder_decoder_inputs, + batched=True, + batch_size=batch_size, + remove_columns=["article", "highlights"], + ) + train_dataset.set_format( + type="torch", + columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"], + ) + + # same for validation dataset + val_dataset = val_dataset.map( + _map_to_encoder_decoder_inputs, + batched=True, + batch_size=batch_size, + remove_columns=["article", "highlights"], + ) + val_dataset.set_format( + type="torch", + columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"], + ) + + output_dir = self.get_auto_remove_tmp_dir() + + training_args = Seq2SeqTrainingArguments( + output_dir=output_dir, + per_device_train_batch_size=batch_size, + per_device_eval_batch_size=batch_size, + predict_with_generate=True, + evaluation_strategy="steps", + do_train=True, + do_eval=True, + warmup_steps=0, + eval_steps=2, + logging_steps=2, + ) + + # instantiate trainer + trainer = Seq2SeqTrainer( + model=bert2bert, + args=training_args, + compute_metrics=_compute_metrics, + train_dataset=train_dataset, + eval_dataset=val_dataset, + tokenizer=tokenizer, + ) + + # start training + trainer.train() + + @slow + @require_torch + def test_return_sequences(self): + # Tests that the number of generated sequences is correct when num_return_sequences > 1 + # and essentially ensuring that `accelerator.gather()` is used instead of `gather_for_metrics` + INPUT_COLUMN = "question" + TARGET_COLUMN = "answer" + MAX_INPUT_LENGTH = 256 + MAX_TARGET_LENGTH = 256 + + dataset = datasets.load_dataset("gsm8k", "main", split="train[:38]") + model = AutoModelForSeq2SeqLM.from_pretrained("t5-small") + tokenizer = T5Tokenizer.from_pretrained("t5-small") + data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, return_tensors="pt", padding="longest") + gen_config = GenerationConfig.from_pretrained( + "t5-small", max_length=None, min_length=None, max_new_tokens=256, min_new_tokens=1, num_beams=5 + ) + + training_args = Seq2SeqTrainingArguments(".", predict_with_generate=True) + + trainer = Seq2SeqTrainer( + model=model, + args=training_args, + tokenizer=tokenizer, + data_collator=data_collator, + compute_metrics=lambda x: {"samples": x[0].shape[0]}, + ) + + def prepare_data(examples): + # Remove pairs where at least one record is none + inputs = examples[INPUT_COLUMN] + targets = examples[TARGET_COLUMN] + + model_inputs = tokenizer(inputs, max_length=MAX_INPUT_LENGTH, truncation=True) + labels = tokenizer(text_target=targets, max_length=MAX_TARGET_LENGTH, truncation=True) + model_inputs["labels"] = labels["input_ids"] + + return model_inputs + + prepared_dataset = dataset.map(prepare_data, batched=True, remove_columns=[INPUT_COLUMN, TARGET_COLUMN]) + dataset_len = len(prepared_dataset) # 38 + + for num_return_sequences in range(3, 0, -1): + gen_config.num_return_sequences = num_return_sequences + metrics = trainer.evaluate(eval_dataset=prepared_dataset, generation_config=gen_config) + assert ( + metrics["eval_samples"] == dataset_len * num_return_sequences + ), f"Got {metrics['eval_samples']}, expected: {dataset_len * num_return_sequences}" diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_tpu.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_tpu.py new file mode 100644 index 0000000000000000000000000000000000000000..135153fdddd9d758c97486384d198a71696995b2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_tpu.py @@ -0,0 +1,131 @@ +# 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. + +# This test is meant to be run in on an instance with TPUs like this: +# +# python examples/pytorch/xla_spawn.py --num_cores=8 tests/test_trainer_tpu.py +# +# Replace 8 with the number of TPU cores you have. +# + +import sys +from typing import Dict + +from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available +from transformers.utils import logging + + +logger = logging.get_logger(__name__) + + +if is_torch_available(): + import torch + from torch import nn + from torch.utils.data import Dataset + + from transformers import Trainer + + class DummyDataset(Dataset): + def __init__(self, length: int = 101): + self.length = length + + def __len__(self): + return self.length + + def __getitem__(self, i) -> int: + return i + + class DummyDataCollator: + def __call__(self, features): + return {"input_ids": torch.tensor(features), "labels": torch.tensor(features)} + + class DummyModel(nn.Module): + def __init__(self): + super().__init__() + # Add some (unused) params otherwise DDP will complain. + self.fc = nn.Linear(120, 80) + + def forward(self, input_ids, labels=None): + if labels is not None: + return torch.tensor(0.0, device=input_ids.device), input_ids + else: + return input_ids + + +def main(): + parser = HfArgumentParser((TrainingArguments,)) + sys.argv += ["--output_dir", "./examples"] + training_args = parser.parse_args_into_dataclasses()[0] + + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, " + f"tpu_num_cores: {training_args.tpu_num_cores}", + ) + + # Essentially, what we want to verify in the distributed case is + # that we get all samples back, in the right order. + # (this is crucial for prediction for instance) + for dataset_length in [1001, 256, 15]: + dataset = DummyDataset(dataset_length) + + def compute_metrics(p: EvalPrediction) -> Dict: + sequential = list(range(len(dataset))) + success = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential + return {"success": success} + + trainer = Trainer( + model=DummyModel(), + args=training_args, + data_collator=DummyDataCollator(), + eval_dataset=dataset, + compute_metrics=compute_metrics, + ) + metrics = trainer.evaluate() + logger.info(metrics) + if metrics["eval_success"] is not True: + logger.error(metrics) + exit(1) + + p = trainer.predict(dataset) + logger.info(p.metrics) + if p.metrics["test_success"] is not True: + logger.error(p.metrics) + exit(1) + + trainer.args.eval_accumulation_steps = 2 + + metrics = trainer.evaluate() + logger.info(metrics) + if metrics["eval_success"] is not True: + logger.error(metrics) + exit(1) + + p = trainer.predict(dataset) + logger.info(p.metrics) + if p.metrics["test_success"] is not True: + logger.error(p.metrics) + exit(1) + + trainer.args.eval_accumulation_steps = None + + logger.info("🔥 All distributed tests successful") + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf162677e9fce1e1da4a2b1bb7b8ae4fb4555c5 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/trainer/test_trainer_utils.py @@ -0,0 +1,499 @@ +# coding=utf-8 +# Copyright 2018 the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import unittest + +import numpy as np + +from transformers.data.data_collator import default_data_collator +from transformers.testing_utils import require_accelerate, require_torch +from transformers.trainer_utils import RemoveColumnsCollator, find_executable_batch_size +from transformers.utils import is_torch_available + + +if is_torch_available(): + import torch + from torch import nn + from torch.utils.data import IterableDataset + + from transformers.modeling_outputs import SequenceClassifierOutput + from transformers.tokenization_utils_base import BatchEncoding + from transformers.trainer_pt_utils import ( + DistributedLengthGroupedSampler, + DistributedSamplerWithLoop, + DistributedTensorGatherer, + IterableDatasetShard, + LabelSmoother, + LengthGroupedSampler, + SequentialDistributedSampler, + ShardSampler, + get_parameter_names, + numpy_pad_and_concatenate, + torch_pad_and_concatenate, + ) + + class TstLayer(nn.Module): + def __init__(self, hidden_size): + super().__init__() + self.linear1 = nn.Linear(hidden_size, hidden_size) + self.ln1 = nn.LayerNorm(hidden_size) + self.linear2 = nn.Linear(hidden_size, hidden_size) + self.ln2 = nn.LayerNorm(hidden_size) + self.bias = nn.Parameter(torch.zeros(hidden_size)) + + def forward(self, x): + h = self.ln1(nn.functional.relu(self.linear1(x))) + h = nn.functional.relu(self.linear2(x)) + return self.ln2(x + h + self.bias) + + class RandomIterableDataset(IterableDataset): + # For testing, an iterable dataset of random length + def __init__(self, p_stop=0.01, max_length=1000): + self.p_stop = p_stop + self.max_length = max_length + self.generator = torch.Generator() + + def __iter__(self): + count = 0 + stop = False + while not stop and count < self.max_length: + yield count + count += 1 + number = torch.rand(1, generator=self.generator).item() + stop = number < self.p_stop + + +@require_torch +class TrainerUtilsTest(unittest.TestCase): + def test_distributed_tensor_gatherer(self): + # Simulate a result with a dataset of size 21, 4 processes and chunks of lengths 2, 3, 1 + world_size = 4 + num_samples = 21 + input_indices = [ + [0, 1, 6, 7, 12, 13, 18, 19], + [2, 3, 4, 8, 9, 10, 14, 15, 16, 20, 0, 1], + [5, 11, 17, 2], + ] + + predictions = np.random.normal(size=(num_samples, 13)) + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices in input_indices: + gatherer.add_arrays(predictions[indices]) + result = gatherer.finalize() + self.assertTrue(np.array_equal(result, predictions)) + + # With nested tensors + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices in input_indices: + gatherer.add_arrays([predictions[indices], [predictions[indices], predictions[indices]]]) + result = gatherer.finalize() + self.assertTrue(isinstance(result, list)) + self.assertEqual(len(result), 2) + self.assertTrue(isinstance(result[1], list)) + self.assertEqual(len(result[1]), 2) + self.assertTrue(np.array_equal(result[0], predictions)) + self.assertTrue(np.array_equal(result[1][0], predictions)) + self.assertTrue(np.array_equal(result[1][1], predictions)) + + def test_distributed_tensor_gatherer_different_shapes(self): + # Simulate a result with a dataset of size 21, 4 processes and chunks of lengths 2, 3, 1 + world_size = 4 + num_samples = 21 + input_indices = [ + [0, 1, 6, 7, 12, 13, 18, 19], + [2, 3, 4, 8, 9, 10, 14, 15, 16, 20, 0, 1], + [5, 11, 17, 2], + ] + sequence_lengths = [8, 10, 13] + + predictions = np.random.normal(size=(num_samples, 13)) + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices, seq_length in zip(input_indices, sequence_lengths): + gatherer.add_arrays(predictions[indices, :seq_length]) + result = gatherer.finalize() + + # Remove the extra samples added at the end for a round multiple of num processes. + actual_indices = [input_indices[0], input_indices[1][:-2], input_indices[2][:-1]] + for indices, seq_length in zip(actual_indices, sequence_lengths): + self.assertTrue(np.array_equal(result[indices, :seq_length], predictions[indices, :seq_length])) + + # With nested tensors + predictions = np.random.normal(size=(num_samples, 13)) + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices, seq_length in zip(input_indices, sequence_lengths): + gatherer.add_arrays([predictions[indices, :seq_length], predictions[indices]]) + result = gatherer.finalize() + + for indices, seq_length in zip(actual_indices, sequence_lengths): + self.assertTrue(np.array_equal(result[0][indices, :seq_length], predictions[indices, :seq_length])) + self.assertTrue(np.array_equal(result[1], predictions)) + + # Check if works if varying seq_length is second + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices, seq_length in zip(input_indices, sequence_lengths): + gatherer.add_arrays([predictions[indices], predictions[indices, :seq_length]]) + result = gatherer.finalize() + + self.assertTrue(np.array_equal(result[0], predictions)) + for indices, seq_length in zip(actual_indices, sequence_lengths): + self.assertTrue(np.array_equal(result[1][indices, :seq_length], predictions[indices, :seq_length])) + + def test_label_smoothing(self): + epsilon = 0.1 + num_labels = 12 + random_logits = torch.randn(4, 5, num_labels) + random_labels = torch.randint(0, num_labels, (4, 5)) + loss = nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) + model_output = SequenceClassifierOutput(logits=random_logits) + label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) + log_probs = -nn.functional.log_softmax(random_logits, dim=-1) + expected_loss = (1 - epsilon) * loss + epsilon * log_probs.mean() + self.assertTrue(torch.allclose(label_smoothed_loss, expected_loss)) + + # With a few -100 labels + random_labels[0, 1] = -100 + random_labels[2, 1] = -100 + random_labels[2, 3] = -100 + + loss = nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) + model_output = SequenceClassifierOutput(logits=random_logits) + label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) + log_probs = -nn.functional.log_softmax(random_logits, dim=-1) + # Mask the log probs with the -100 labels + log_probs[0, 1] = 0.0 + log_probs[2, 1] = 0.0 + log_probs[2, 3] = 0.0 + expected_loss = (1 - epsilon) * loss + epsilon * log_probs.sum() / (num_labels * 17) + self.assertTrue(torch.allclose(label_smoothed_loss, expected_loss)) + + def test_group_by_length(self): + # Get some inputs of random lengths + lengths = torch.randint(0, 25, (100,)).tolist() + # Put one bigger than the others to check it ends up in first position + lengths[32] = 50 + + indices = list(LengthGroupedSampler(4, lengths=lengths)) + # The biggest element should be first + self.assertEqual(lengths[indices[0]], 50) + # The indices should be a permutation of range(100) + self.assertEqual(sorted(indices), list(range(100))) + + def test_group_by_length_with_dict(self): + # Get some inputs of random lengths + data = [] + for _ in range(6): + input_ids = torch.randint(0, 25, (100,)).tolist() + data.append({"input_ids": input_ids}) + # Put one bigger than the others to check it ends up in first position + data[3]["input_ids"] = torch.randint(0, 25, (105,)).tolist() + + indices = list(LengthGroupedSampler(4, dataset=data)) + # The biggest element should be first + self.assertEqual(len(data[indices[0]]["input_ids"]), 105) + # The indices should be a permutation of range(6) + self.assertEqual(sorted(indices), list(range(6))) + + def test_group_by_length_with_batch_encoding(self): + # Get some inputs of random lengths + data = [] + for _ in range(6): + input_ids = torch.randint(0, 25, (100,)).tolist() + data.append(BatchEncoding({"input_ids": input_ids})) + # Put one bigger than the others to check it ends up in first position + data[3]["input_ids"] = torch.randint(0, 25, (105,)).tolist() + + indices = list(LengthGroupedSampler(4, dataset=data)) + # The biggest element should be first + self.assertEqual(len(data[indices[0]]["input_ids"]), 105) + # The indices should be a permutation of range(6) + self.assertEqual(sorted(indices), list(range(6))) + + def test_distributed_length_grouped(self): + # Get some inputs of random lengths + lengths = torch.randint(0, 25, (100,)).tolist() + # Put one bigger than the others to check it ends up in first position + lengths[32] = 50 + + indices_process_0 = list(DistributedLengthGroupedSampler(4, num_replicas=2, rank=0, lengths=lengths)) + indices_process_1 = list(DistributedLengthGroupedSampler(4, num_replicas=2, rank=1, lengths=lengths)) + # The biggest element should be first + self.assertEqual(lengths[indices_process_0[0]], 50) + # The indices should be a permutation of range(100) + self.assertEqual(sorted(indices_process_0 + indices_process_1), list(range(100))) + + def test_get_parameter_names(self): + model = nn.Sequential(TstLayer(128), nn.ModuleList([TstLayer(128), TstLayer(128)])) + # fmt: off + self.assertEqual( + get_parameter_names(model, [nn.LayerNorm]), + ['0.linear1.weight', '0.linear1.bias', '0.linear2.weight', '0.linear2.bias', '0.bias', '1.0.linear1.weight', '1.0.linear1.bias', '1.0.linear2.weight', '1.0.linear2.bias', '1.0.bias', '1.1.linear1.weight', '1.1.linear1.bias', '1.1.linear2.weight', '1.1.linear2.bias', '1.1.bias'] + ) + # fmt: on + + def test_distributed_sampler_with_loop(self): + batch_size = 16 + for length in [23, 64, 123]: + dataset = list(range(length)) + shard1 = DistributedSamplerWithLoop(dataset, batch_size, num_replicas=2, rank=0) + shard2 = DistributedSamplerWithLoop(dataset, batch_size, num_replicas=2, rank=1) + + # Set seeds + shard1.set_epoch(0) + shard2.set_epoch(0) + + # Sample + samples1 = list(shard1) + samples2 = list(shard2) + + self.assertTrue(len(samples1) % batch_size == 0) + self.assertTrue(len(samples2) % batch_size == 0) + + total = [] + for sample1, sample2 in zip(samples1, samples2): + total += [sample1, sample2] + + self.assertEqual(set(total[:length]), set(dataset)) + self.assertEqual(set(total[length:]), set(total[: (len(total) - length)])) + + def test_sequential_distributed_sampler(self): + batch_size = 16 + for length in [23, 64, 123]: + dataset = list(range(length)) + shard1 = SequentialDistributedSampler(dataset, num_replicas=2, rank=0) + shard2 = SequentialDistributedSampler(dataset, num_replicas=2, rank=1) + + # Sample + samples1 = list(shard1) + samples2 = list(shard2) + + total = samples1 + samples2 + + self.assertListEqual(total[:length], dataset) + self.assertListEqual(total[length:], dataset[: (len(total) - length)]) + + # With a batch_size passed + shard1 = SequentialDistributedSampler(dataset, num_replicas=2, rank=0, batch_size=batch_size) + shard2 = SequentialDistributedSampler(dataset, num_replicas=2, rank=1, batch_size=batch_size) + + # Sample + samples1 = list(shard1) + samples2 = list(shard2) + + self.assertTrue(len(samples1) % batch_size == 0) + self.assertTrue(len(samples2) % batch_size == 0) + + total = samples1 + samples2 + + self.assertListEqual(total[:length], dataset) + self.assertListEqual(total[length:], dataset[: (len(total) - length)]) + + def check_iterable_dataset_shard(self, dataset, batch_size, drop_last, num_processes=2, epoch=0): + # Set the seed for the base dataset to get the proper reference. + dataset.generator.manual_seed(epoch) + reference = list(dataset) + + shards = [ + IterableDatasetShard( + dataset, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i + ) + for i in range(num_processes) + ] + for shard in shards: + shard.set_epoch(epoch) + shard_lists = [list(shard) for shard in shards] + + for shard in shard_lists: + # All shards have a number of samples that is a round multiple of batch size + self.assertTrue(len(shard) % batch_size == 0) + # All shards have the same number of samples + self.assertEqual(len(shard), len(shard_lists[0])) + + for shard in shards: + # All shards know the total number of samples + self.assertEqual(shard.num_examples, len(reference)) + + observed = [] + for idx in range(0, len(shard_lists[0]), batch_size): + for shard in shard_lists: + observed += shard[idx : idx + batch_size] + + # If drop_last is False we loop through samples at the beginning to have a size that is a round multiple of + # batch_size + if not drop_last: + while len(reference) < len(observed): + reference += reference + self.assertListEqual(observed, reference[: len(observed)]) + + # Check equivalence between IterableDataset and ShardSampler + dataset.generator.manual_seed(epoch) + reference = list(dataset) + + sampler_shards = [ + ShardSampler( + reference, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i + ) + for i in range(num_processes) + ] + for shard, sampler_shard in zip(shard_lists, sampler_shards): + self.assertListEqual(shard, list(sampler_shard)) + + def test_iterable_dataset_shard(self): + dataset = RandomIterableDataset() + + self.check_iterable_dataset_shard(dataset, 4, drop_last=True, num_processes=2, epoch=0) + self.check_iterable_dataset_shard(dataset, 4, drop_last=False, num_processes=2, epoch=0) + + self.check_iterable_dataset_shard(dataset, 4, drop_last=True, num_processes=3, epoch=42) + self.check_iterable_dataset_shard(dataset, 4, drop_last=False, num_processes=3, epoch=42) + + def test_iterable_dataset_shard_with_length(self): + sampler_shards = [ + IterableDatasetShard(list(range(100)), batch_size=4, drop_last=True, num_processes=2, process_index=i) + for i in range(2) + ] + + # Build expected shards: each process will have batches of size 4 until there is not enough elements to + # form two full batches (so we stop at 96 = (100 // (4 * 2)) * 4) + expected_shards = [[], []] + current_shard = 0 + for i in range(0, 96, 4): + expected_shards[current_shard].extend(list(range(i, i + 4))) + current_shard = 1 - current_shard + + self.assertListEqual([list(shard) for shard in sampler_shards], expected_shards) + self.assertListEqual([len(shard) for shard in sampler_shards], [len(shard) for shard in expected_shards]) + + sampler_shards = [ + IterableDatasetShard(list(range(100)), batch_size=4, drop_last=False, num_processes=2, process_index=i) + for i in range(2) + ] + # When drop_last=False, we get two last full batches by looping back to the beginning. + expected_shards[0].extend(list(range(96, 100))) + expected_shards[1].extend(list(range(0, 4))) + + self.assertListEqual([list(shard) for shard in sampler_shards], expected_shards) + self.assertListEqual([len(shard) for shard in sampler_shards], [len(shard) for shard in expected_shards]) + + def check_shard_sampler(self, dataset, batch_size, drop_last, num_processes=2): + shards = [ + ShardSampler( + dataset, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i + ) + for i in range(num_processes) + ] + shard_lists = [list(shard) for shard in shards] + + for shard in shard_lists: + # All shards have a number of samples that is a round multiple of batch size + self.assertTrue(len(shard) % batch_size == 0) + # All shards have the same number of samples + self.assertEqual(len(shard), len(shard_lists[0])) + + observed = [] + for idx in range(0, len(shard_lists[0]), batch_size): + for shard in shard_lists: + observed += shard[idx : idx + batch_size] + + # If drop_last is False we loop through samples at the beginning to have a size that is a round multiple of + # batch_size + reference = copy.copy(dataset) + if not drop_last: + while len(reference) < len(observed): + reference += reference + self.assertListEqual(observed, reference[: len(observed)]) + + def test_shard_sampler(self): + for n_elements in [64, 123]: + dataset = list(range(n_elements)) + + self.check_shard_sampler(dataset, 4, drop_last=True, num_processes=2) + self.check_shard_sampler(dataset, 4, drop_last=False, num_processes=2) + + self.check_shard_sampler(dataset, 4, drop_last=True, num_processes=3) + self.check_shard_sampler(dataset, 4, drop_last=False, num_processes=3) + + @require_accelerate + def test_executable_batch_size(self): + batch_sizes = [] + + @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=True) + def mock_training_loop_function(batch_size): + nonlocal batch_sizes + batch_sizes.append(batch_size) + if batch_size > 16: + raise RuntimeError("CUDA out of memory.") + + mock_training_loop_function() + self.assertEqual(batch_sizes, [64, 32, 16]) + + @require_accelerate + def test_executable_batch_size_no_search(self): + batch_sizes = [] + + @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=False) + def mock_training_loop_function(batch_size): + nonlocal batch_sizes + batch_sizes.append(batch_size) + + mock_training_loop_function() + self.assertEqual(batch_sizes, [64]) + + @require_accelerate + def test_executable_batch_size_with_error(self): + @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=False) + def mock_training_loop_function(batch_size): + raise RuntimeError("CUDA out of memory.") + + with self.assertRaises(RuntimeError) as cm: + mock_training_loop_function() + self.assertEqual("CUDA out of memory", cm.args[0]) + + def test_pad_and_concatenate_with_1d(self): + """Tests whether pad_and_concatenate works with scalars.""" + array1 = 1.0 + array2 = 2.0 + result = numpy_pad_and_concatenate(array1, array2) + self.assertTrue(np.array_equal(np.array([1.0, 2.0]), result)) + + tensor1 = torch.tensor(1.0) + tensor2 = torch.tensor(2.0) + result = torch_pad_and_concatenate(tensor1, tensor2) + self.assertTrue(torch.equal(result, torch.Tensor([1.0, 2.0]))) + + def test_remove_columns_collator(self): + class MockLogger: + def __init__(self) -> None: + self.called = 0 + + def info(self, msg): + self.called += 1 + self.last_msg = msg + + data_batch = [ + {"col1": 1, "col2": 2, "col3": 3}, + {"col1": 1, "col2": 2, "col3": 3}, + ] + logger = MockLogger() + remove_columns_collator = RemoveColumnsCollator( + default_data_collator, ["col1", "col2"], logger, "model", "training" + ) + + self.assertNotIn("col3", remove_columns_collator(data_batch)) + # check that the logging message is printed out only once + remove_columns_collator(data_batch) + remove_columns_collator(data_batch) + self.assertEqual(logger.called, 1) + self.assertIn("col3", logger.last_msg) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/__init__.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_activations.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_activations.py new file mode 100644 index 0000000000000000000000000000000000000000..bc203418721075857d4d35f9fdb51bf836375e3b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_activations.py @@ -0,0 +1,74 @@ +# 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 unittest + +from transformers import is_torch_available +from transformers.testing_utils import require_torch + + +if is_torch_available(): + import torch + + from transformers.activations import gelu_new, gelu_python, get_activation + + +@require_torch +class TestActivations(unittest.TestCase): + def test_gelu_versions(self): + x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) + torch_builtin = get_activation("gelu") + self.assertTrue(torch.allclose(gelu_python(x), torch_builtin(x))) + self.assertFalse(torch.allclose(gelu_python(x), gelu_new(x))) + + def test_gelu_10(self): + x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) + torch_builtin = get_activation("gelu") + gelu10 = get_activation("gelu_10") + + y_gelu = torch_builtin(x) + y_gelu_10 = gelu10(x) + + clipped_mask = torch.where(y_gelu_10 < 10.0, 1, 0) + + self.assertTrue(torch.max(y_gelu_10).item() == 10.0) + self.assertTrue(torch.allclose(y_gelu * clipped_mask, y_gelu_10 * clipped_mask)) + + def test_get_activation(self): + get_activation("gelu") + get_activation("gelu_10") + get_activation("gelu_fast") + get_activation("gelu_new") + get_activation("gelu_python") + get_activation("gelu_pytorch_tanh") + get_activation("linear") + get_activation("mish") + get_activation("quick_gelu") + get_activation("relu") + get_activation("sigmoid") + get_activation("silu") + get_activation("swish") + get_activation("tanh") + with self.assertRaises(KeyError): + get_activation("bogus") + with self.assertRaises(KeyError): + get_activation(None) + + def test_activations_are_distinct_objects(self): + act1 = get_activation("gelu") + act1.a = 1 + act2 = get_activation("gelu") + self.assertEqual(act1.a, 1) + with self.assertRaises(AttributeError): + _ = act2.a diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_activations_tf.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_activations_tf.py new file mode 100644 index 0000000000000000000000000000000000000000..8d418d7fe3fc78f8af266b0a27c8489771fea4e2 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_activations_tf.py @@ -0,0 +1,60 @@ +# 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 unittest + +import numpy as np + +from transformers import is_tf_available +from transformers.testing_utils import require_tf + + +if is_tf_available(): + import tensorflow as tf + + from transformers.activations_tf import get_tf_activation + + +@require_tf +class TestTFActivations(unittest.TestCase): + def test_gelu_10(self): + x = tf.constant([-100, -1.0, -0.1, 0, 0.1, 1.0, 100.0]) + gelu = get_tf_activation("gelu") + gelu10 = get_tf_activation("gelu_10") + + y_gelu = gelu(x) + y_gelu_10 = gelu10(x) + + clipped_mask = tf.where(y_gelu_10 < 10.0, 1.0, 0.0) + + self.assertEqual(tf.math.reduce_max(y_gelu_10).numpy().item(), 10.0) + self.assertTrue(np.allclose(y_gelu * clipped_mask, y_gelu_10 * clipped_mask)) + + def test_get_activation(self): + get_tf_activation("gelu") + get_tf_activation("gelu_10") + get_tf_activation("gelu_fast") + get_tf_activation("gelu_new") + get_tf_activation("glu") + get_tf_activation("mish") + get_tf_activation("quick_gelu") + get_tf_activation("relu") + get_tf_activation("sigmoid") + get_tf_activation("silu") + get_tf_activation("swish") + get_tf_activation("tanh") + with self.assertRaises(KeyError): + get_tf_activation("bogus") + with self.assertRaises(KeyError): + get_tf_activation(None) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_add_new_model_like.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_add_new_model_like.py new file mode 100644 index 0000000000000000000000000000000000000000..61ccc184f5519ea956ba4b957ddb21e3ad8fbc5d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_add_new_model_like.py @@ -0,0 +1,1548 @@ +# Copyright 2022 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 os +import re +import tempfile +import unittest +from pathlib import Path + +import transformers +from transformers.commands.add_new_model_like import ( + ModelPatterns, + _re_class_func, + add_content_to_file, + add_content_to_text, + clean_frameworks_in_init, + duplicate_doc_file, + duplicate_module, + filter_framework_files, + find_base_model_checkpoint, + get_model_files, + get_module_from_file, + parse_module_content, + replace_model_patterns, + retrieve_info_for_model, + retrieve_model_classes, + simplify_replacements, +) +from transformers.testing_utils import require_flax, require_tf, require_torch + + +BERT_MODEL_FILES = { + "src/transformers/models/bert/__init__.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/tokenization_bert.py", + "src/transformers/models/bert/tokenization_bert_fast.py", + "src/transformers/models/bert/tokenization_bert_tf.py", + "src/transformers/models/bert/modeling_bert.py", + "src/transformers/models/bert/modeling_flax_bert.py", + "src/transformers/models/bert/modeling_tf_bert.py", + "src/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py", + "src/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py", + "src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py", + "src/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py", +} + +VIT_MODEL_FILES = { + "src/transformers/models/vit/__init__.py", + "src/transformers/models/vit/configuration_vit.py", + "src/transformers/models/vit/convert_dino_to_pytorch.py", + "src/transformers/models/vit/convert_vit_timm_to_pytorch.py", + "src/transformers/models/vit/feature_extraction_vit.py", + "src/transformers/models/vit/image_processing_vit.py", + "src/transformers/models/vit/modeling_vit.py", + "src/transformers/models/vit/modeling_tf_vit.py", + "src/transformers/models/vit/modeling_flax_vit.py", +} + +WAV2VEC2_MODEL_FILES = { + "src/transformers/models/wav2vec2/__init__.py", + "src/transformers/models/wav2vec2/configuration_wav2vec2.py", + "src/transformers/models/wav2vec2/convert_wav2vec2_original_pytorch_checkpoint_to_pytorch.py", + "src/transformers/models/wav2vec2/convert_wav2vec2_original_s3prl_checkpoint_to_pytorch.py", + "src/transformers/models/wav2vec2/feature_extraction_wav2vec2.py", + "src/transformers/models/wav2vec2/modeling_wav2vec2.py", + "src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py", + "src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py", + "src/transformers/models/wav2vec2/processing_wav2vec2.py", + "src/transformers/models/wav2vec2/tokenization_wav2vec2.py", +} + +REPO_PATH = Path(transformers.__path__[0]).parent.parent + + +@require_torch +@require_tf +@require_flax +class TestAddNewModelLike(unittest.TestCase): + def init_file(self, file_name, content): + with open(file_name, "w", encoding="utf-8") as f: + f.write(content) + + def check_result(self, file_name, expected_result): + with open(file_name, "r", encoding="utf-8") as f: + result = f.read() + self.assertEqual(result, expected_result) + + def test_re_class_func(self): + self.assertEqual(_re_class_func.search("def my_function(x, y):").groups()[0], "my_function") + self.assertEqual(_re_class_func.search("class MyClass:").groups()[0], "MyClass") + self.assertEqual(_re_class_func.search("class MyClass(SuperClass):").groups()[0], "MyClass") + + def test_model_patterns_defaults(self): + model_patterns = ModelPatterns("GPT-New new", "huggingface/gpt-new-base") + + self.assertEqual(model_patterns.model_type, "gpt-new-new") + self.assertEqual(model_patterns.model_lower_cased, "gpt_new_new") + self.assertEqual(model_patterns.model_camel_cased, "GPTNewNew") + self.assertEqual(model_patterns.model_upper_cased, "GPT_NEW_NEW") + self.assertEqual(model_patterns.config_class, "GPTNewNewConfig") + self.assertIsNone(model_patterns.tokenizer_class) + self.assertIsNone(model_patterns.feature_extractor_class) + self.assertIsNone(model_patterns.processor_class) + + def test_parse_module_content(self): + test_code = """SOME_CONSTANT = a constant + +CONSTANT_DEFINED_ON_SEVERAL_LINES = [ + first_item, + second_item +] + +def function(args): + some code + +# Copied from transformers.some_module +class SomeClass: + some code +""" + + expected_parts = [ + "SOME_CONSTANT = a constant\n", + "CONSTANT_DEFINED_ON_SEVERAL_LINES = [\n first_item,\n second_item\n]", + "", + "def function(args):\n some code\n", + "# Copied from transformers.some_module\nclass SomeClass:\n some code\n", + ] + self.assertEqual(parse_module_content(test_code), expected_parts) + + def test_add_content_to_text(self): + test_text = """all_configs = { + "gpt": "GPTConfig", + "bert": "BertConfig", + "t5": "T5Config", +}""" + + expected = """all_configs = { + "gpt": "GPTConfig", + "gpt2": "GPT2Config", + "bert": "BertConfig", + "t5": "T5Config", +}""" + line = ' "gpt2": "GPT2Config",' + + self.assertEqual(add_content_to_text(test_text, line, add_before="bert"), expected) + self.assertEqual(add_content_to_text(test_text, line, add_before="bert", exact_match=True), test_text) + self.assertEqual( + add_content_to_text(test_text, line, add_before=' "bert": "BertConfig",', exact_match=True), expected + ) + self.assertEqual(add_content_to_text(test_text, line, add_before=re.compile(r'^\s*"bert":')), expected) + + self.assertEqual(add_content_to_text(test_text, line, add_after="gpt"), expected) + self.assertEqual(add_content_to_text(test_text, line, add_after="gpt", exact_match=True), test_text) + self.assertEqual( + add_content_to_text(test_text, line, add_after=' "gpt": "GPTConfig",', exact_match=True), expected + ) + self.assertEqual(add_content_to_text(test_text, line, add_after=re.compile(r'^\s*"gpt":')), expected) + + def test_add_content_to_file(self): + test_text = """all_configs = { + "gpt": "GPTConfig", + "bert": "BertConfig", + "t5": "T5Config", +}""" + + expected = """all_configs = { + "gpt": "GPTConfig", + "gpt2": "GPT2Config", + "bert": "BertConfig", + "t5": "T5Config", +}""" + line = ' "gpt2": "GPT2Config",' + + with tempfile.TemporaryDirectory() as tmp_dir: + file_name = os.path.join(tmp_dir, "code.py") + + self.init_file(file_name, test_text) + add_content_to_file(file_name, line, add_before="bert") + self.check_result(file_name, expected) + + self.init_file(file_name, test_text) + add_content_to_file(file_name, line, add_before="bert", exact_match=True) + self.check_result(file_name, test_text) + + self.init_file(file_name, test_text) + add_content_to_file(file_name, line, add_before=' "bert": "BertConfig",', exact_match=True) + self.check_result(file_name, expected) + + self.init_file(file_name, test_text) + add_content_to_file(file_name, line, add_before=re.compile(r'^\s*"bert":')) + self.check_result(file_name, expected) + + self.init_file(file_name, test_text) + add_content_to_file(file_name, line, add_after="gpt") + self.check_result(file_name, expected) + + self.init_file(file_name, test_text) + add_content_to_file(file_name, line, add_after="gpt", exact_match=True) + self.check_result(file_name, test_text) + + self.init_file(file_name, test_text) + add_content_to_file(file_name, line, add_after=' "gpt": "GPTConfig",', exact_match=True) + self.check_result(file_name, expected) + + self.init_file(file_name, test_text) + add_content_to_file(file_name, line, add_after=re.compile(r'^\s*"gpt":')) + self.check_result(file_name, expected) + + def test_simplify_replacements(self): + self.assertEqual(simplify_replacements([("Bert", "NewBert")]), [("Bert", "NewBert")]) + self.assertEqual( + simplify_replacements([("Bert", "NewBert"), ("bert", "new-bert")]), + [("Bert", "NewBert"), ("bert", "new-bert")], + ) + self.assertEqual( + simplify_replacements([("BertConfig", "NewBertConfig"), ("Bert", "NewBert"), ("bert", "new-bert")]), + [("Bert", "NewBert"), ("bert", "new-bert")], + ) + + def test_replace_model_patterns(self): + bert_model_patterns = ModelPatterns("Bert", "bert-base-cased") + new_bert_model_patterns = ModelPatterns("New Bert", "huggingface/bert-new-base") + bert_test = '''class TFBertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = BertConfig + load_tf_weights = load_tf_weights_in_bert + base_model_prefix = "bert" + is_parallelizable = True + supports_gradient_checkpointing = True + model_type = "bert" + +BERT_CONSTANT = "value" +''' + bert_expected = '''class TFNewBertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = NewBertConfig + load_tf_weights = load_tf_weights_in_new_bert + base_model_prefix = "new_bert" + is_parallelizable = True + supports_gradient_checkpointing = True + model_type = "new-bert" + +NEW_BERT_CONSTANT = "value" +''' + + bert_converted, replacements = replace_model_patterns(bert_test, bert_model_patterns, new_bert_model_patterns) + self.assertEqual(bert_converted, bert_expected) + # Replacements are empty here since bert as been replaced by bert_new in some instances and bert-new + # in others. + self.assertEqual(replacements, "") + + # If we remove the model type, we will get replacements + bert_test = bert_test.replace(' model_type = "bert"\n', "") + bert_expected = bert_expected.replace(' model_type = "new-bert"\n', "") + bert_converted, replacements = replace_model_patterns(bert_test, bert_model_patterns, new_bert_model_patterns) + self.assertEqual(bert_converted, bert_expected) + self.assertEqual(replacements, "BERT->NEW_BERT,Bert->NewBert,bert->new_bert") + + gpt_model_patterns = ModelPatterns("GPT2", "gpt2") + new_gpt_model_patterns = ModelPatterns("GPT-New new", "huggingface/gpt-new-base") + gpt_test = '''class GPT2PreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = GPT2Config + load_tf_weights = load_tf_weights_in_gpt2 + base_model_prefix = "transformer" + is_parallelizable = True + supports_gradient_checkpointing = True + +GPT2_CONSTANT = "value" +''' + + gpt_expected = '''class GPTNewNewPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = GPTNewNewConfig + load_tf_weights = load_tf_weights_in_gpt_new_new + base_model_prefix = "transformer" + is_parallelizable = True + supports_gradient_checkpointing = True + +GPT_NEW_NEW_CONSTANT = "value" +''' + + gpt_converted, replacements = replace_model_patterns(gpt_test, gpt_model_patterns, new_gpt_model_patterns) + self.assertEqual(gpt_converted, gpt_expected) + # Replacements are empty here since GPT2 as been replaced by GPTNewNew in some instances and GPT_NEW_NEW + # in others. + self.assertEqual(replacements, "") + + roberta_model_patterns = ModelPatterns("RoBERTa", "roberta-base", model_camel_cased="Roberta") + new_roberta_model_patterns = ModelPatterns( + "RoBERTa-New", "huggingface/roberta-new-base", model_camel_cased="RobertaNew" + ) + roberta_test = '''# Copied from transformers.models.bert.BertModel with Bert->Roberta +class RobertaModel(RobertaPreTrainedModel): + """ The base RoBERTa model. """ + checkpoint = roberta-base + base_model_prefix = "roberta" + ''' + roberta_expected = '''# Copied from transformers.models.bert.BertModel with Bert->RobertaNew +class RobertaNewModel(RobertaNewPreTrainedModel): + """ The base RoBERTa-New model. """ + checkpoint = huggingface/roberta-new-base + base_model_prefix = "roberta_new" + ''' + roberta_converted, replacements = replace_model_patterns( + roberta_test, roberta_model_patterns, new_roberta_model_patterns + ) + self.assertEqual(roberta_converted, roberta_expected) + + def test_get_module_from_file(self): + self.assertEqual( + get_module_from_file("/git/transformers/src/transformers/models/bert/modeling_tf_bert.py"), + "transformers.models.bert.modeling_tf_bert", + ) + self.assertEqual( + get_module_from_file("/transformers/models/gpt2/modeling_gpt2.py"), + "transformers.models.gpt2.modeling_gpt2", + ) + with self.assertRaises(ValueError): + get_module_from_file("/models/gpt2/modeling_gpt2.py") + + def test_duplicate_module(self): + bert_model_patterns = ModelPatterns("Bert", "bert-base-cased") + new_bert_model_patterns = ModelPatterns("New Bert", "huggingface/bert-new-base") + bert_test = '''class TFBertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = BertConfig + load_tf_weights = load_tf_weights_in_bert + base_model_prefix = "bert" + is_parallelizable = True + supports_gradient_checkpointing = True + +BERT_CONSTANT = "value" +''' + bert_expected = '''class TFNewBertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = NewBertConfig + load_tf_weights = load_tf_weights_in_new_bert + base_model_prefix = "new_bert" + is_parallelizable = True + supports_gradient_checkpointing = True + +NEW_BERT_CONSTANT = "value" +''' + bert_expected_with_copied_from = ( + "# Copied from transformers.bert_module.TFBertPreTrainedModel with Bert->NewBert,bert->new_bert\n" + + bert_expected + ) + with tempfile.TemporaryDirectory() as tmp_dir: + work_dir = os.path.join(tmp_dir, "transformers") + os.makedirs(work_dir) + file_name = os.path.join(work_dir, "bert_module.py") + dest_file_name = os.path.join(work_dir, "new_bert_module.py") + + self.init_file(file_name, bert_test) + duplicate_module(file_name, bert_model_patterns, new_bert_model_patterns) + self.check_result(dest_file_name, bert_expected_with_copied_from) + + self.init_file(file_name, bert_test) + duplicate_module(file_name, bert_model_patterns, new_bert_model_patterns, add_copied_from=False) + self.check_result(dest_file_name, bert_expected) + + def test_duplicate_module_with_copied_from(self): + bert_model_patterns = ModelPatterns("Bert", "bert-base-cased") + new_bert_model_patterns = ModelPatterns("New Bert", "huggingface/bert-new-base") + bert_test = '''# Copied from transformers.models.xxx.XxxModel with Xxx->Bert +class TFBertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = BertConfig + load_tf_weights = load_tf_weights_in_bert + base_model_prefix = "bert" + is_parallelizable = True + supports_gradient_checkpointing = True + +BERT_CONSTANT = "value" +''' + bert_expected = '''# Copied from transformers.models.xxx.XxxModel with Xxx->NewBert +class TFNewBertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = NewBertConfig + load_tf_weights = load_tf_weights_in_new_bert + base_model_prefix = "new_bert" + is_parallelizable = True + supports_gradient_checkpointing = True + +NEW_BERT_CONSTANT = "value" +''' + with tempfile.TemporaryDirectory() as tmp_dir: + work_dir = os.path.join(tmp_dir, "transformers") + os.makedirs(work_dir) + file_name = os.path.join(work_dir, "bert_module.py") + dest_file_name = os.path.join(work_dir, "new_bert_module.py") + + self.init_file(file_name, bert_test) + duplicate_module(file_name, bert_model_patterns, new_bert_model_patterns) + # There should not be a new Copied from statement, the old one should be adapated. + self.check_result(dest_file_name, bert_expected) + + self.init_file(file_name, bert_test) + duplicate_module(file_name, bert_model_patterns, new_bert_model_patterns, add_copied_from=False) + self.check_result(dest_file_name, bert_expected) + + def test_filter_framework_files(self): + files = ["modeling_bert.py", "modeling_tf_bert.py", "modeling_flax_bert.py", "configuration_bert.py"] + self.assertEqual(filter_framework_files(files), files) + self.assertEqual(set(filter_framework_files(files, ["pt", "tf", "flax"])), set(files)) + + self.assertEqual(set(filter_framework_files(files, ["pt"])), {"modeling_bert.py", "configuration_bert.py"}) + self.assertEqual(set(filter_framework_files(files, ["tf"])), {"modeling_tf_bert.py", "configuration_bert.py"}) + self.assertEqual( + set(filter_framework_files(files, ["flax"])), {"modeling_flax_bert.py", "configuration_bert.py"} + ) + + self.assertEqual( + set(filter_framework_files(files, ["pt", "tf"])), + {"modeling_tf_bert.py", "modeling_bert.py", "configuration_bert.py"}, + ) + self.assertEqual( + set(filter_framework_files(files, ["tf", "flax"])), + {"modeling_tf_bert.py", "modeling_flax_bert.py", "configuration_bert.py"}, + ) + self.assertEqual( + set(filter_framework_files(files, ["pt", "flax"])), + {"modeling_bert.py", "modeling_flax_bert.py", "configuration_bert.py"}, + ) + + def test_get_model_files(self): + # BERT + bert_files = get_model_files("bert") + + doc_file = str(Path(bert_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/bert.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in bert_files["model_files"]} + self.assertEqual(model_files, BERT_MODEL_FILES) + + self.assertEqual(bert_files["module_name"], "bert") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in bert_files["test_files"]} + bert_test_files = { + "tests/models/bert/test_tokenization_bert.py", + "tests/models/bert/test_modeling_bert.py", + "tests/models/bert/test_modeling_tf_bert.py", + "tests/models/bert/test_modeling_flax_bert.py", + } + self.assertEqual(test_files, bert_test_files) + + # VIT + vit_files = get_model_files("vit") + doc_file = str(Path(vit_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/vit.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in vit_files["model_files"]} + self.assertEqual(model_files, VIT_MODEL_FILES) + + self.assertEqual(vit_files["module_name"], "vit") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in vit_files["test_files"]} + vit_test_files = { + "tests/models/vit/test_image_processing_vit.py", + "tests/models/vit/test_modeling_vit.py", + "tests/models/vit/test_modeling_tf_vit.py", + "tests/models/vit/test_modeling_flax_vit.py", + } + self.assertEqual(test_files, vit_test_files) + + # Wav2Vec2 + wav2vec2_files = get_model_files("wav2vec2") + doc_file = str(Path(wav2vec2_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/wav2vec2.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in wav2vec2_files["model_files"]} + self.assertEqual(model_files, WAV2VEC2_MODEL_FILES) + + self.assertEqual(wav2vec2_files["module_name"], "wav2vec2") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in wav2vec2_files["test_files"]} + wav2vec2_test_files = { + "tests/models/wav2vec2/test_feature_extraction_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_tf_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_flax_wav2vec2.py", + "tests/models/wav2vec2/test_processor_wav2vec2.py", + "tests/models/wav2vec2/test_tokenization_wav2vec2.py", + } + self.assertEqual(test_files, wav2vec2_test_files) + + def test_get_model_files_only_pt(self): + # BERT + bert_files = get_model_files("bert", frameworks=["pt"]) + + doc_file = str(Path(bert_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/bert.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in bert_files["model_files"]} + bert_model_files = BERT_MODEL_FILES - { + "src/transformers/models/bert/modeling_tf_bert.py", + "src/transformers/models/bert/modeling_flax_bert.py", + } + self.assertEqual(model_files, bert_model_files) + + self.assertEqual(bert_files["module_name"], "bert") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in bert_files["test_files"]} + bert_test_files = { + "tests/models/bert/test_tokenization_bert.py", + "tests/models/bert/test_modeling_bert.py", + } + self.assertEqual(test_files, bert_test_files) + + # VIT + vit_files = get_model_files("vit", frameworks=["pt"]) + doc_file = str(Path(vit_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/vit.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in vit_files["model_files"]} + vit_model_files = VIT_MODEL_FILES - { + "src/transformers/models/vit/modeling_tf_vit.py", + "src/transformers/models/vit/modeling_flax_vit.py", + } + self.assertEqual(model_files, vit_model_files) + + self.assertEqual(vit_files["module_name"], "vit") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in vit_files["test_files"]} + vit_test_files = { + "tests/models/vit/test_image_processing_vit.py", + "tests/models/vit/test_modeling_vit.py", + } + self.assertEqual(test_files, vit_test_files) + + # Wav2Vec2 + wav2vec2_files = get_model_files("wav2vec2", frameworks=["pt"]) + doc_file = str(Path(wav2vec2_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/wav2vec2.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in wav2vec2_files["model_files"]} + wav2vec2_model_files = WAV2VEC2_MODEL_FILES - { + "src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py", + "src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py", + } + self.assertEqual(model_files, wav2vec2_model_files) + + self.assertEqual(wav2vec2_files["module_name"], "wav2vec2") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in wav2vec2_files["test_files"]} + wav2vec2_test_files = { + "tests/models/wav2vec2/test_feature_extraction_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_wav2vec2.py", + "tests/models/wav2vec2/test_processor_wav2vec2.py", + "tests/models/wav2vec2/test_tokenization_wav2vec2.py", + } + self.assertEqual(test_files, wav2vec2_test_files) + + def test_get_model_files_tf_and_flax(self): + # BERT + bert_files = get_model_files("bert", frameworks=["tf", "flax"]) + + doc_file = str(Path(bert_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/bert.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in bert_files["model_files"]} + bert_model_files = BERT_MODEL_FILES - {"src/transformers/models/bert/modeling_bert.py"} + self.assertEqual(model_files, bert_model_files) + + self.assertEqual(bert_files["module_name"], "bert") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in bert_files["test_files"]} + bert_test_files = { + "tests/models/bert/test_tokenization_bert.py", + "tests/models/bert/test_modeling_tf_bert.py", + "tests/models/bert/test_modeling_flax_bert.py", + } + self.assertEqual(test_files, bert_test_files) + + # VIT + vit_files = get_model_files("vit", frameworks=["tf", "flax"]) + doc_file = str(Path(vit_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/vit.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in vit_files["model_files"]} + vit_model_files = VIT_MODEL_FILES - {"src/transformers/models/vit/modeling_vit.py"} + self.assertEqual(model_files, vit_model_files) + + self.assertEqual(vit_files["module_name"], "vit") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in vit_files["test_files"]} + vit_test_files = { + "tests/models/vit/test_image_processing_vit.py", + "tests/models/vit/test_modeling_tf_vit.py", + "tests/models/vit/test_modeling_flax_vit.py", + } + self.assertEqual(test_files, vit_test_files) + + # Wav2Vec2 + wav2vec2_files = get_model_files("wav2vec2", frameworks=["tf", "flax"]) + doc_file = str(Path(wav2vec2_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/wav2vec2.md") + + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in wav2vec2_files["model_files"]} + wav2vec2_model_files = WAV2VEC2_MODEL_FILES - {"src/transformers/models/wav2vec2/modeling_wav2vec2.py"} + self.assertEqual(model_files, wav2vec2_model_files) + + self.assertEqual(wav2vec2_files["module_name"], "wav2vec2") + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in wav2vec2_files["test_files"]} + wav2vec2_test_files = { + "tests/models/wav2vec2/test_feature_extraction_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_tf_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_flax_wav2vec2.py", + "tests/models/wav2vec2/test_processor_wav2vec2.py", + "tests/models/wav2vec2/test_tokenization_wav2vec2.py", + } + self.assertEqual(test_files, wav2vec2_test_files) + + def test_find_base_model_checkpoint(self): + self.assertEqual(find_base_model_checkpoint("bert"), "bert-base-uncased") + self.assertEqual(find_base_model_checkpoint("gpt2"), "gpt2") + + def test_retrieve_model_classes(self): + gpt_classes = {k: set(v) for k, v in retrieve_model_classes("gpt2").items()} + expected_gpt_classes = { + "pt": {"GPT2ForTokenClassification", "GPT2Model", "GPT2LMHeadModel", "GPT2ForSequenceClassification"}, + "tf": {"TFGPT2Model", "TFGPT2ForSequenceClassification", "TFGPT2LMHeadModel"}, + "flax": {"FlaxGPT2Model", "FlaxGPT2LMHeadModel"}, + } + self.assertEqual(gpt_classes, expected_gpt_classes) + + del expected_gpt_classes["flax"] + gpt_classes = {k: set(v) for k, v in retrieve_model_classes("gpt2", frameworks=["pt", "tf"]).items()} + self.assertEqual(gpt_classes, expected_gpt_classes) + + del expected_gpt_classes["pt"] + gpt_classes = {k: set(v) for k, v in retrieve_model_classes("gpt2", frameworks=["tf"]).items()} + self.assertEqual(gpt_classes, expected_gpt_classes) + + def test_retrieve_info_for_model_with_bert(self): + bert_info = retrieve_info_for_model("bert") + bert_classes = [ + "BertForTokenClassification", + "BertForQuestionAnswering", + "BertForNextSentencePrediction", + "BertForSequenceClassification", + "BertForMaskedLM", + "BertForMultipleChoice", + "BertModel", + "BertForPreTraining", + "BertLMHeadModel", + ] + expected_model_classes = { + "pt": set(bert_classes), + "tf": {f"TF{m}" for m in bert_classes}, + "flax": {f"Flax{m}" for m in bert_classes[:-1] + ["BertForCausalLM"]}, + } + + self.assertEqual(set(bert_info["frameworks"]), {"pt", "tf", "flax"}) + model_classes = {k: set(v) for k, v in bert_info["model_classes"].items()} + self.assertEqual(model_classes, expected_model_classes) + + all_bert_files = bert_info["model_files"] + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in all_bert_files["model_files"]} + self.assertEqual(model_files, BERT_MODEL_FILES) + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in all_bert_files["test_files"]} + bert_test_files = { + "tests/models/bert/test_tokenization_bert.py", + "tests/models/bert/test_modeling_bert.py", + "tests/models/bert/test_modeling_tf_bert.py", + "tests/models/bert/test_modeling_flax_bert.py", + } + self.assertEqual(test_files, bert_test_files) + + doc_file = str(Path(all_bert_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/bert.md") + + self.assertEqual(all_bert_files["module_name"], "bert") + + bert_model_patterns = bert_info["model_patterns"] + self.assertEqual(bert_model_patterns.model_name, "BERT") + self.assertEqual(bert_model_patterns.checkpoint, "bert-base-uncased") + self.assertEqual(bert_model_patterns.model_type, "bert") + self.assertEqual(bert_model_patterns.model_lower_cased, "bert") + self.assertEqual(bert_model_patterns.model_camel_cased, "Bert") + self.assertEqual(bert_model_patterns.model_upper_cased, "BERT") + self.assertEqual(bert_model_patterns.config_class, "BertConfig") + self.assertEqual(bert_model_patterns.tokenizer_class, "BertTokenizer") + self.assertIsNone(bert_model_patterns.feature_extractor_class) + self.assertIsNone(bert_model_patterns.processor_class) + + def test_retrieve_info_for_model_pt_tf_with_bert(self): + bert_info = retrieve_info_for_model("bert", frameworks=["pt", "tf"]) + bert_classes = [ + "BertForTokenClassification", + "BertForQuestionAnswering", + "BertForNextSentencePrediction", + "BertForSequenceClassification", + "BertForMaskedLM", + "BertForMultipleChoice", + "BertModel", + "BertForPreTraining", + "BertLMHeadModel", + ] + expected_model_classes = {"pt": set(bert_classes), "tf": {f"TF{m}" for m in bert_classes}} + + self.assertEqual(set(bert_info["frameworks"]), {"pt", "tf"}) + model_classes = {k: set(v) for k, v in bert_info["model_classes"].items()} + self.assertEqual(model_classes, expected_model_classes) + + all_bert_files = bert_info["model_files"] + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in all_bert_files["model_files"]} + bert_model_files = BERT_MODEL_FILES - {"src/transformers/models/bert/modeling_flax_bert.py"} + self.assertEqual(model_files, bert_model_files) + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in all_bert_files["test_files"]} + bert_test_files = { + "tests/models/bert/test_tokenization_bert.py", + "tests/models/bert/test_modeling_bert.py", + "tests/models/bert/test_modeling_tf_bert.py", + } + self.assertEqual(test_files, bert_test_files) + + doc_file = str(Path(all_bert_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/bert.md") + + self.assertEqual(all_bert_files["module_name"], "bert") + + bert_model_patterns = bert_info["model_patterns"] + self.assertEqual(bert_model_patterns.model_name, "BERT") + self.assertEqual(bert_model_patterns.checkpoint, "bert-base-uncased") + self.assertEqual(bert_model_patterns.model_type, "bert") + self.assertEqual(bert_model_patterns.model_lower_cased, "bert") + self.assertEqual(bert_model_patterns.model_camel_cased, "Bert") + self.assertEqual(bert_model_patterns.model_upper_cased, "BERT") + self.assertEqual(bert_model_patterns.config_class, "BertConfig") + self.assertEqual(bert_model_patterns.tokenizer_class, "BertTokenizer") + self.assertIsNone(bert_model_patterns.feature_extractor_class) + self.assertIsNone(bert_model_patterns.processor_class) + + def test_retrieve_info_for_model_with_vit(self): + vit_info = retrieve_info_for_model("vit") + vit_classes = ["ViTForImageClassification", "ViTModel"] + pt_only_classes = ["ViTForMaskedImageModeling"] + expected_model_classes = { + "pt": set(vit_classes + pt_only_classes), + "tf": {f"TF{m}" for m in vit_classes}, + "flax": {f"Flax{m}" for m in vit_classes}, + } + + self.assertEqual(set(vit_info["frameworks"]), {"pt", "tf", "flax"}) + model_classes = {k: set(v) for k, v in vit_info["model_classes"].items()} + self.assertEqual(model_classes, expected_model_classes) + + all_vit_files = vit_info["model_files"] + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in all_vit_files["model_files"]} + self.assertEqual(model_files, VIT_MODEL_FILES) + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in all_vit_files["test_files"]} + vit_test_files = { + "tests/models/vit/test_image_processing_vit.py", + "tests/models/vit/test_modeling_vit.py", + "tests/models/vit/test_modeling_tf_vit.py", + "tests/models/vit/test_modeling_flax_vit.py", + } + self.assertEqual(test_files, vit_test_files) + + doc_file = str(Path(all_vit_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/vit.md") + + self.assertEqual(all_vit_files["module_name"], "vit") + + vit_model_patterns = vit_info["model_patterns"] + self.assertEqual(vit_model_patterns.model_name, "ViT") + self.assertEqual(vit_model_patterns.checkpoint, "google/vit-base-patch16-224-in21k") + self.assertEqual(vit_model_patterns.model_type, "vit") + self.assertEqual(vit_model_patterns.model_lower_cased, "vit") + self.assertEqual(vit_model_patterns.model_camel_cased, "ViT") + self.assertEqual(vit_model_patterns.model_upper_cased, "VIT") + self.assertEqual(vit_model_patterns.config_class, "ViTConfig") + self.assertEqual(vit_model_patterns.feature_extractor_class, "ViTFeatureExtractor") + self.assertEqual(vit_model_patterns.image_processor_class, "ViTImageProcessor") + self.assertIsNone(vit_model_patterns.tokenizer_class) + self.assertIsNone(vit_model_patterns.processor_class) + + def test_retrieve_info_for_model_with_wav2vec2(self): + wav2vec2_info = retrieve_info_for_model("wav2vec2") + wav2vec2_classes = [ + "Wav2Vec2Model", + "Wav2Vec2ForPreTraining", + "Wav2Vec2ForAudioFrameClassification", + "Wav2Vec2ForCTC", + "Wav2Vec2ForMaskedLM", + "Wav2Vec2ForSequenceClassification", + "Wav2Vec2ForXVector", + ] + expected_model_classes = { + "pt": set(wav2vec2_classes), + "tf": {f"TF{m}" for m in wav2vec2_classes[:1]}, + "flax": {f"Flax{m}" for m in wav2vec2_classes[:2]}, + } + + self.assertEqual(set(wav2vec2_info["frameworks"]), {"pt", "tf", "flax"}) + model_classes = {k: set(v) for k, v in wav2vec2_info["model_classes"].items()} + self.assertEqual(model_classes, expected_model_classes) + + all_wav2vec2_files = wav2vec2_info["model_files"] + model_files = {str(Path(f).relative_to(REPO_PATH)) for f in all_wav2vec2_files["model_files"]} + self.assertEqual(model_files, WAV2VEC2_MODEL_FILES) + + test_files = {str(Path(f).relative_to(REPO_PATH)) for f in all_wav2vec2_files["test_files"]} + wav2vec2_test_files = { + "tests/models/wav2vec2/test_feature_extraction_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_tf_wav2vec2.py", + "tests/models/wav2vec2/test_modeling_flax_wav2vec2.py", + "tests/models/wav2vec2/test_processor_wav2vec2.py", + "tests/models/wav2vec2/test_tokenization_wav2vec2.py", + } + self.assertEqual(test_files, wav2vec2_test_files) + + doc_file = str(Path(all_wav2vec2_files["doc_file"]).relative_to(REPO_PATH)) + self.assertEqual(doc_file, "docs/source/en/model_doc/wav2vec2.md") + + self.assertEqual(all_wav2vec2_files["module_name"], "wav2vec2") + + wav2vec2_model_patterns = wav2vec2_info["model_patterns"] + self.assertEqual(wav2vec2_model_patterns.model_name, "Wav2Vec2") + self.assertEqual(wav2vec2_model_patterns.checkpoint, "facebook/wav2vec2-base-960h") + self.assertEqual(wav2vec2_model_patterns.model_type, "wav2vec2") + self.assertEqual(wav2vec2_model_patterns.model_lower_cased, "wav2vec2") + self.assertEqual(wav2vec2_model_patterns.model_camel_cased, "Wav2Vec2") + self.assertEqual(wav2vec2_model_patterns.model_upper_cased, "WAV_2_VEC_2") + self.assertEqual(wav2vec2_model_patterns.config_class, "Wav2Vec2Config") + self.assertEqual(wav2vec2_model_patterns.feature_extractor_class, "Wav2Vec2FeatureExtractor") + self.assertEqual(wav2vec2_model_patterns.processor_class, "Wav2Vec2Processor") + self.assertEqual(wav2vec2_model_patterns.tokenizer_class, "Wav2Vec2CTCTokenizer") + + def test_clean_frameworks_in_init_with_gpt(self): + test_init = """ +from typing import TYPE_CHECKING + +from ...utils import _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available + +_import_structure = { + "configuration_gpt2": ["GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPT2Config", "GPT2OnnxConfig"], + "tokenization_gpt2": ["GPT2Tokenizer"], +} + +try: + if not is_tokenizers_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["tokenization_gpt2_fast"] = ["GPT2TokenizerFast"] + +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_gpt2"] = ["GPT2Model"] + +try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_tf_gpt2"] = ["TFGPT2Model"] + +try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_flax_gpt2"] = ["FlaxGPT2Model"] + +if TYPE_CHECKING: + from .configuration_gpt2 import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2Config, GPT2OnnxConfig + from .tokenization_gpt2 import GPT2Tokenizer + + try: + if not is_tokenizers_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .tokenization_gpt2_fast import GPT2TokenizerFast + + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_gpt2 import GPT2Model + + try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_tf_gpt2 import TFGPT2Model + + try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_flax_gpt2 import FlaxGPT2Model + +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure) +""" + + init_no_tokenizer = """ +from typing import TYPE_CHECKING + +from ...utils import _LazyModule, is_flax_available, is_tf_available, is_torch_available + +_import_structure = { + "configuration_gpt2": ["GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPT2Config", "GPT2OnnxConfig"], +} + +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_gpt2"] = ["GPT2Model"] + +try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_tf_gpt2"] = ["TFGPT2Model"] + +try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_flax_gpt2"] = ["FlaxGPT2Model"] + +if TYPE_CHECKING: + from .configuration_gpt2 import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2Config, GPT2OnnxConfig + + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_gpt2 import GPT2Model + + try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_tf_gpt2 import TFGPT2Model + + try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_flax_gpt2 import FlaxGPT2Model + +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure) +""" + + init_pt_only = """ +from typing import TYPE_CHECKING + +from ...utils import _LazyModule, is_tokenizers_available, is_torch_available + +_import_structure = { + "configuration_gpt2": ["GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPT2Config", "GPT2OnnxConfig"], + "tokenization_gpt2": ["GPT2Tokenizer"], +} + +try: + if not is_tokenizers_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["tokenization_gpt2_fast"] = ["GPT2TokenizerFast"] + +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_gpt2"] = ["GPT2Model"] + +if TYPE_CHECKING: + from .configuration_gpt2 import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2Config, GPT2OnnxConfig + from .tokenization_gpt2 import GPT2Tokenizer + + try: + if not is_tokenizers_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .tokenization_gpt2_fast import GPT2TokenizerFast + + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_gpt2 import GPT2Model + +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure) +""" + + init_pt_only_no_tokenizer = """ +from typing import TYPE_CHECKING + +from ...utils import _LazyModule, is_torch_available + +_import_structure = { + "configuration_gpt2": ["GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPT2Config", "GPT2OnnxConfig"], +} + +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_gpt2"] = ["GPT2Model"] + +if TYPE_CHECKING: + from .configuration_gpt2 import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2Config, GPT2OnnxConfig + + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_gpt2 import GPT2Model + +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure) +""" + + with tempfile.TemporaryDirectory() as tmp_dir: + file_name = os.path.join(tmp_dir, "../__init__.py") + + self.init_file(file_name, test_init) + clean_frameworks_in_init(file_name, keep_processing=False) + self.check_result(file_name, init_no_tokenizer) + + self.init_file(file_name, test_init) + clean_frameworks_in_init(file_name, frameworks=["pt"]) + self.check_result(file_name, init_pt_only) + + self.init_file(file_name, test_init) + clean_frameworks_in_init(file_name, frameworks=["pt"], keep_processing=False) + self.check_result(file_name, init_pt_only_no_tokenizer) + + def test_clean_frameworks_in_init_with_vit(self): + test_init = """ +from typing import TYPE_CHECKING + +from ...utils import _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available + +_import_structure = { + "configuration_vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig"], +} + +try: + if not is_vision_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["image_processing_vit"] = ["ViTImageProcessor"] + +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_vit"] = ["ViTModel"] + +try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_tf_vit"] = ["TFViTModel"] + +try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_flax_vit"] = ["FlaxViTModel"] + +if TYPE_CHECKING: + from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig + + try: + if not is_vision_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .image_processing_vit import ViTImageProcessor + + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_vit import ViTModel + + try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_tf_vit import TFViTModel + + try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_flax_vit import FlaxViTModel + +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure) +""" + + init_no_feature_extractor = """ +from typing import TYPE_CHECKING + +from ...utils import _LazyModule, is_flax_available, is_tf_available, is_torch_available + +_import_structure = { + "configuration_vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig"], +} + +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_vit"] = ["ViTModel"] + +try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_tf_vit"] = ["TFViTModel"] + +try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_flax_vit"] = ["FlaxViTModel"] + +if TYPE_CHECKING: + from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig + + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_vit import ViTModel + + try: + if not is_tf_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_tf_vit import TFViTModel + + try: + if not is_flax_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_flax_vit import FlaxViTModel + +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure) +""" + + init_pt_only = """ +from typing import TYPE_CHECKING + +from ...utils import _LazyModule, is_torch_available, is_vision_available + +_import_structure = { + "configuration_vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig"], +} + +try: + if not is_vision_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["image_processing_vit"] = ["ViTImageProcessor"] + +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_vit"] = ["ViTModel"] + +if TYPE_CHECKING: + from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig + + try: + if not is_vision_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .image_processing_vit import ViTImageProcessor + + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_vit import ViTModel + +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure) +""" + + init_pt_only_no_feature_extractor = """ +from typing import TYPE_CHECKING + +from ...utils import _LazyModule, is_torch_available + +_import_structure = { + "configuration_vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig"], +} + +try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + pass +else: + _import_structure["modeling_vit"] = ["ViTModel"] + +if TYPE_CHECKING: + from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig + + try: + if not is_torch_available(): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + pass + else: + from .modeling_vit import ViTModel + +else: + import sys + + sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure) +""" + + with tempfile.TemporaryDirectory() as tmp_dir: + file_name = os.path.join(tmp_dir, "../__init__.py") + + self.init_file(file_name, test_init) + clean_frameworks_in_init(file_name, keep_processing=False) + self.check_result(file_name, init_no_feature_extractor) + + self.init_file(file_name, test_init) + clean_frameworks_in_init(file_name, frameworks=["pt"]) + self.check_result(file_name, init_pt_only) + + self.init_file(file_name, test_init) + clean_frameworks_in_init(file_name, frameworks=["pt"], keep_processing=False) + self.check_result(file_name, init_pt_only_no_feature_extractor) + + def test_duplicate_doc_file(self): + test_doc = """ +# GPT2 + +## Overview + +Overview of the model. + +## GPT2Config + +[[autodoc]] GPT2Config + +## GPT2Tokenizer + +[[autodoc]] GPT2Tokenizer + - save_vocabulary + +## GPT2TokenizerFast + +[[autodoc]] GPT2TokenizerFast + +## GPT2 specific outputs + +[[autodoc]] models.gpt2.modeling_gpt2.GPT2DoubleHeadsModelOutput + +[[autodoc]] models.gpt2.modeling_tf_gpt2.TFGPT2DoubleHeadsModelOutput + +## GPT2Model + +[[autodoc]] GPT2Model + - forward + +## TFGPT2Model + +[[autodoc]] TFGPT2Model + - call + +## FlaxGPT2Model + +[[autodoc]] FlaxGPT2Model + - __call__ + +""" + test_new_doc = """ +# GPT-New New + +## Overview + +The GPT-New New model was proposed in []() by . + + +The abstract from the paper is the following: + +** + +Tips: + + + +This model was contributed by [INSERT YOUR HF USERNAME HERE](https://huggingface.co/). +The original code can be found [here](). + + +## GPTNewNewConfig + +[[autodoc]] GPTNewNewConfig + +## GPTNewNewTokenizer + +[[autodoc]] GPTNewNewTokenizer + - save_vocabulary + +## GPTNewNewTokenizerFast + +[[autodoc]] GPTNewNewTokenizerFast + +## GPTNewNew specific outputs + +[[autodoc]] models.gpt_new_new.modeling_gpt_new_new.GPTNewNewDoubleHeadsModelOutput + +[[autodoc]] models.gpt_new_new.modeling_tf_gpt_new_new.TFGPTNewNewDoubleHeadsModelOutput + +## GPTNewNewModel + +[[autodoc]] GPTNewNewModel + - forward + +## TFGPTNewNewModel + +[[autodoc]] TFGPTNewNewModel + - call + +## FlaxGPTNewNewModel + +[[autodoc]] FlaxGPTNewNewModel + - __call__ + +""" + + with tempfile.TemporaryDirectory() as tmp_dir: + doc_file = os.path.join(tmp_dir, "gpt2.md") + new_doc_file = os.path.join(tmp_dir, "gpt-new-new.md") + + gpt2_model_patterns = ModelPatterns("GPT2", "gpt2", tokenizer_class="GPT2Tokenizer") + new_model_patterns = ModelPatterns( + "GPT-New New", "huggingface/gpt-new-new", tokenizer_class="GPTNewNewTokenizer" + ) + + self.init_file(doc_file, test_doc) + duplicate_doc_file(doc_file, gpt2_model_patterns, new_model_patterns) + self.check_result(new_doc_file, test_new_doc) + + test_new_doc_pt_only = test_new_doc.replace( + """ +## TFGPTNewNewModel + +[[autodoc]] TFGPTNewNewModel + - call + +## FlaxGPTNewNewModel + +[[autodoc]] FlaxGPTNewNewModel + - __call__ + +""", + "", + ) + self.init_file(doc_file, test_doc) + duplicate_doc_file(doc_file, gpt2_model_patterns, new_model_patterns, frameworks=["pt"]) + self.check_result(new_doc_file, test_new_doc_pt_only) + + test_new_doc_no_tok = test_new_doc.replace( + """ +## GPTNewNewTokenizer + +[[autodoc]] GPTNewNewTokenizer + - save_vocabulary + +## GPTNewNewTokenizerFast + +[[autodoc]] GPTNewNewTokenizerFast +""", + "", + ) + new_model_patterns = ModelPatterns( + "GPT-New New", "huggingface/gpt-new-new", tokenizer_class="GPT2Tokenizer" + ) + self.init_file(doc_file, test_doc) + duplicate_doc_file(doc_file, gpt2_model_patterns, new_model_patterns) + print(test_new_doc_no_tok) + self.check_result(new_doc_file, test_new_doc_no_tok) + + test_new_doc_pt_only_no_tok = test_new_doc_no_tok.replace( + """ +## TFGPTNewNewModel + +[[autodoc]] TFGPTNewNewModel + - call + +## FlaxGPTNewNewModel + +[[autodoc]] FlaxGPTNewNewModel + - __call__ + +""", + "", + ) + self.init_file(doc_file, test_doc) + duplicate_doc_file(doc_file, gpt2_model_patterns, new_model_patterns, frameworks=["pt"]) + self.check_result(new_doc_file, test_new_doc_pt_only_no_tok) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_audio_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_audio_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..12d00929a969bd0a1ea9e258c1c7a552bfb317f3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_audio_utils.py @@ -0,0 +1,757 @@ +# coding=utf-8 +# Copyright 2023 HuggingFace Inc. +# +# 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 unittest + +import numpy as np +import pytest + +from transformers.audio_utils import ( + amplitude_to_db, + hertz_to_mel, + mel_filter_bank, + mel_to_hertz, + power_to_db, + spectrogram, + window_function, +) + + +class AudioUtilsFunctionTester(unittest.TestCase): + def test_hertz_to_mel(self): + self.assertEqual(hertz_to_mel(0.0), 0.0) + self.assertAlmostEqual(hertz_to_mel(100), 150.48910241) + + inputs = np.array([100, 200]) + expected = np.array([150.48910241, 283.22989816]) + self.assertTrue(np.allclose(hertz_to_mel(inputs), expected)) + + self.assertEqual(hertz_to_mel(0.0, "slaney"), 0.0) + self.assertEqual(hertz_to_mel(100, "slaney"), 1.5) + + inputs = np.array([60, 100, 200, 1000, 1001, 2000]) + expected = np.array([0.9, 1.5, 3.0, 15.0, 15.01453781, 25.08188016]) + self.assertTrue(np.allclose(hertz_to_mel(inputs, "slaney"), expected)) + + inputs = np.array([60, 100, 200, 1000, 1001, 2000]) + expected = np.array([92.6824, 150.4899, 283.2313, 999.9907, 1000.6534, 1521.3674]) + self.assertTrue(np.allclose(hertz_to_mel(inputs, "kaldi"), expected)) + + with pytest.raises(ValueError): + hertz_to_mel(100, mel_scale=None) + + def test_mel_to_hertz(self): + self.assertEqual(mel_to_hertz(0.0), 0.0) + self.assertAlmostEqual(mel_to_hertz(150.48910241), 100) + + inputs = np.array([150.48910241, 283.22989816]) + expected = np.array([100, 200]) + self.assertTrue(np.allclose(mel_to_hertz(inputs), expected)) + + self.assertEqual(mel_to_hertz(0.0, "slaney"), 0.0) + self.assertEqual(mel_to_hertz(1.5, "slaney"), 100) + + inputs = np.array([0.9, 1.5, 3.0, 15.0, 15.01453781, 25.08188016]) + expected = np.array([60, 100, 200, 1000, 1001, 2000]) + self.assertTrue(np.allclose(mel_to_hertz(inputs, "slaney"), expected)) + + inputs = np.array([92.6824, 150.4899, 283.2313, 999.9907, 1000.6534, 1521.3674]) + expected = np.array([60, 100, 200, 1000, 1001, 2000]) + self.assertTrue(np.allclose(mel_to_hertz(inputs, "kaldi"), expected)) + + with pytest.raises(ValueError): + mel_to_hertz(100, mel_scale=None) + + def test_mel_filter_bank_shape(self): + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm=None, + mel_scale="htk", + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm="slaney", + mel_scale="slaney", + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm="slaney", + mel_scale="slaney", + triangularize_in_mel_space=True, + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + def test_mel_filter_bank_htk(self): + mel_filters = mel_filter_bank( + num_frequency_bins=16, + num_mel_filters=4, + min_frequency=0, + max_frequency=2000, + sampling_rate=4000, + norm=None, + mel_scale="htk", + ) + # fmt: off + expected = np.array([ + [0.0 , 0.0 , 0.0 , 0.0 ], + [0.61454786, 0.0 , 0.0 , 0.0 ], + [0.82511046, 0.17488954, 0.0 , 0.0 ], + [0.35597035, 0.64402965, 0.0 , 0.0 ], + [0.0 , 0.91360726, 0.08639274, 0.0 ], + [0.0 , 0.55547007, 0.44452993, 0.0 ], + [0.0 , 0.19733289, 0.80266711, 0.0 ], + [0.0 , 0.0 , 0.87724349, 0.12275651], + [0.0 , 0.0 , 0.6038449 , 0.3961551 ], + [0.0 , 0.0 , 0.33044631, 0.66955369], + [0.0 , 0.0 , 0.05704771, 0.94295229], + [0.0 , 0.0 , 0.0 , 0.83483975], + [0.0 , 0.0 , 0.0 , 0.62612982], + [0.0 , 0.0 , 0.0 , 0.41741988], + [0.0 , 0.0 , 0.0 , 0.20870994], + [0.0 , 0.0 , 0.0 , 0.0 ] + ]) + # fmt: on + self.assertTrue(np.allclose(mel_filters, expected)) + + def test_mel_filter_bank_slaney(self): + mel_filters = mel_filter_bank( + num_frequency_bins=16, + num_mel_filters=4, + min_frequency=0, + max_frequency=2000, + sampling_rate=4000, + norm=None, + mel_scale="slaney", + ) + # fmt: off + expected = np.array([ + [0.0 , 0.0 , 0.0 , 0.0 ], + [0.39869419, 0.0 , 0.0 , 0.0 ], + [0.79738839, 0.0 , 0.0 , 0.0 ], + [0.80391742, 0.19608258, 0.0 , 0.0 ], + [0.40522322, 0.59477678, 0.0 , 0.0 ], + [0.00652903, 0.99347097, 0.0 , 0.0 ], + [0.0 , 0.60796161, 0.39203839, 0.0 ], + [0.0 , 0.20939631, 0.79060369, 0.0 ], + [0.0 , 0.0 , 0.84685344, 0.15314656], + [0.0 , 0.0 , 0.52418477, 0.47581523], + [0.0 , 0.0 , 0.2015161 , 0.7984839 ], + [0.0 , 0.0 , 0.0 , 0.9141874 ], + [0.0 , 0.0 , 0.0 , 0.68564055], + [0.0 , 0.0 , 0.0 , 0.4570937 ], + [0.0 , 0.0 , 0.0 , 0.22854685], + [0.0 , 0.0 , 0.0 , 0.0 ] + ]) + # fmt: on + self.assertTrue(np.allclose(mel_filters, expected)) + + def test_mel_filter_bank_kaldi(self): + mel_filters = mel_filter_bank( + num_frequency_bins=16, + num_mel_filters=4, + min_frequency=0, + max_frequency=2000, + sampling_rate=4000, + norm=None, + mel_scale="kaldi", + triangularize_in_mel_space=True, + ) + # fmt: off + expected = np.array( + [[0.0000, 0.0000, 0.0000, 0.0000], + [0.6086, 0.0000, 0.0000, 0.0000], + [0.8689, 0.1311, 0.0000, 0.0000], + [0.4110, 0.5890, 0.0000, 0.0000], + [0.0036, 0.9964, 0.0000, 0.0000], + [0.0000, 0.6366, 0.3634, 0.0000], + [0.0000, 0.3027, 0.6973, 0.0000], + [0.0000, 0.0000, 0.9964, 0.0036], + [0.0000, 0.0000, 0.7135, 0.2865], + [0.0000, 0.0000, 0.4507, 0.5493], + [0.0000, 0.0000, 0.2053, 0.7947], + [0.0000, 0.0000, 0.0000, 0.9752], + [0.0000, 0.0000, 0.0000, 0.7585], + [0.0000, 0.0000, 0.0000, 0.5539], + [0.0000, 0.0000, 0.0000, 0.3599], + [0.0000, 0.0000, 0.0000, 0.1756]] + ) + # fmt: on + self.assertTrue(np.allclose(mel_filters, expected, atol=5e-5)) + + def test_mel_filter_bank_slaney_norm(self): + mel_filters = mel_filter_bank( + num_frequency_bins=16, + num_mel_filters=4, + min_frequency=0, + max_frequency=2000, + sampling_rate=4000, + norm="slaney", + mel_scale="slaney", + ) + # fmt: off + expected = np.array([ + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], + [1.19217795e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], + [2.38435591e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], + [2.40387905e-03, 5.86232616e-04, 0.00000000e+00, 0.00000000e+00], + [1.21170110e-03, 1.77821783e-03, 0.00000000e+00, 0.00000000e+00], + [1.95231437e-05, 2.97020305e-03, 0.00000000e+00, 0.00000000e+00], + [0.00000000e+00, 1.81763684e-03, 1.04857612e-03, 0.00000000e+00], + [0.00000000e+00, 6.26036972e-04, 2.11460963e-03, 0.00000000e+00], + [0.00000000e+00, 0.00000000e+00, 2.26505954e-03, 3.07332945e-04], + [0.00000000e+00, 0.00000000e+00, 1.40202503e-03, 9.54861093e-04], + [0.00000000e+00, 0.00000000e+00, 5.38990521e-04, 1.60238924e-03], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.83458185e-03], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.37593638e-03], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 9.17290923e-04], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 4.58645462e-04], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00] + ]) + # fmt: on + self.assertTrue(np.allclose(mel_filters, expected)) + + def test_window_function(self): + window = window_function(16, "hann") + self.assertEqual(len(window), 16) + + # fmt: off + expected = np.array([ + 0.0, 0.03806023, 0.14644661, 0.30865828, 0.5, 0.69134172, 0.85355339, 0.96193977, + 1.0, 0.96193977, 0.85355339, 0.69134172, 0.5, 0.30865828, 0.14644661, 0.03806023, + ]) + # fmt: on + self.assertTrue(np.allclose(window, expected)) + + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] + return [x["array"] for x in speech_samples] + + def test_spectrogram_impulse(self): + waveform = np.zeros(40) + waveform[9] = 1.0 # impulse shifted in time + + spec = spectrogram( + waveform, + window_function(12, "hann", frame_length=16), + frame_length=16, + hop_length=4, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (9, 11)) + + expected = np.array([[0.0, 0.0669873, 0.9330127, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) + self.assertTrue(np.allclose(spec, expected)) + + def test_spectrogram_integration_test(self): + waveform = self._load_datasamples(1)[0] + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (257, 732)) + + # fmt: off + expected = np.array([ + 0.02464888, 0.04648664, 0.05872392, 0.02311783, 0.0327175 , + 0.02433643, 0.01198814, 0.02055709, 0.01559287, 0.01394357, + 0.01299037, 0.01728045, 0.0254554 , 0.02486533, 0.02011792, + 0.01755333, 0.02100457, 0.02337024, 0.01436963, 0.01464558, + 0.0211017 , 0.0193489 , 0.01272165, 0.01858462, 0.03722598, + 0.0456542 , 0.03281558, 0.00620586, 0.02226466, 0.03618042, + 0.03508182, 0.02271432, 0.01051649, 0.01225771, 0.02315293, + 0.02331886, 0.01417785, 0.0106844 , 0.01791214, 0.017177 , + 0.02125114, 0.05028201, 0.06830665, 0.05216664, 0.01963666, + 0.06941418, 0.11513043, 0.12257859, 0.10948435, 0.08568069, + 0.05509328, 0.05047818, 0.047112 , 0.05060737, 0.02982424, + 0.02803827, 0.02933729, 0.01760491, 0.00587815, 0.02117637, + 0.0293578 , 0.03452379, 0.02194803, 0.01676056, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 400], expected)) + + spec = spectrogram( + waveform, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + fft_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (257, 732)) + self.assertTrue(np.allclose(spec[:64, 400], expected)) + + mel_filters = mel_filter_bank( + num_frequency_bins=256, + num_mel_filters=400, + min_frequency=20, + max_frequency=8000, + sampling_rate=16000, + norm=None, + mel_scale="kaldi", + triangularize_in_mel_space=True, + ) + + mel_filters = np.pad(mel_filters, ((0, 1), (0, 0))) + + spec = spectrogram( + waveform, + window_function(400, "povey", periodic=False), + frame_length=400, + hop_length=160, + fft_length=512, + power=2.0, + center=False, + pad_mode="reflect", + onesided=True, + preemphasis=0.97, + mel_filters=mel_filters, + log_mel="log", + mel_floor=1.1920928955078125e-07, + remove_dc_offset=True, + ) + self.assertEqual(spec.shape, (400, 584)) + + # fmt: off + expected = np.array([-15.94238515, -8.20712299, -8.22704352, -15.94238515, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -6.52463769, -7.73677889, -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -4.18650018, -3.37195286, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -4.70190154, -2.4217066 , -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -5.62755239, -3.53385194, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -9.43303023, -8.77480925, -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -4.2951092 , -5.51585994, + -15.94238515, -15.94238515, -15.94238515, -4.40151721, + -3.95228878, -15.94238515, -15.94238515, -15.94238515, + -6.10365415, -4.59494697, -15.94238515, -15.94238515, + -15.94238515, -8.10727767, -6.2585298 , -15.94238515, + -15.94238515, -15.94238515, -5.60161702, -4.47217004, + -15.94238515, -15.94238515, -15.94238515, -5.91641988] + ) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 400], expected, atol=1e-5)) + + def test_spectrogram_center_padding(self): + waveform = self._load_datasamples(1)[0] + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=True, + pad_mode="reflect", + ) + self.assertEqual(spec.shape, (257, 732)) + + # fmt: off + expected = np.array([ + 0.1287945 , 0.12792738, 0.08311573, 0.03155122, 0.02470202, + 0.00727857, 0.00910694, 0.00686163, 0.01238981, 0.01473668, + 0.00336144, 0.00370314, 0.00600871, 0.01120164, 0.01942998, + 0.03132008, 0.0232842 , 0.01124642, 0.02754783, 0.02423725, + 0.00147893, 0.00038027, 0.00112299, 0.00596233, 0.00571529, + 0.02084235, 0.0231855 , 0.00810006, 0.01837943, 0.00651339, + 0.00093931, 0.00067426, 0.01058399, 0.01270507, 0.00151734, + 0.00331913, 0.00302416, 0.01081792, 0.00754549, 0.00148963, + 0.00111943, 0.00152573, 0.00608017, 0.01749986, 0.01205949, + 0.0143082 , 0.01910573, 0.00413786, 0.03916619, 0.09873404, + 0.08302026, 0.02673891, 0.00401255, 0.01397392, 0.00751862, + 0.01024884, 0.01544606, 0.00638907, 0.00623633, 0.0085103 , + 0.00217659, 0.00276204, 0.00260835, 0.00299299, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 0], expected)) + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=True, + pad_mode="constant", + ) + self.assertEqual(spec.shape, (257, 732)) + + # fmt: off + expected = np.array([ + 0.06558744, 0.06889656, 0.06263352, 0.04264418, 0.03404115, + 0.03244197, 0.02279134, 0.01646339, 0.01452216, 0.00826055, + 0.00062093, 0.0031821 , 0.00419456, 0.00689327, 0.01106367, + 0.01712119, 0.01721762, 0.00977533, 0.01606626, 0.02275621, + 0.01727687, 0.00992739, 0.01217688, 0.01049927, 0.01022947, + 0.01302475, 0.01166873, 0.01081812, 0.01057327, 0.00767912, + 0.00429567, 0.00089625, 0.00654583, 0.00912084, 0.00700984, + 0.00225026, 0.00290545, 0.00667712, 0.00730663, 0.00410813, + 0.00073102, 0.00219296, 0.00527618, 0.00996585, 0.01123781, + 0.00872816, 0.01165121, 0.02047945, 0.03681747, 0.0514379 , + 0.05137928, 0.03960042, 0.02821562, 0.01813349, 0.01201322, + 0.01260964, 0.00900654, 0.00207905, 0.00456714, 0.00850599, + 0.00788239, 0.00664407, 0.00824227, 0.00628301, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 0], expected)) + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=False, + ) + self.assertEqual(spec.shape, (257, 728)) + + # fmt: off + expected = np.array([ + 0.00250445, 0.02161521, 0.06232229, 0.04339567, 0.00937727, + 0.01080616, 0.00248685, 0.0095264 , 0.00727476, 0.0079152 , + 0.00839946, 0.00254932, 0.00716622, 0.005559 , 0.00272623, + 0.00581774, 0.01896395, 0.01829788, 0.01020514, 0.01632692, + 0.00870888, 0.02065827, 0.0136022 , 0.0132382 , 0.011827 , + 0.00194505, 0.0189979 , 0.026874 , 0.02194014, 0.01923883, + 0.01621437, 0.00661967, 0.00289517, 0.00470257, 0.00957801, + 0.00191455, 0.00431664, 0.00544359, 0.01126213, 0.00785778, + 0.00423469, 0.01322504, 0.02226548, 0.02318576, 0.03428908, + 0.03648811, 0.0202938 , 0.011902 , 0.03226198, 0.06347476, + 0.01306318, 0.05308729, 0.05474771, 0.03127991, 0.00998512, + 0.01449977, 0.01272741, 0.00868176, 0.00850386, 0.00313876, + 0.00811857, 0.00538216, 0.00685749, 0.00535275, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 0], expected)) + + def test_spectrogram_shapes(self): + waveform = self._load_datasamples(1)[0] + + spec = spectrogram( + waveform, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (201, 732)) + + spec = spectrogram( + waveform, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + power=1.0, + center=False, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (201, 729)) + + spec = spectrogram( + waveform, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + fft_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (257, 732)) + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=64, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec.shape, (512, 1464)) + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=64, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec.shape, (512, 1464)) + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec.shape, (512, 183)) + + def test_mel_spectrogram(self): + waveform = self._load_datasamples(1)[0] + + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm=None, + mel_scale="htk", + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + spec = spectrogram( + waveform, + window_function(800, "hann", frame_length=1024), + frame_length=1024, + hop_length=128, + power=2.0, + ) + self.assertEqual(spec.shape, (513, 732)) + + spec = spectrogram( + waveform, + window_function(800, "hann", frame_length=1024), + frame_length=1024, + hop_length=128, + power=2.0, + mel_filters=mel_filters, + ) + self.assertEqual(spec.shape, (13, 732)) + + # fmt: off + expected = np.array([ + 1.08027889e+02, 1.48080673e+01, 7.70758213e+00, 9.57676639e-01, + 8.81639061e-02, 5.26073833e-02, 1.52736155e-02, 9.95350117e-03, + 7.95364356e-03, 1.01148004e-02, 4.29241020e-03, 9.90708797e-03, + 9.44153646e-04 + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:, 300], expected)) + + def test_spectrogram_power(self): + waveform = self._load_datasamples(1)[0] + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=None, + ) + self.assertEqual(spec.shape, (257, 732)) + self.assertEqual(spec.dtype, np.complex64) + + # fmt: off + expected = np.array([ + 0.01452305+0.01820039j, -0.01737362-0.01641946j, + 0.0121028 +0.01565081j, -0.02794554-0.03021514j, + 0.04719803+0.04086519j, -0.04391563-0.02779365j, + 0.05682834+0.01571325j, -0.08604821-0.02023657j, + 0.07497991+0.0186641j , -0.06366091-0.00922475j, + 0.11003416+0.0114788j , -0.13677941-0.01523552j, + 0.10934535-0.00117226j, -0.11635598+0.02551187j, + 0.14708674-0.03469823j, -0.1328196 +0.06034218j, + 0.12667368-0.13973421j, -0.14764774+0.18912019j, + 0.10235471-0.12181523j, -0.00773012+0.04730498j, + -0.01487191-0.07312611j, -0.02739162+0.09619419j, + 0.02895459-0.05398273j, 0.01198589+0.05276592j, + -0.02117299-0.10123465j, 0.00666388+0.09526499j, + -0.01672773-0.05649684j, 0.02723125+0.05939891j, + -0.01879361-0.062954j , 0.03686557+0.04568823j, + -0.07394181-0.07949649j, 0.06238583+0.13905765j, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[64:96, 321], expected)) + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=1.0, + ) + self.assertEqual(spec.shape, (257, 732)) + self.assertEqual(spec.dtype, np.float64) + + # fmt: off + expected = np.array([ + 0.02328461, 0.02390484, 0.01978448, 0.04115711, 0.0624309 , + 0.05197181, 0.05896072, 0.08839577, 0.07726794, 0.06432579, + 0.11063128, 0.13762532, 0.10935163, 0.11911998, 0.15112405, + 0.14588428, 0.18860507, 0.23992978, 0.15910825, 0.04793241, + 0.07462307, 0.10001811, 0.06125769, 0.05411011, 0.10342509, + 0.09549777, 0.05892122, 0.06534349, 0.06569936, 0.05870678, + 0.10856833, 0.1524107 , 0.11463385, 0.05766969, 0.12385171, + 0.14472842, 0.11978184, 0.10353675, 0.07244056, 0.03461861, + 0.02624896, 0.02227475, 0.01238363, 0.00885281, 0.0110049 , + 0.00807005, 0.01033663, 0.01703181, 0.01445856, 0.00585615, + 0.0132431 , 0.02754132, 0.01524478, 0.0204908 , 0.07453328, + 0.10716327, 0.07195779, 0.08816078, 0.18340898, 0.16449876, + 0.12322842, 0.1621659 , 0.12334293, 0.06033659, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[64:128, 321], expected)) + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=2.0, + ) + self.assertEqual(spec.shape, (257, 732)) + self.assertEqual(spec.dtype, np.float64) + + # fmt: off + expected = np.array([ + 5.42173162e-04, 5.71441371e-04, 3.91425507e-04, 1.69390778e-03, + 3.89761780e-03, 2.70106923e-03, 3.47636663e-03, 7.81381316e-03, + 5.97033510e-03, 4.13780799e-03, 1.22392802e-02, 1.89407300e-02, + 1.19577805e-02, 1.41895693e-02, 2.28384770e-02, 2.12822221e-02, + 3.55718732e-02, 5.75663000e-02, 2.53154356e-02, 2.29751552e-03, + 5.56860259e-03, 1.00036217e-02, 3.75250424e-03, 2.92790355e-03, + 1.06967501e-02, 9.11982451e-03, 3.47171025e-03, 4.26977174e-03, + 4.31640586e-03, 3.44648538e-03, 1.17870830e-02, 2.32290216e-02, + 1.31409196e-02, 3.32579296e-03, 1.53392460e-02, 2.09463164e-02, + 1.43476883e-02, 1.07198600e-02, 5.24763530e-03, 1.19844836e-03, + 6.89007982e-04, 4.96164430e-04, 1.53354369e-04, 7.83722571e-05, + 1.21107812e-04, 6.51257360e-05, 1.06845939e-04, 2.90082477e-04, + 2.09049831e-04, 3.42945241e-05, 1.75379610e-04, 7.58524227e-04, + 2.32403356e-04, 4.19872697e-04, 5.55520924e-03, 1.14839673e-02, + 5.17792348e-03, 7.77232368e-03, 3.36388536e-02, 2.70598419e-02, + 1.51852425e-02, 2.62977779e-02, 1.52134784e-02, 3.64050455e-03, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[64:128, 321], expected)) + + def test_power_to_db(self): + spectrogram = np.zeros((2, 3)) + spectrogram[0, 0] = 2.0 + spectrogram[0, 1] = 0.5 + spectrogram[0, 2] = 0.707 + spectrogram[1, 1] = 1.0 + + output = power_to_db(spectrogram, reference=1.0) + expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-100.0, 0.0, -100.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, reference=2.0) + expected = np.array([[0.0, -6.02059991, -4.51610582], [-103.01029996, -3.01029996, -103.01029996]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, min_value=1e-6) + expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-60.0, 0.0, -60.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, db_range=80) + expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-76.98970004, 0.0, -76.98970004]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, reference=2.0, db_range=80) + expected = np.array([[0.0, -6.02059991, -4.51610582], [-80.0, -3.01029996, -80.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, reference=2.0, min_value=1e-6, db_range=80) + expected = np.array([[0.0, -6.02059991, -4.51610582], [-63.01029996, -3.01029996, -63.01029996]]) + self.assertTrue(np.allclose(output, expected)) + + with pytest.raises(ValueError): + power_to_db(spectrogram, reference=0.0) + with pytest.raises(ValueError): + power_to_db(spectrogram, min_value=0.0) + with pytest.raises(ValueError): + power_to_db(spectrogram, db_range=-80) + + def test_amplitude_to_db(self): + spectrogram = np.zeros((2, 3)) + spectrogram[0, 0] = 2.0 + spectrogram[0, 1] = 0.5 + spectrogram[0, 2] = 0.707 + spectrogram[1, 1] = 1.0 + + output = amplitude_to_db(spectrogram, reference=1.0) + expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-100.0, 0.0, -100.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, reference=2.0) + expected = np.array([[0.0, -12.04119983, -9.03221164], [-106.02059991, -6.02059991, -106.02059991]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, min_value=1e-3) + expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-60.0, 0.0, -60.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, db_range=80) + expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-73.97940009, 0.0, -73.97940009]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, reference=2.0, db_range=80) + expected = np.array([[0.0, -12.04119983, -9.03221164], [-80.0, -6.02059991, -80.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, reference=2.0, min_value=1e-3, db_range=80) + expected = np.array([[0.0, -12.04119983, -9.03221164], [-66.02059991, -6.02059991, -66.02059991]]) + self.assertTrue(np.allclose(output, expected)) + + with pytest.raises(ValueError): + amplitude_to_db(spectrogram, reference=0.0) + with pytest.raises(ValueError): + amplitude_to_db(spectrogram, min_value=0.0) + with pytest.raises(ValueError): + amplitude_to_db(spectrogram, db_range=-80) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_backbone_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_backbone_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..66b7087da2463b7a074e8d7b9d905c492c7af8f6 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_backbone_utils.py @@ -0,0 +1,102 @@ +# Copyright 2023 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 unittest + +from transformers.utils.backbone_utils import ( + BackboneMixin, + get_aligned_output_features_output_indices, + verify_out_features_out_indices, +) + + +class BackboneUtilsTester(unittest.TestCase): + def test_get_aligned_output_features_output_indices(self): + stage_names = ["a", "b", "c"] + + # Defaults to last layer if both are None + out_features, out_indices = get_aligned_output_features_output_indices(None, None, stage_names) + self.assertEqual(out_features, ["c"]) + self.assertEqual(out_indices, [2]) + + # Out indices set to match out features + out_features, out_indices = get_aligned_output_features_output_indices(["a", "c"], None, stage_names) + self.assertEqual(out_features, ["a", "c"]) + self.assertEqual(out_indices, [0, 2]) + + # Out features set to match out indices + out_features, out_indices = get_aligned_output_features_output_indices(None, [0, 2], stage_names) + self.assertEqual(out_features, ["a", "c"]) + self.assertEqual(out_indices, [0, 2]) + + # Out features selected from negative indices + out_features, out_indices = get_aligned_output_features_output_indices(None, [-3, -1], stage_names) + self.assertEqual(out_features, ["a", "c"]) + self.assertEqual(out_indices, [-3, -1]) + + def test_verify_out_features_out_indices(self): + # Stage names must be set + with self.assertRaises(ValueError): + verify_out_features_out_indices(["a", "b"], (0, 1), None) + + # Out features must be a list + with self.assertRaises(ValueError): + verify_out_features_out_indices(("a", "b"), (0, 1), ["a", "b"]) + + # Out features must be a subset of stage names + with self.assertRaises(ValueError): + verify_out_features_out_indices(["a", "b"], (0, 1), ["a"]) + + # Out indices must be a list or tuple + with self.assertRaises(ValueError): + verify_out_features_out_indices(None, 0, ["a", "b"]) + + # Out indices must be a subset of stage names + with self.assertRaises(ValueError): + verify_out_features_out_indices(None, (0, 1), ["a"]) + + # Out features and out indices must be the same length + with self.assertRaises(ValueError): + verify_out_features_out_indices(["a", "b"], (0,), ["a", "b", "c"]) + + # Out features should match out indices + with self.assertRaises(ValueError): + verify_out_features_out_indices(["a", "b"], (0, 2), ["a", "b", "c"]) + + # Out features and out indices should be in order + with self.assertRaises(ValueError): + verify_out_features_out_indices(["b", "a"], (0, 1), ["a", "b"]) + + # Check passes with valid inputs + verify_out_features_out_indices(["a", "b", "d"], (0, 1, -1), ["a", "b", "c", "d"]) + + def test_backbone_mixin(self): + backbone = BackboneMixin() + + backbone.stage_names = ["a", "b", "c"] + backbone._out_features = ["a", "c"] + backbone._out_indices = [0, 2] + + # Check that the output features and indices are set correctly + self.assertEqual(backbone.out_features, ["a", "c"]) + self.assertEqual(backbone.out_indices, [0, 2]) + + # Check out features and indices are updated correctly + backbone.out_features = ["a", "b"] + self.assertEqual(backbone.out_features, ["a", "b"]) + self.assertEqual(backbone.out_indices, [0, 1]) + + backbone.out_indices = [-3, -1] + self.assertEqual(backbone.out_features, ["a", "c"]) + self.assertEqual(backbone.out_indices, [-3, -1]) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_cli.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..b208ff19f1a425f36f954c5d5525506482a22bd7 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_cli.py @@ -0,0 +1,90 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# 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 os +import shutil +import unittest +from unittest.mock import patch + +from transformers.testing_utils import CaptureStd, is_pt_tf_cross_test, require_torch + + +class CLITest(unittest.TestCase): + @patch("sys.argv", ["fakeprogrampath", "env"]) + def test_cli_env(self): + # test transformers-cli env + import transformers.commands.transformers_cli + + with CaptureStd() as cs: + transformers.commands.transformers_cli.main() + self.assertIn("Python version", cs.out) + self.assertIn("Platform", cs.out) + self.assertIn("Using distributed or parallel set-up in script?", cs.out) + + @is_pt_tf_cross_test + @patch( + "sys.argv", ["fakeprogrampath", "pt-to-tf", "--model-name", "hf-internal-testing/tiny-random-gptj", "--no-pr"] + ) + def test_cli_pt_to_tf(self): + import transformers.commands.transformers_cli + + shutil.rmtree("/tmp/hf-internal-testing/tiny-random-gptj", ignore_errors=True) # cleans potential past runs + transformers.commands.transformers_cli.main() + + self.assertTrue(os.path.exists("/tmp/hf-internal-testing/tiny-random-gptj/tf_model.h5")) + + @require_torch + @patch("sys.argv", ["fakeprogrampath", "download", "hf-internal-testing/tiny-random-gptj", "--cache-dir", "/tmp"]) + def test_cli_download(self): + import transformers.commands.transformers_cli + + # # remove any previously downloaded model to start clean + shutil.rmtree("/tmp/models--hf-internal-testing--tiny-random-gptj", ignore_errors=True) + + # run the command + transformers.commands.transformers_cli.main() + + # check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--tiny-random-gptj + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/blobs")) + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/refs")) + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/snapshots")) + + @require_torch + @patch( + "sys.argv", + [ + "fakeprogrampath", + "download", + "hf-internal-testing/test_dynamic_model_with_tokenizer", + "--trust-remote-code", + "--cache-dir", + "/tmp", + ], + ) + def test_cli_download_trust_remote(self): + import transformers.commands.transformers_cli + + # # remove any previously downloaded model to start clean + shutil.rmtree("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer", ignore_errors=True) + + # run the command + transformers.commands.transformers_cli.main() + + # check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/blobs")) + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/refs")) + self.assertTrue( + os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/snapshots") + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_convert_slow_tokenizer.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_convert_slow_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..edeb06c390c0a01c805875d7723fa5f520106d0f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_convert_slow_tokenizer.py @@ -0,0 +1,35 @@ +import unittest +import warnings +from dataclasses import dataclass + +from transformers.convert_slow_tokenizer import SpmConverter +from transformers.testing_utils import get_tests_dir + + +@dataclass +class FakeOriginalTokenizer: + vocab_file: str + + +class ConvertSlowTokenizerTest(unittest.TestCase): + def test_spm_converter_bytefallback_warning(self): + spm_model_file_without_bytefallback = get_tests_dir("fixtures/test_sentencepiece.model") + spm_model_file_with_bytefallback = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model") + + original_tokenizer_without_bytefallback = FakeOriginalTokenizer(vocab_file=spm_model_file_without_bytefallback) + + with warnings.catch_warnings(record=True) as w: + _ = SpmConverter(original_tokenizer_without_bytefallback) + self.assertEqual(len(w), 0) + + original_tokenizer_with_bytefallback = FakeOriginalTokenizer(vocab_file=spm_model_file_with_bytefallback) + + with warnings.catch_warnings(record=True) as w: + _ = SpmConverter(original_tokenizer_with_bytefallback) + self.assertEqual(len(w), 1) + + self.assertIn( + "The sentencepiece tokenizer that you are converting to a fast tokenizer uses the byte fallback option" + " which is not implemented in the fast tokenizers.", + str(w[0].message), + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_doc_samples.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_doc_samples.py new file mode 100644 index 0000000000000000000000000000000000000000..953654537843ee2a5d9de2eda64ce4b9704ac2e1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_doc_samples.py @@ -0,0 +1,171 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# 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 doctest +import logging +import os +import unittest +from glob import glob +from pathlib import Path +from typing import List, Union + +import transformers +from transformers.testing_utils import require_tf, require_torch, slow + + +logger = logging.getLogger() + + +@require_torch +class TestDocLists(unittest.TestCase): + def test_flash_support_list(self): + with open("./docs/source/en/perf_infer_gpu_one.md", "r") as f: + doctext = f.read() + + doctext = doctext.split("FlashAttention-2 is currently supported for the following architectures:")[1] + doctext = doctext.split("You can request to add FlashAttention-2 support")[0] + + patterns = glob("./src/transformers/models/**/modeling_*.py") + patterns_tf = glob("./src/transformers/models/**/modeling_tf_*.py") + patterns_flax = glob("./src/transformers/models/**/modeling_flax_*.py") + patterns = list(set(patterns) - set(patterns_tf) - set(patterns_flax)) + archs_supporting_fa2 = [] + for filename in patterns: + with open(filename, "r") as f: + text = f.read() + + if "_supports_flash_attn_2 = True" in text: + model_name = os.path.basename(filename).replace(".py", "").replace("modeling_", "") + archs_supporting_fa2.append(model_name) + + for arch in archs_supporting_fa2: + if arch not in doctext: + raise ValueError( + f"{arch} should be in listed in the flash attention documentation but is not. Please update the documentation." + ) + + def test_sdpa_support_list(self): + with open("./docs/source/en/perf_infer_gpu_one.md", "r") as f: + doctext = f.read() + + doctext = doctext.split( + "For now, Transformers supports inference and training through SDPA for the following architectures:" + )[1] + doctext = doctext.split("Note that FlashAttention can only be used for models using the")[0] + + patterns = glob("./src/transformers/models/**/modeling_*.py") + patterns_tf = glob("./src/transformers/models/**/modeling_tf_*.py") + patterns_flax = glob("./src/transformers/models/**/modeling_flax_*.py") + patterns = list(set(patterns) - set(patterns_tf) - set(patterns_flax)) + archs_supporting_sdpa = [] + for filename in patterns: + with open(filename, "r") as f: + text = f.read() + + if "_supports_sdpa = True" in text: + model_name = os.path.basename(filename).replace(".py", "").replace("modeling_", "") + archs_supporting_sdpa.append(model_name) + + for arch in archs_supporting_sdpa: + if arch not in doctext: + raise ValueError( + f"{arch} should be in listed in the SDPA documentation but is not. Please update the documentation." + ) + + +@unittest.skip("Temporarily disable the doc tests.") +@require_torch +@require_tf +@slow +class TestCodeExamples(unittest.TestCase): + def analyze_directory( + self, + directory: Path, + identifier: Union[str, None] = None, + ignore_files: Union[List[str], None] = None, + n_identifier: Union[str, List[str], None] = None, + only_modules: bool = True, + ): + """ + Runs through the specific directory, looking for the files identified with `identifier`. Executes + the doctests in those files + + Args: + directory (`Path`): Directory containing the files + identifier (`str`): Will parse files containing this + ignore_files (`List[str]`): List of files to skip + n_identifier (`str` or `List[str]`): Will not parse files containing this/these identifiers. + only_modules (`bool`): Whether to only analyze modules + """ + files = [file for file in os.listdir(directory) if os.path.isfile(os.path.join(directory, file))] + + if identifier is not None: + files = [file for file in files if identifier in file] + + if n_identifier is not None: + if isinstance(n_identifier, List): + for n_ in n_identifier: + files = [file for file in files if n_ not in file] + else: + files = [file for file in files if n_identifier not in file] + + ignore_files = ignore_files or [] + ignore_files.append("__init__.py") + files = [file for file in files if file not in ignore_files] + + for file in files: + # Open all files + print("Testing", file) + + if only_modules: + module_identifier = file.split(".")[0] + try: + module_identifier = getattr(transformers, module_identifier) + suite = doctest.DocTestSuite(module_identifier) + result = unittest.TextTestRunner().run(suite) + self.assertIs(len(result.failures), 0) + except AttributeError: + logger.info(f"{module_identifier} is not a module.") + else: + result = doctest.testfile(str(".." / directory / file), optionflags=doctest.ELLIPSIS) + self.assertIs(result.failed, 0) + + def test_modeling_examples(self): + transformers_directory = Path("src/transformers") + files = "modeling" + ignore_files = [ + "modeling_ctrl.py", + "modeling_tf_ctrl.py", + ] + self.analyze_directory(transformers_directory, identifier=files, ignore_files=ignore_files) + + def test_tokenization_examples(self): + transformers_directory = Path("src/transformers") + files = "tokenization" + self.analyze_directory(transformers_directory, identifier=files) + + def test_configuration_examples(self): + transformers_directory = Path("src/transformers") + files = "configuration" + self.analyze_directory(transformers_directory, identifier=files) + + def test_remaining_examples(self): + transformers_directory = Path("src/transformers") + n_identifiers = ["configuration", "modeling", "tokenization"] + self.analyze_directory(transformers_directory, n_identifier=n_identifiers) + + def test_doc_sources(self): + doc_source_directory = Path("docs/source") + ignore_files = ["favicon.ico"] + self.analyze_directory(doc_source_directory, ignore_files=ignore_files, only_modules=False) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_dynamic_module_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_dynamic_module_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dfdc63460cd34648ef2f23dbff32b82509e11947 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_dynamic_module_utils.py @@ -0,0 +1,129 @@ +# Copyright 2023 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 os + +import pytest + +from transformers.dynamic_module_utils import get_imports + + +TOP_LEVEL_IMPORT = """ +import os +""" + +IMPORT_IN_FUNCTION = """ +def foo(): + import os + return False +""" + +DEEPLY_NESTED_IMPORT = """ +def foo(): + def bar(): + if True: + import os + return False + return bar() +""" + +TOP_LEVEL_TRY_IMPORT = """ +import os + +try: + import bar +except ImportError: + raise ValueError() +""" + +TRY_IMPORT_IN_FUNCTION = """ +import os + +def foo(): + try: + import bar + except ImportError: + raise ValueError() +""" + +MULTIPLE_EXCEPTS_IMPORT = """ +import os + +try: + import bar +except (ImportError, AttributeError): + raise ValueError() +""" + +EXCEPT_AS_IMPORT = """ +import os + +try: + import bar +except ImportError as e: + raise ValueError() +""" + +GENERIC_EXCEPT_IMPORT = """ +import os + +try: + import bar +except: + raise ValueError() +""" + +MULTILINE_TRY_IMPORT = """ +import os + +try: + import bar + import baz +except ImportError: + raise ValueError() +""" + +MULTILINE_BOTH_IMPORT = """ +import os + +try: + import bar + import baz +except ImportError: + x = 1 + raise ValueError() +""" + +CASES = [ + TOP_LEVEL_IMPORT, + IMPORT_IN_FUNCTION, + DEEPLY_NESTED_IMPORT, + TOP_LEVEL_TRY_IMPORT, + GENERIC_EXCEPT_IMPORT, + MULTILINE_TRY_IMPORT, + MULTILINE_BOTH_IMPORT, + MULTIPLE_EXCEPTS_IMPORT, + EXCEPT_AS_IMPORT, + TRY_IMPORT_IN_FUNCTION, +] + + +@pytest.mark.parametrize("case", CASES) +def test_import_parsing(tmp_path, case): + tmp_file_path = os.path.join(tmp_path, "test_file.py") + with open(tmp_file_path, "w") as _tmp_file: + _tmp_file.write(case) + + parsed_imports = get_imports(tmp_file_path) + assert parsed_imports == ["os"] diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_file_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_file_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1cbde0fb18c6178c63c9ba74775d17b806322184 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_file_utils.py @@ -0,0 +1,133 @@ +# 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 contextlib +import importlib +import io +import unittest + +import transformers + +# Try to import everything from transformers to ensure every object can be loaded. +from transformers import * # noqa F406 +from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch +from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available + + +if is_torch_available(): + from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification + +if is_tf_available(): + from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification + +if is_flax_available(): + from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification + + +MODEL_ID = DUMMY_UNKNOWN_IDENTIFIER +# An actual model hosted on huggingface.co + +REVISION_ID_DEFAULT = "main" +# Default branch name +REVISION_ID_ONE_SPECIFIC_COMMIT = "f2c752cfc5c0ab6f4bdec59acea69eefbee381c2" +# One particular commit (not the top of `main`) +REVISION_ID_INVALID = "aaaaaaa" +# This commit does not exist, so we should 404. + +PINNED_SHA1 = "d9e9f15bc825e4b2c9249e9578f884bbcb5e3684" +# Sha-1 of config.json on the top of `main`, for checking purposes +PINNED_SHA256 = "4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3" +# Sha-256 of pytorch_model.bin on the top of `main`, for checking purposes + + +# Dummy contexts to test `ContextManagers` +@contextlib.contextmanager +def context_en(): + print("Welcome!") + yield + print("Bye!") + + +@contextlib.contextmanager +def context_fr(): + print("Bonjour!") + yield + print("Au revoir!") + + +class TestImportMechanisms(unittest.TestCase): + def test_module_spec_available(self): + # If the spec is missing, importlib would not be able to import the module dynamically. + assert transformers.__spec__ is not None + assert importlib.util.find_spec("transformers") is not None + + +class GenericUtilTests(unittest.TestCase): + @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) + def test_context_managers_no_context(self, mock_stdout): + with ContextManagers([]): + print("Transformers are awesome!") + # The print statement adds a new line at the end of the output + self.assertEqual(mock_stdout.getvalue(), "Transformers are awesome!\n") + + @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) + def test_context_managers_one_context(self, mock_stdout): + with ContextManagers([context_en()]): + print("Transformers are awesome!") + # The output should be wrapped with an English welcome and goodbye + self.assertEqual(mock_stdout.getvalue(), "Welcome!\nTransformers are awesome!\nBye!\n") + + @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) + def test_context_managers_two_context(self, mock_stdout): + with ContextManagers([context_fr(), context_en()]): + print("Transformers are awesome!") + # The output should be wrapped with an English and French welcome and goodbye + self.assertEqual(mock_stdout.getvalue(), "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n") + + @require_torch + def test_find_labels_pt(self): + self.assertEqual(find_labels(BertForSequenceClassification), ["labels"]) + self.assertEqual(find_labels(BertForPreTraining), ["labels", "next_sentence_label"]) + self.assertEqual(find_labels(BertForQuestionAnswering), ["start_positions", "end_positions"]) + + # find_labels works regardless of the class name (it detects the framework through inheritance) + class DummyModel(BertForSequenceClassification): + pass + + self.assertEqual(find_labels(DummyModel), ["labels"]) + + @require_tf + def test_find_labels_tf(self): + self.assertEqual(find_labels(TFBertForSequenceClassification), ["labels"]) + self.assertEqual(find_labels(TFBertForPreTraining), ["labels", "next_sentence_label"]) + self.assertEqual(find_labels(TFBertForQuestionAnswering), ["start_positions", "end_positions"]) + + # find_labels works regardless of the class name (it detects the framework through inheritance) + class DummyModel(TFBertForSequenceClassification): + pass + + self.assertEqual(find_labels(DummyModel), ["labels"]) + + @require_flax + def test_find_labels_flax(self): + # Flax models don't have labels + self.assertEqual(find_labels(FlaxBertForSequenceClassification), []) + self.assertEqual(find_labels(FlaxBertForPreTraining), []) + self.assertEqual(find_labels(FlaxBertForQuestionAnswering), []) + + # find_labels works regardless of the class name (it detects the framework through inheritance) + class DummyModel(FlaxBertForSequenceClassification): + pass + + self.assertEqual(find_labels(DummyModel), []) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_generic.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_generic.py new file mode 100644 index 0000000000000000000000000000000000000000..3d864648120b569baefe6c58612648890f66f2b6 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_generic.py @@ -0,0 +1,200 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# 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 unittest + +import numpy as np + +from transformers.testing_utils import require_flax, require_tf, require_torch +from transformers.utils import ( + expand_dims, + flatten_dict, + is_flax_available, + is_tf_available, + is_torch_available, + reshape, + squeeze, + transpose, +) + + +if is_flax_available(): + import jax.numpy as jnp + +if is_tf_available(): + import tensorflow as tf + +if is_torch_available(): + import torch + + +class GenericTester(unittest.TestCase): + def test_flatten_dict(self): + input_dict = { + "task_specific_params": { + "summarization": {"length_penalty": 1.0, "max_length": 128, "min_length": 12, "num_beams": 4}, + "summarization_cnn": {"length_penalty": 2.0, "max_length": 142, "min_length": 56, "num_beams": 4}, + "summarization_xsum": {"length_penalty": 1.0, "max_length": 62, "min_length": 11, "num_beams": 6}, + } + } + expected_dict = { + "task_specific_params.summarization.length_penalty": 1.0, + "task_specific_params.summarization.max_length": 128, + "task_specific_params.summarization.min_length": 12, + "task_specific_params.summarization.num_beams": 4, + "task_specific_params.summarization_cnn.length_penalty": 2.0, + "task_specific_params.summarization_cnn.max_length": 142, + "task_specific_params.summarization_cnn.min_length": 56, + "task_specific_params.summarization_cnn.num_beams": 4, + "task_specific_params.summarization_xsum.length_penalty": 1.0, + "task_specific_params.summarization_xsum.max_length": 62, + "task_specific_params.summarization_xsum.min_length": 11, + "task_specific_params.summarization_xsum.num_beams": 6, + } + + self.assertEqual(flatten_dict(input_dict), expected_dict) + + def test_transpose_numpy(self): + x = np.random.randn(3, 4) + self.assertTrue(np.allclose(transpose(x), x.transpose())) + + x = np.random.randn(3, 4, 5) + self.assertTrue(np.allclose(transpose(x, axes=(1, 2, 0)), x.transpose((1, 2, 0)))) + + @require_torch + def test_transpose_torch(self): + x = np.random.randn(3, 4) + t = torch.tensor(x) + self.assertTrue(np.allclose(transpose(x), transpose(t).numpy())) + + x = np.random.randn(3, 4, 5) + t = torch.tensor(x) + self.assertTrue(np.allclose(transpose(x, axes=(1, 2, 0)), transpose(t, axes=(1, 2, 0)).numpy())) + + @require_tf + def test_transpose_tf(self): + x = np.random.randn(3, 4) + t = tf.constant(x) + self.assertTrue(np.allclose(transpose(x), transpose(t).numpy())) + + x = np.random.randn(3, 4, 5) + t = tf.constant(x) + self.assertTrue(np.allclose(transpose(x, axes=(1, 2, 0)), transpose(t, axes=(1, 2, 0)).numpy())) + + @require_flax + def test_transpose_flax(self): + x = np.random.randn(3, 4) + t = jnp.array(x) + self.assertTrue(np.allclose(transpose(x), np.asarray(transpose(t)))) + + x = np.random.randn(3, 4, 5) + t = jnp.array(x) + self.assertTrue(np.allclose(transpose(x, axes=(1, 2, 0)), np.asarray(transpose(t, axes=(1, 2, 0))))) + + def test_reshape_numpy(self): + x = np.random.randn(3, 4) + self.assertTrue(np.allclose(reshape(x, (4, 3)), np.reshape(x, (4, 3)))) + + x = np.random.randn(3, 4, 5) + self.assertTrue(np.allclose(reshape(x, (12, 5)), np.reshape(x, (12, 5)))) + + @require_torch + def test_reshape_torch(self): + x = np.random.randn(3, 4) + t = torch.tensor(x) + self.assertTrue(np.allclose(reshape(x, (4, 3)), reshape(t, (4, 3)).numpy())) + + x = np.random.randn(3, 4, 5) + t = torch.tensor(x) + self.assertTrue(np.allclose(reshape(x, (12, 5)), reshape(t, (12, 5)).numpy())) + + @require_tf + def test_reshape_tf(self): + x = np.random.randn(3, 4) + t = tf.constant(x) + self.assertTrue(np.allclose(reshape(x, (4, 3)), reshape(t, (4, 3)).numpy())) + + x = np.random.randn(3, 4, 5) + t = tf.constant(x) + self.assertTrue(np.allclose(reshape(x, (12, 5)), reshape(t, (12, 5)).numpy())) + + @require_flax + def test_reshape_flax(self): + x = np.random.randn(3, 4) + t = jnp.array(x) + self.assertTrue(np.allclose(reshape(x, (4, 3)), np.asarray(reshape(t, (4, 3))))) + + x = np.random.randn(3, 4, 5) + t = jnp.array(x) + self.assertTrue(np.allclose(reshape(x, (12, 5)), np.asarray(reshape(t, (12, 5))))) + + def test_squeeze_numpy(self): + x = np.random.randn(1, 3, 4) + self.assertTrue(np.allclose(squeeze(x), np.squeeze(x))) + + x = np.random.randn(1, 4, 1, 5) + self.assertTrue(np.allclose(squeeze(x, axis=2), np.squeeze(x, axis=2))) + + @require_torch + def test_squeeze_torch(self): + x = np.random.randn(1, 3, 4) + t = torch.tensor(x) + self.assertTrue(np.allclose(squeeze(x), squeeze(t).numpy())) + + x = np.random.randn(1, 4, 1, 5) + t = torch.tensor(x) + self.assertTrue(np.allclose(squeeze(x, axis=2), squeeze(t, axis=2).numpy())) + + @require_tf + def test_squeeze_tf(self): + x = np.random.randn(1, 3, 4) + t = tf.constant(x) + self.assertTrue(np.allclose(squeeze(x), squeeze(t).numpy())) + + x = np.random.randn(1, 4, 1, 5) + t = tf.constant(x) + self.assertTrue(np.allclose(squeeze(x, axis=2), squeeze(t, axis=2).numpy())) + + @require_flax + def test_squeeze_flax(self): + x = np.random.randn(1, 3, 4) + t = jnp.array(x) + self.assertTrue(np.allclose(squeeze(x), np.asarray(squeeze(t)))) + + x = np.random.randn(1, 4, 1, 5) + t = jnp.array(x) + self.assertTrue(np.allclose(squeeze(x, axis=2), np.asarray(squeeze(t, axis=2)))) + + def test_expand_dims_numpy(self): + x = np.random.randn(3, 4) + self.assertTrue(np.allclose(expand_dims(x, axis=1), np.expand_dims(x, axis=1))) + + @require_torch + def test_expand_dims_torch(self): + x = np.random.randn(3, 4) + t = torch.tensor(x) + self.assertTrue(np.allclose(expand_dims(x, axis=1), expand_dims(t, axis=1).numpy())) + + @require_tf + def test_expand_dims_tf(self): + x = np.random.randn(3, 4) + t = tf.constant(x) + self.assertTrue(np.allclose(expand_dims(x, axis=1), expand_dims(t, axis=1).numpy())) + + @require_flax + def test_expand_dims_flax(self): + x = np.random.randn(3, 4) + t = jnp.array(x) + self.assertTrue(np.allclose(expand_dims(x, axis=1), np.asarray(expand_dims(t, axis=1)))) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_hf_argparser.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_hf_argparser.py new file mode 100644 index 0000000000000000000000000000000000000000..c0fa748cbfa4398ed42ffc6ba7ee24bbbee0272f --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_hf_argparser.py @@ -0,0 +1,407 @@ +# 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 argparse +import json +import os +import sys +import tempfile +import unittest +from argparse import Namespace +from dataclasses import dataclass, field +from enum import Enum +from pathlib import Path +from typing import List, Literal, Optional + +import yaml + +from transformers import HfArgumentParser, TrainingArguments +from transformers.hf_argparser import make_choice_type_function, string_to_bool + + +# Since Python 3.10, we can use the builtin `|` operator for Union types +# See PEP 604: https://peps.python.org/pep-0604 +is_python_no_less_than_3_10 = sys.version_info >= (3, 10) + + +def list_field(default=None, metadata=None): + return field(default_factory=lambda: default, metadata=metadata) + + +@dataclass +class BasicExample: + foo: int + bar: float + baz: str + flag: bool + + +@dataclass +class WithDefaultExample: + foo: int = 42 + baz: str = field(default="toto", metadata={"help": "help message"}) + + +@dataclass +class WithDefaultBoolExample: + foo: bool = False + baz: bool = True + opt: Optional[bool] = None + + +class BasicEnum(Enum): + titi = "titi" + toto = "toto" + + +class MixedTypeEnum(Enum): + titi = "titi" + toto = "toto" + fourtytwo = 42 + + +@dataclass +class EnumExample: + foo: BasicEnum = "toto" + + def __post_init__(self): + self.foo = BasicEnum(self.foo) + + +@dataclass +class MixedTypeEnumExample: + foo: MixedTypeEnum = "toto" + + def __post_init__(self): + self.foo = MixedTypeEnum(self.foo) + + +@dataclass +class OptionalExample: + foo: Optional[int] = None + bar: Optional[float] = field(default=None, metadata={"help": "help message"}) + baz: Optional[str] = None + ces: Optional[List[str]] = list_field(default=[]) + des: Optional[List[int]] = list_field(default=[]) + + +@dataclass +class ListExample: + foo_int: List[int] = list_field(default=[]) + bar_int: List[int] = list_field(default=[1, 2, 3]) + foo_str: List[str] = list_field(default=["Hallo", "Bonjour", "Hello"]) + foo_float: List[float] = list_field(default=[0.1, 0.2, 0.3]) + + +@dataclass +class RequiredExample: + required_list: List[int] = field() + required_str: str = field() + required_enum: BasicEnum = field() + + def __post_init__(self): + self.required_enum = BasicEnum(self.required_enum) + + +@dataclass +class StringLiteralAnnotationExample: + foo: int + required_enum: "BasicEnum" = field() + opt: "Optional[bool]" = None + baz: "str" = field(default="toto", metadata={"help": "help message"}) + foo_str: "List[str]" = list_field(default=["Hallo", "Bonjour", "Hello"]) + + +if is_python_no_less_than_3_10: + + @dataclass + class WithDefaultBoolExamplePep604: + foo: bool = False + baz: bool = True + opt: bool | None = None + + @dataclass + class OptionalExamplePep604: + foo: int | None = None + bar: float | None = field(default=None, metadata={"help": "help message"}) + baz: str | None = None + ces: list[str] | None = list_field(default=[]) + des: list[int] | None = list_field(default=[]) + + +class HfArgumentParserTest(unittest.TestCase): + def argparsersEqual(self, a: argparse.ArgumentParser, b: argparse.ArgumentParser): + """ + Small helper to check pseudo-equality of parsed arguments on `ArgumentParser` instances. + """ + self.assertEqual(len(a._actions), len(b._actions)) + for x, y in zip(a._actions, b._actions): + xx = {k: v for k, v in vars(x).items() if k != "container"} + yy = {k: v for k, v in vars(y).items() if k != "container"} + + # Choices with mixed type have custom function as "type" + # So we need to compare results directly for equality + if xx.get("choices", None) and yy.get("choices", None): + for expected_choice in yy["choices"] + xx["choices"]: + self.assertEqual(xx["type"](expected_choice), yy["type"](expected_choice)) + del xx["type"], yy["type"] + + self.assertEqual(xx, yy) + + def test_basic(self): + parser = HfArgumentParser(BasicExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--foo", type=int, required=True) + expected.add_argument("--bar", type=float, required=True) + expected.add_argument("--baz", type=str, required=True) + expected.add_argument("--flag", type=string_to_bool, default=False, const=True, nargs="?") + self.argparsersEqual(parser, expected) + + args = ["--foo", "1", "--baz", "quux", "--bar", "0.5"] + (example,) = parser.parse_args_into_dataclasses(args, look_for_args_file=False) + self.assertFalse(example.flag) + + def test_with_default(self): + parser = HfArgumentParser(WithDefaultExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--foo", default=42, type=int) + expected.add_argument("--baz", default="toto", type=str, help="help message") + self.argparsersEqual(parser, expected) + + def test_with_default_bool(self): + expected = argparse.ArgumentParser() + expected.add_argument("--foo", type=string_to_bool, default=False, const=True, nargs="?") + expected.add_argument("--baz", type=string_to_bool, default=True, const=True, nargs="?") + # A boolean no_* argument always has to come after its "default: True" regular counter-part + # and its default must be set to False + expected.add_argument("--no_baz", action="store_false", default=False, dest="baz") + expected.add_argument("--opt", type=string_to_bool, default=None) + + dataclass_types = [WithDefaultBoolExample] + if is_python_no_less_than_3_10: + dataclass_types.append(WithDefaultBoolExamplePep604) + + for dataclass_type in dataclass_types: + parser = HfArgumentParser(dataclass_type) + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual(args, Namespace(foo=False, baz=True, opt=None)) + + args = parser.parse_args(["--foo", "--no_baz"]) + self.assertEqual(args, Namespace(foo=True, baz=False, opt=None)) + + args = parser.parse_args(["--foo", "--baz"]) + self.assertEqual(args, Namespace(foo=True, baz=True, opt=None)) + + args = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"]) + self.assertEqual(args, Namespace(foo=True, baz=True, opt=True)) + + args = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"]) + self.assertEqual(args, Namespace(foo=False, baz=False, opt=False)) + + def test_with_enum(self): + parser = HfArgumentParser(MixedTypeEnumExample) + + expected = argparse.ArgumentParser() + expected.add_argument( + "--foo", + default="toto", + choices=["titi", "toto", 42], + type=make_choice_type_function(["titi", "toto", 42]), + ) + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual(args.foo, "toto") + enum_ex = parser.parse_args_into_dataclasses([])[0] + self.assertEqual(enum_ex.foo, MixedTypeEnum.toto) + + args = parser.parse_args(["--foo", "titi"]) + self.assertEqual(args.foo, "titi") + enum_ex = parser.parse_args_into_dataclasses(["--foo", "titi"])[0] + self.assertEqual(enum_ex.foo, MixedTypeEnum.titi) + + args = parser.parse_args(["--foo", "42"]) + self.assertEqual(args.foo, 42) + enum_ex = parser.parse_args_into_dataclasses(["--foo", "42"])[0] + self.assertEqual(enum_ex.foo, MixedTypeEnum.fourtytwo) + + def test_with_literal(self): + @dataclass + class LiteralExample: + foo: Literal["titi", "toto", 42] = "toto" + + parser = HfArgumentParser(LiteralExample) + + expected = argparse.ArgumentParser() + expected.add_argument( + "--foo", + default="toto", + choices=("titi", "toto", 42), + type=make_choice_type_function(["titi", "toto", 42]), + ) + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual(args.foo, "toto") + + args = parser.parse_args(["--foo", "titi"]) + self.assertEqual(args.foo, "titi") + + args = parser.parse_args(["--foo", "42"]) + self.assertEqual(args.foo, 42) + + def test_with_list(self): + parser = HfArgumentParser(ListExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--foo_int", nargs="+", default=[], type=int) + expected.add_argument("--bar_int", nargs="+", default=[1, 2, 3], type=int) + expected.add_argument("--foo_str", nargs="+", default=["Hallo", "Bonjour", "Hello"], type=str) + expected.add_argument("--foo_float", nargs="+", default=[0.1, 0.2, 0.3], type=float) + + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual( + args, + Namespace(foo_int=[], bar_int=[1, 2, 3], foo_str=["Hallo", "Bonjour", "Hello"], foo_float=[0.1, 0.2, 0.3]), + ) + + args = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split()) + self.assertEqual(args, Namespace(foo_int=[1], bar_int=[2, 3], foo_str=["a", "b", "c"], foo_float=[0.1, 0.7])) + + def test_with_optional(self): + expected = argparse.ArgumentParser() + expected.add_argument("--foo", default=None, type=int) + expected.add_argument("--bar", default=None, type=float, help="help message") + expected.add_argument("--baz", default=None, type=str) + expected.add_argument("--ces", nargs="+", default=[], type=str) + expected.add_argument("--des", nargs="+", default=[], type=int) + + dataclass_types = [OptionalExample] + if is_python_no_less_than_3_10: + dataclass_types.append(OptionalExamplePep604) + + for dataclass_type in dataclass_types: + parser = HfArgumentParser(dataclass_type) + + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual(args, Namespace(foo=None, bar=None, baz=None, ces=[], des=[])) + + args = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split()) + self.assertEqual(args, Namespace(foo=12, bar=3.14, baz="42", ces=["a", "b", "c"], des=[1, 2, 3])) + + def test_with_required(self): + parser = HfArgumentParser(RequiredExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--required_list", nargs="+", type=int, required=True) + expected.add_argument("--required_str", type=str, required=True) + expected.add_argument( + "--required_enum", + type=make_choice_type_function(["titi", "toto"]), + choices=["titi", "toto"], + required=True, + ) + self.argparsersEqual(parser, expected) + + def test_with_string_literal_annotation(self): + parser = HfArgumentParser(StringLiteralAnnotationExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--foo", type=int, required=True) + expected.add_argument( + "--required_enum", + type=make_choice_type_function(["titi", "toto"]), + choices=["titi", "toto"], + required=True, + ) + expected.add_argument("--opt", type=string_to_bool, default=None) + expected.add_argument("--baz", default="toto", type=str, help="help message") + expected.add_argument("--foo_str", nargs="+", default=["Hallo", "Bonjour", "Hello"], type=str) + self.argparsersEqual(parser, expected) + + def test_parse_dict(self): + parser = HfArgumentParser(BasicExample) + + args_dict = { + "foo": 12, + "bar": 3.14, + "baz": "42", + "flag": True, + } + + parsed_args = parser.parse_dict(args_dict)[0] + args = BasicExample(**args_dict) + self.assertEqual(parsed_args, args) + + def test_parse_dict_extra_key(self): + parser = HfArgumentParser(BasicExample) + + args_dict = { + "foo": 12, + "bar": 3.14, + "baz": "42", + "flag": True, + "extra": 42, + } + + self.assertRaises(ValueError, parser.parse_dict, args_dict, allow_extra_keys=False) + + def test_parse_json(self): + parser = HfArgumentParser(BasicExample) + + args_dict_for_json = { + "foo": 12, + "bar": 3.14, + "baz": "42", + "flag": True, + } + with tempfile.TemporaryDirectory() as tmp_dir: + temp_local_path = os.path.join(tmp_dir, "temp_json") + os.mkdir(temp_local_path) + with open(temp_local_path + ".json", "w+") as f: + json.dump(args_dict_for_json, f) + parsed_args = parser.parse_yaml_file(Path(temp_local_path + ".json"))[0] + + args = BasicExample(**args_dict_for_json) + self.assertEqual(parsed_args, args) + + def test_parse_yaml(self): + parser = HfArgumentParser(BasicExample) + + args_dict_for_yaml = { + "foo": 12, + "bar": 3.14, + "baz": "42", + "flag": True, + } + with tempfile.TemporaryDirectory() as tmp_dir: + temp_local_path = os.path.join(tmp_dir, "temp_yaml") + os.mkdir(temp_local_path) + with open(temp_local_path + ".yaml", "w+") as f: + yaml.dump(args_dict_for_yaml, f) + parsed_args = parser.parse_yaml_file(Path(temp_local_path + ".yaml"))[0] + args = BasicExample(**args_dict_for_yaml) + self.assertEqual(parsed_args, args) + + def test_integration_training_args(self): + parser = HfArgumentParser(TrainingArguments) + self.assertIsNotNone(parser) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_hub_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_hub_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dffc018e284cbc775e78ec5275d2861f9ad38e5b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_hub_utils.py @@ -0,0 +1,141 @@ +# 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 tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from requests.exceptions import HTTPError + +from transformers.utils import ( + CONFIG_NAME, + FLAX_WEIGHTS_NAME, + TF2_WEIGHTS_NAME, + TRANSFORMERS_CACHE, + WEIGHTS_NAME, + cached_file, + get_file_from_repo, + has_file, +) + + +RANDOM_BERT = "hf-internal-testing/tiny-random-bert" +CACHE_DIR = os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert") +FULL_COMMIT_HASH = "9b8c223d42b2188cb49d29af482996f9d0f3e5a6" + +GATED_REPO = "hf-internal-testing/dummy-gated-model" +README_FILE = "README.md" + + +class GetFromCacheTests(unittest.TestCase): + def test_cached_file(self): + archive_file = cached_file(RANDOM_BERT, CONFIG_NAME) + # Should have downloaded the file in here + self.assertTrue(os.path.isdir(CACHE_DIR)) + # Cache should contain at least those three subfolders: + for subfolder in ["blobs", "refs", "snapshots"]: + self.assertTrue(os.path.isdir(os.path.join(CACHE_DIR, subfolder))) + with open(os.path.join(CACHE_DIR, "refs", "main")) as f: + main_commit = f.read() + self.assertEqual(archive_file, os.path.join(CACHE_DIR, "snapshots", main_commit, CONFIG_NAME)) + self.assertTrue(os.path.isfile(archive_file)) + + # File is cached at the same place the second time. + new_archive_file = cached_file(RANDOM_BERT, CONFIG_NAME) + self.assertEqual(archive_file, new_archive_file) + + # Using a specific revision to test the full commit hash. + archive_file = cached_file(RANDOM_BERT, CONFIG_NAME, revision="9b8c223") + self.assertEqual(archive_file, os.path.join(CACHE_DIR, "snapshots", FULL_COMMIT_HASH, CONFIG_NAME)) + + def test_cached_file_errors(self): + with self.assertRaisesRegex(EnvironmentError, "is not a valid model identifier"): + _ = cached_file("tiny-random-bert", CONFIG_NAME) + + with self.assertRaisesRegex(EnvironmentError, "is not a valid git identifier"): + _ = cached_file(RANDOM_BERT, CONFIG_NAME, revision="aaaa") + + with self.assertRaisesRegex(EnvironmentError, "does not appear to have a file named"): + _ = cached_file(RANDOM_BERT, "conf") + + def test_non_existence_is_cached(self): + with self.assertRaisesRegex(EnvironmentError, "does not appear to have a file named"): + _ = cached_file(RANDOM_BERT, "conf") + + with open(os.path.join(CACHE_DIR, "refs", "main")) as f: + main_commit = f.read() + self.assertTrue(os.path.isfile(os.path.join(CACHE_DIR, ".no_exist", main_commit, "conf"))) + + path = cached_file(RANDOM_BERT, "conf", _raise_exceptions_for_missing_entries=False) + self.assertIsNone(path) + + path = cached_file(RANDOM_BERT, "conf", local_files_only=True, _raise_exceptions_for_missing_entries=False) + self.assertIsNone(path) + + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Under the mock environment we get a 500 error when trying to reach the tokenizer. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + path = cached_file(RANDOM_BERT, "conf", _raise_exceptions_for_connection_errors=False) + self.assertIsNone(path) + # This check we did call the fake head request + mock_head.assert_called() + + def test_has_file(self): + self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only", WEIGHTS_NAME)) + self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only", TF2_WEIGHTS_NAME)) + self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only", FLAX_WEIGHTS_NAME)) + + def test_get_file_from_repo_distant(self): + # `get_file_from_repo` returns None if the file does not exist + self.assertIsNone(get_file_from_repo("bert-base-cased", "ahah.txt")) + + # The function raises if the repository does not exist. + with self.assertRaisesRegex(EnvironmentError, "is not a valid model identifier"): + get_file_from_repo("bert-base-case", CONFIG_NAME) + + # The function raises if the revision does not exist. + with self.assertRaisesRegex(EnvironmentError, "is not a valid git identifier"): + get_file_from_repo("bert-base-cased", CONFIG_NAME, revision="ahaha") + + resolved_file = get_file_from_repo("bert-base-cased", CONFIG_NAME) + # The name is the cached name which is not very easy to test, so instead we load the content. + config = json.loads(open(resolved_file, "r").read()) + self.assertEqual(config["hidden_size"], 768) + + def test_get_file_from_repo_local(self): + with tempfile.TemporaryDirectory() as tmp_dir: + filename = Path(tmp_dir) / "a.txt" + filename.touch() + self.assertEqual(get_file_from_repo(tmp_dir, "a.txt"), str(filename)) + + self.assertIsNone(get_file_from_repo(tmp_dir, "b.txt")) + + def test_get_file_gated_repo(self): + """Test download file from a gated repo fails with correct message when not authenticated.""" + with self.assertRaisesRegex(EnvironmentError, "You are trying to access a gated repo."): + # All files except README.md are protected on a gated repo. + cached_file(GATED_REPO, "gated_file.txt", token=False) + + def test_has_file_gated_repo(self): + """Test check file existence from a gated repo fails with correct message when not authenticated.""" + with self.assertRaisesRegex(EnvironmentError, "is a gated repository"): + # All files except README.md are protected on a gated repo. + has_file(GATED_REPO, "gated_file.txt", token=False) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_image_processing_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_image_processing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..afb6283e6ed345cb1b2749a1857c6f931466bc77 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_image_processing_utils.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. +# +# 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 unittest + +from transformers.image_processing_utils import get_size_dict + + +class ImageProcessingUtilsTester(unittest.TestCase): + def test_get_size_dict(self): + # Test a dict with the wrong keys raises an error + inputs = {"wrong_key": 224} + with self.assertRaises(ValueError): + get_size_dict(inputs) + + inputs = {"height": 224} + with self.assertRaises(ValueError): + get_size_dict(inputs) + + inputs = {"width": 224, "shortest_edge": 224} + with self.assertRaises(ValueError): + get_size_dict(inputs) + + # Test a dict with the correct keys is returned as is + inputs = {"height": 224, "width": 224} + outputs = get_size_dict(inputs) + self.assertEqual(outputs, inputs) + + inputs = {"shortest_edge": 224} + outputs = get_size_dict(inputs) + self.assertEqual(outputs, {"shortest_edge": 224}) + + inputs = {"longest_edge": 224, "shortest_edge": 224} + outputs = get_size_dict(inputs) + self.assertEqual(outputs, {"longest_edge": 224, "shortest_edge": 224}) + + # Test a single int value which represents (size, size) + outputs = get_size_dict(224) + self.assertEqual(outputs, {"height": 224, "width": 224}) + + # Test a single int value which represents the shortest edge + outputs = get_size_dict(224, default_to_square=False) + self.assertEqual(outputs, {"shortest_edge": 224}) + + # Test a tuple of ints which represents (height, width) + outputs = get_size_dict((150, 200)) + self.assertEqual(outputs, {"height": 150, "width": 200}) + + # Test a tuple of ints which represents (width, height) + outputs = get_size_dict((150, 200), height_width_order=False) + self.assertEqual(outputs, {"height": 200, "width": 150}) + + # Test an int representing the shortest edge and max_size which represents the longest edge + outputs = get_size_dict(224, max_size=256, default_to_square=False) + self.assertEqual(outputs, {"shortest_edge": 224, "longest_edge": 256}) + + # Test int with default_to_square=True and max_size fails + with self.assertRaises(ValueError): + get_size_dict(224, max_size=256, default_to_square=True) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_image_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5d899c2f1ddf72e7caa48556d0cad805012e595a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_image_utils.py @@ -0,0 +1,666 @@ +# coding=utf-8 +# Copyright 2021 HuggingFace Inc. +# +# 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 os +import tempfile +import unittest + +import datasets +import numpy as np +import pytest +from huggingface_hub.file_download import http_get +from requests import ConnectTimeout, ReadTimeout + +from tests.pipelines.test_pipelines_document_question_answering import INVOICE_URL +from transformers import is_torch_available, is_vision_available +from transformers.image_utils import ChannelDimension, get_channel_dimension_axis, make_list_of_images +from transformers.testing_utils import is_flaky, require_torch, require_vision + + +if is_torch_available(): + import torch + +if is_vision_available(): + import PIL.Image + + from transformers import ImageFeatureExtractionMixin + from transformers.image_utils import get_image_size, infer_channel_dimension_format, load_image + + +def get_random_image(height, width): + random_array = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8) + return PIL.Image.fromarray(random_array) + + +@require_vision +class ImageFeatureExtractionTester(unittest.TestCase): + def test_conversion_image_to_array(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + + # Conversion with defaults (rescale + channel first) + array1 = feature_extractor.to_numpy_array(image) + self.assertTrue(array1.dtype, np.float32) + self.assertEqual(array1.shape, (3, 16, 32)) + + # Conversion with rescale and not channel first + array2 = feature_extractor.to_numpy_array(image, channel_first=False) + self.assertTrue(array2.dtype, np.float32) + self.assertEqual(array2.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array1, array2.transpose(2, 0, 1))) + + # Conversion with no rescale and channel first + array3 = feature_extractor.to_numpy_array(image, rescale=False) + self.assertTrue(array3.dtype, np.uint8) + self.assertEqual(array3.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array1, array3.astype(np.float32) * (1 / 255.0))) + + # Conversion with no rescale and not channel first + array4 = feature_extractor.to_numpy_array(image, rescale=False, channel_first=False) + self.assertTrue(array4.dtype, np.uint8) + self.assertEqual(array4.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array2, array4.astype(np.float32) * (1 / 255.0))) + + def test_conversion_array_to_array(self): + feature_extractor = ImageFeatureExtractionMixin() + array = np.random.randint(0, 256, (16, 32, 3), dtype=np.uint8) + + # By default, rescale (for an array of ints) and channel permute + array1 = feature_extractor.to_numpy_array(array) + self.assertTrue(array1.dtype, np.float32) + self.assertEqual(array1.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array1, array.transpose(2, 0, 1).astype(np.float32) * (1 / 255.0))) + + # Same with no permute + array2 = feature_extractor.to_numpy_array(array, channel_first=False) + self.assertTrue(array2.dtype, np.float32) + self.assertEqual(array2.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array2, array.astype(np.float32) * (1 / 255.0))) + + # Force rescale to False + array3 = feature_extractor.to_numpy_array(array, rescale=False) + self.assertTrue(array3.dtype, np.uint8) + self.assertEqual(array3.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array3, array.transpose(2, 0, 1))) + + # Force rescale to False and no channel permute + array4 = feature_extractor.to_numpy_array(array, rescale=False, channel_first=False) + self.assertTrue(array4.dtype, np.uint8) + self.assertEqual(array4.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array4, array)) + + # Now test the default rescale for a float array (defaults to False) + array5 = feature_extractor.to_numpy_array(array2) + self.assertTrue(array5.dtype, np.float32) + self.assertEqual(array5.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array5, array1)) + + def test_make_list_of_images_numpy(self): + # Test a single image is converted to a list of 1 image + images = np.random.randint(0, 256, (16, 32, 3)) + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 1) + self.assertTrue(np.array_equal(images_list[0], images)) + self.assertIsInstance(images_list, list) + + # Test a batch of images is converted to a list of images + images = np.random.randint(0, 256, (4, 16, 32, 3)) + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + # Test a list of images is not modified + images = [np.random.randint(0, 256, (16, 32, 3)) for _ in range(4)] + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + # Test batched masks with no channel dimension are converted to a list of masks + masks = np.random.randint(0, 2, (4, 16, 32)) + masks_list = make_list_of_images(masks, expected_ndims=2) + self.assertEqual(len(masks_list), 4) + self.assertTrue(np.array_equal(masks_list[0], masks[0])) + self.assertIsInstance(masks_list, list) + + @require_torch + def test_make_list_of_images_torch(self): + # Test a single image is converted to a list of 1 image + images = torch.randint(0, 256, (16, 32, 3)) + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 1) + self.assertTrue(np.array_equal(images_list[0], images)) + self.assertIsInstance(images_list, list) + + # Test a batch of images is converted to a list of images + images = torch.randint(0, 256, (4, 16, 32, 3)) + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + # Test a list of images is left unchanged + images = [torch.randint(0, 256, (16, 32, 3)) for _ in range(4)] + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + @require_torch + def test_conversion_torch_to_array(self): + feature_extractor = ImageFeatureExtractionMixin() + tensor = torch.randint(0, 256, (16, 32, 3)) + array = tensor.numpy() + + # By default, rescale (for a tensor of ints) and channel permute + array1 = feature_extractor.to_numpy_array(array) + self.assertTrue(array1.dtype, np.float32) + self.assertEqual(array1.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array1, array.transpose(2, 0, 1).astype(np.float32) * (1 / 255.0))) + + # Same with no permute + array2 = feature_extractor.to_numpy_array(array, channel_first=False) + self.assertTrue(array2.dtype, np.float32) + self.assertEqual(array2.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array2, array.astype(np.float32) * (1 / 255.0))) + + # Force rescale to False + array3 = feature_extractor.to_numpy_array(array, rescale=False) + self.assertTrue(array3.dtype, np.uint8) + self.assertEqual(array3.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array3, array.transpose(2, 0, 1))) + + # Force rescale to False and no channel permute + array4 = feature_extractor.to_numpy_array(array, rescale=False, channel_first=False) + self.assertTrue(array4.dtype, np.uint8) + self.assertEqual(array4.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array4, array)) + + # Now test the default rescale for a float tensor (defaults to False) + array5 = feature_extractor.to_numpy_array(array2) + self.assertTrue(array5.dtype, np.float32) + self.assertEqual(array5.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array5, array1)) + + def test_conversion_image_to_image(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + + # On an image, `to_pil_image1` is a noop. + image1 = feature_extractor.to_pil_image(image) + self.assertTrue(isinstance(image, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image), np.array(image1))) + + def test_conversion_array_to_image(self): + feature_extractor = ImageFeatureExtractionMixin() + array = np.random.randint(0, 256, (16, 32, 3), dtype=np.uint8) + + # By default, no rescale (for an array of ints) + image1 = feature_extractor.to_pil_image(array) + self.assertTrue(isinstance(image1, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image1), array)) + + # If the array is channel-first, proper reordering of the channels is done. + image2 = feature_extractor.to_pil_image(array.transpose(2, 0, 1)) + self.assertTrue(isinstance(image2, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image2), array)) + + # If the array has floating type, it's rescaled by default. + image3 = feature_extractor.to_pil_image(array.astype(np.float32) * (1 / 255.0)) + self.assertTrue(isinstance(image3, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image3), array)) + + # You can override the default to rescale. + image4 = feature_extractor.to_pil_image(array.astype(np.float32), rescale=False) + self.assertTrue(isinstance(image4, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image4), array)) + + # And with floats + channel first. + image5 = feature_extractor.to_pil_image(array.transpose(2, 0, 1).astype(np.float32) * (1 / 255.0)) + self.assertTrue(isinstance(image5, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image5), array)) + + @require_torch + def test_conversion_tensor_to_image(self): + feature_extractor = ImageFeatureExtractionMixin() + tensor = torch.randint(0, 256, (16, 32, 3)) + array = tensor.numpy() + + # By default, no rescale (for a tensor of ints) + image1 = feature_extractor.to_pil_image(tensor) + self.assertTrue(isinstance(image1, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image1), array)) + + # If the tensor is channel-first, proper reordering of the channels is done. + image2 = feature_extractor.to_pil_image(tensor.permute(2, 0, 1)) + self.assertTrue(isinstance(image2, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image2), array)) + + # If the tensor has floating type, it's rescaled by default. + image3 = feature_extractor.to_pil_image(tensor.float() / 255.0) + self.assertTrue(isinstance(image3, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image3), array)) + + # You can override the default to rescale. + image4 = feature_extractor.to_pil_image(tensor.float(), rescale=False) + self.assertTrue(isinstance(image4, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image4), array)) + + # And with floats + channel first. + image5 = feature_extractor.to_pil_image(tensor.permute(2, 0, 1).float() * (1 / 255.0)) + self.assertTrue(isinstance(image5, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image5), array)) + + def test_resize_image_and_array(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + array = np.array(image) + + # Size can be an int or a tuple of ints. + resized_image = feature_extractor.resize(image, 8) + self.assertTrue(isinstance(resized_image, PIL.Image.Image)) + self.assertEqual(resized_image.size, (8, 8)) + + resized_image1 = feature_extractor.resize(image, (8, 16)) + self.assertTrue(isinstance(resized_image1, PIL.Image.Image)) + self.assertEqual(resized_image1.size, (8, 16)) + + # Passing an array converts it to a PIL Image. + resized_image2 = feature_extractor.resize(array, 8) + self.assertTrue(isinstance(resized_image2, PIL.Image.Image)) + self.assertEqual(resized_image2.size, (8, 8)) + self.assertTrue(np.array_equal(np.array(resized_image), np.array(resized_image2))) + + resized_image3 = feature_extractor.resize(image, (8, 16)) + self.assertTrue(isinstance(resized_image3, PIL.Image.Image)) + self.assertEqual(resized_image3.size, (8, 16)) + self.assertTrue(np.array_equal(np.array(resized_image1), np.array(resized_image3))) + + def test_resize_image_and_array_non_default_to_square(self): + feature_extractor = ImageFeatureExtractionMixin() + + heights_widths = [ + # height, width + # square image + (28, 28), + (27, 27), + # rectangular image: h < w + (28, 34), + (29, 35), + # rectangular image: h > w + (34, 28), + (35, 29), + ] + + # single integer or single integer in tuple/list + sizes = [22, 27, 28, 36, [22], (27,)] + + for (height, width), size in zip(heights_widths, sizes): + for max_size in (None, 37, 1000): + image = get_random_image(height, width) + array = np.array(image) + + size = size[0] if isinstance(size, (list, tuple)) else size + # Size can be an int or a tuple of ints. + # If size is an int, smaller edge of the image will be matched to this number. + # i.e, if height > width, then image will be rescaled to (size * height / width, size). + if height < width: + exp_w, exp_h = (int(size * width / height), size) + if max_size is not None and max_size < exp_w: + exp_w, exp_h = max_size, int(max_size * exp_h / exp_w) + elif width < height: + exp_w, exp_h = (size, int(size * height / width)) + if max_size is not None and max_size < exp_h: + exp_w, exp_h = int(max_size * exp_w / exp_h), max_size + else: + exp_w, exp_h = (size, size) + if max_size is not None and max_size < size: + exp_w, exp_h = max_size, max_size + + resized_image = feature_extractor.resize(image, size=size, default_to_square=False, max_size=max_size) + self.assertTrue(isinstance(resized_image, PIL.Image.Image)) + self.assertEqual(resized_image.size, (exp_w, exp_h)) + + # Passing an array converts it to a PIL Image. + resized_image2 = feature_extractor.resize(array, size=size, default_to_square=False, max_size=max_size) + self.assertTrue(isinstance(resized_image2, PIL.Image.Image)) + self.assertEqual(resized_image2.size, (exp_w, exp_h)) + self.assertTrue(np.array_equal(np.array(resized_image), np.array(resized_image2))) + + @require_torch + def test_resize_tensor(self): + feature_extractor = ImageFeatureExtractionMixin() + tensor = torch.randint(0, 256, (16, 32, 3)) + array = tensor.numpy() + + # Size can be an int or a tuple of ints. + resized_image = feature_extractor.resize(tensor, 8) + self.assertTrue(isinstance(resized_image, PIL.Image.Image)) + self.assertEqual(resized_image.size, (8, 8)) + + resized_image1 = feature_extractor.resize(tensor, (8, 16)) + self.assertTrue(isinstance(resized_image1, PIL.Image.Image)) + self.assertEqual(resized_image1.size, (8, 16)) + + # Check we get the same results as with NumPy arrays. + resized_image2 = feature_extractor.resize(array, 8) + self.assertTrue(np.array_equal(np.array(resized_image), np.array(resized_image2))) + + resized_image3 = feature_extractor.resize(array, (8, 16)) + self.assertTrue(np.array_equal(np.array(resized_image1), np.array(resized_image3))) + + def test_normalize_image(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + array = np.array(image) + mean = [0.1, 0.5, 0.9] + std = [0.2, 0.4, 0.6] + + # PIL Image are converted to NumPy arrays for the normalization + normalized_image = feature_extractor.normalize(image, mean, std) + self.assertTrue(isinstance(normalized_image, np.ndarray)) + self.assertEqual(normalized_image.shape, (3, 16, 32)) + + # During the conversion rescale and channel first will be applied. + expected = array.transpose(2, 0, 1).astype(np.float32) * (1 / 255.0) + np_mean = np.array(mean).astype(np.float32)[:, None, None] + np_std = np.array(std).astype(np.float32)[:, None, None] + expected = (expected - np_mean) / np_std + self.assertTrue(np.array_equal(normalized_image, expected)) + + def test_normalize_array(self): + feature_extractor = ImageFeatureExtractionMixin() + array = np.random.random((16, 32, 3)) + mean = [0.1, 0.5, 0.9] + std = [0.2, 0.4, 0.6] + + # mean and std can be passed as lists or NumPy arrays. + expected = (array - np.array(mean)) / np.array(std) + normalized_array = feature_extractor.normalize(array, mean, std) + self.assertTrue(np.array_equal(normalized_array, expected)) + + normalized_array = feature_extractor.normalize(array, np.array(mean), np.array(std)) + self.assertTrue(np.array_equal(normalized_array, expected)) + + # Normalize will detect automatically if channel first or channel last is used. + array = np.random.random((3, 16, 32)) + expected = (array - np.array(mean)[:, None, None]) / np.array(std)[:, None, None] + normalized_array = feature_extractor.normalize(array, mean, std) + self.assertTrue(np.array_equal(normalized_array, expected)) + + normalized_array = feature_extractor.normalize(array, np.array(mean), np.array(std)) + self.assertTrue(np.array_equal(normalized_array, expected)) + + @require_torch + def test_normalize_tensor(self): + feature_extractor = ImageFeatureExtractionMixin() + tensor = torch.rand(16, 32, 3) + mean = [0.1, 0.5, 0.9] + std = [0.2, 0.4, 0.6] + + # mean and std can be passed as lists or tensors. + expected = (tensor - torch.tensor(mean)) / torch.tensor(std) + normalized_tensor = feature_extractor.normalize(tensor, mean, std) + self.assertTrue(torch.equal(normalized_tensor, expected)) + + normalized_tensor = feature_extractor.normalize(tensor, torch.tensor(mean), torch.tensor(std)) + self.assertTrue(torch.equal(normalized_tensor, expected)) + + # Normalize will detect automatically if channel first or channel last is used. + tensor = torch.rand(3, 16, 32) + expected = (tensor - torch.tensor(mean)[:, None, None]) / torch.tensor(std)[:, None, None] + normalized_tensor = feature_extractor.normalize(tensor, mean, std) + self.assertTrue(torch.equal(normalized_tensor, expected)) + + normalized_tensor = feature_extractor.normalize(tensor, torch.tensor(mean), torch.tensor(std)) + self.assertTrue(torch.equal(normalized_tensor, expected)) + + def test_center_crop_image(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + + # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions. + crop_sizes = [8, (8, 64), 20, (32, 64)] + for size in crop_sizes: + cropped_image = feature_extractor.center_crop(image, size) + self.assertTrue(isinstance(cropped_image, PIL.Image.Image)) + + # PIL Image.size is transposed compared to NumPy or PyTorch (width first instead of height first). + expected_size = (size, size) if isinstance(size, int) else (size[1], size[0]) + self.assertEqual(cropped_image.size, expected_size) + + def test_center_crop_array(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + array = feature_extractor.to_numpy_array(image) + + # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions. + crop_sizes = [8, (8, 64), 20, (32, 64)] + for size in crop_sizes: + cropped_array = feature_extractor.center_crop(array, size) + self.assertTrue(isinstance(cropped_array, np.ndarray)) + + expected_size = (size, size) if isinstance(size, int) else size + self.assertEqual(cropped_array.shape[-2:], expected_size) + + # Check result is consistent with PIL.Image.crop + cropped_image = feature_extractor.center_crop(image, size) + self.assertTrue(np.array_equal(cropped_array, feature_extractor.to_numpy_array(cropped_image))) + + @require_torch + def test_center_crop_tensor(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + array = feature_extractor.to_numpy_array(image) + tensor = torch.tensor(array) + + # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions. + crop_sizes = [8, (8, 64), 20, (32, 64)] + for size in crop_sizes: + cropped_tensor = feature_extractor.center_crop(tensor, size) + self.assertTrue(isinstance(cropped_tensor, torch.Tensor)) + + expected_size = (size, size) if isinstance(size, int) else size + self.assertEqual(cropped_tensor.shape[-2:], expected_size) + + # Check result is consistent with PIL.Image.crop + cropped_image = feature_extractor.center_crop(image, size) + self.assertTrue(torch.equal(cropped_tensor, torch.tensor(feature_extractor.to_numpy_array(cropped_image)))) + + +@require_vision +class LoadImageTester(unittest.TestCase): + def test_load_img_url(self): + img = load_image(INVOICE_URL) + img_arr = np.array(img) + + self.assertEqual(img_arr.shape, (1061, 750, 3)) + + @is_flaky() + def test_load_img_url_timeout(self): + with self.assertRaises((ReadTimeout, ConnectTimeout)): + load_image(INVOICE_URL, timeout=0.001) + + def test_load_img_local(self): + img = load_image("./tests/fixtures/tests_samples/COCO/000000039769.png") + img_arr = np.array(img) + + self.assertEqual( + img_arr.shape, + (480, 640, 3), + ) + + def test_load_img_base64_prefix(self): + try: + tmp_file = tempfile.mktemp() + with open(tmp_file, "wb") as f: + http_get( + "https://huggingface.co/datasets/hf-internal-testing/dummy-base64-images/raw/main/image_0.txt", f + ) + + with open(tmp_file, encoding="utf-8") as b64: + img = load_image(b64.read()) + img_arr = np.array(img) + + finally: + os.remove(tmp_file) + + self.assertEqual(img_arr.shape, (64, 32, 3)) + + def test_load_img_base64(self): + try: + tmp_file = tempfile.mktemp() + with open(tmp_file, "wb") as f: + http_get( + "https://huggingface.co/datasets/hf-internal-testing/dummy-base64-images/raw/main/image_1.txt", f + ) + + with open(tmp_file, encoding="utf-8") as b64: + img = load_image(b64.read()) + img_arr = np.array(img) + + finally: + os.remove(tmp_file) + + self.assertEqual(img_arr.shape, (64, 32, 3)) + + def test_load_img_rgba(self): + dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test") + + img = load_image(dataset[0]["file"]) # img with mode RGBA + img_arr = np.array(img) + + self.assertEqual( + img_arr.shape, + (512, 512, 3), + ) + + def test_load_img_la(self): + dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test") + + img = load_image(dataset[1]["file"]) # img with mode LA + img_arr = np.array(img) + + self.assertEqual( + img_arr.shape, + (512, 768, 3), + ) + + def test_load_img_l(self): + dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test") + + img = load_image(dataset[2]["file"]) # img with mode L + img_arr = np.array(img) + + self.assertEqual( + img_arr.shape, + (381, 225, 3), + ) + + def test_load_img_exif_transpose(self): + dataset = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", "image", split="test") + img_file = dataset[3]["file"] + + img_without_exif_transpose = PIL.Image.open(img_file) + img_arr_without_exif_transpose = np.array(img_without_exif_transpose) + + self.assertEqual( + img_arr_without_exif_transpose.shape, + (333, 500, 3), + ) + + img_with_exif_transpose = load_image(img_file) + img_arr_with_exif_transpose = np.array(img_with_exif_transpose) + + self.assertEqual( + img_arr_with_exif_transpose.shape, + (500, 333, 3), + ) + + +class UtilFunctionTester(unittest.TestCase): + def test_get_image_size(self): + # Test we can infer the size and channel dimension of an image. + image = np.random.randint(0, 256, (32, 64, 3)) + self.assertEqual(get_image_size(image), (32, 64)) + + image = np.random.randint(0, 256, (3, 32, 64)) + self.assertEqual(get_image_size(image), (32, 64)) + + # Test the channel dimension can be overriden + image = np.random.randint(0, 256, (3, 32, 64)) + self.assertEqual(get_image_size(image, channel_dim=ChannelDimension.LAST), (3, 32)) + + def test_infer_channel_dimension(self): + # Test we fail with invalid input + with pytest.raises(ValueError): + infer_channel_dimension_format(np.random.randint(0, 256, (10, 10))) + + with pytest.raises(ValueError): + infer_channel_dimension_format(np.random.randint(0, 256, (10, 10, 10, 10, 10))) + + # Test we fail if neither first not last dimension is of size 3 or 1 + with pytest.raises(ValueError): + infer_channel_dimension_format(np.random.randint(0, 256, (10, 1, 50))) + + # But if we explicitly set one of the number of channels to 50 it works + inferred_dim = infer_channel_dimension_format(np.random.randint(0, 256, (10, 1, 50)), num_channels=50) + self.assertEqual(inferred_dim, ChannelDimension.LAST) + + # Test we correctly identify the channel dimension + image = np.random.randint(0, 256, (3, 4, 5)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.FIRST) + + image = np.random.randint(0, 256, (1, 4, 5)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.FIRST) + + image = np.random.randint(0, 256, (4, 5, 3)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.LAST) + + image = np.random.randint(0, 256, (4, 5, 1)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.LAST) + + # We can take a batched array of images and find the dimension + image = np.random.randint(0, 256, (1, 3, 4, 5)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.FIRST) + + def test_get_channel_dimension_axis(self): + # Test we correctly identify the channel dimension + image = np.random.randint(0, 256, (3, 4, 5)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 0) + + image = np.random.randint(0, 256, (1, 4, 5)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 0) + + image = np.random.randint(0, 256, (4, 5, 3)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 2) + + image = np.random.randint(0, 256, (4, 5, 1)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 2) + + # We can take a batched array of images and find the dimension + image = np.random.randint(0, 256, (1, 3, 4, 5)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 1) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_logging.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bbb824365108541d6e22cb0cae09c355e14b50 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_logging.py @@ -0,0 +1,135 @@ +# 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 os +import unittest + +from huggingface_hub.utils import are_progress_bars_disabled + +import transformers.models.bart.tokenization_bart +from transformers import logging +from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context +from transformers.utils.logging import disable_progress_bar, enable_progress_bar + + +class HfArgumentParserTest(unittest.TestCase): + def test_set_level(self): + logger = logging.get_logger() + + # the current default level is logging.WARNING + level_origin = logging.get_verbosity() + + logging.set_verbosity_error() + self.assertEqual(logger.getEffectiveLevel(), logging.get_verbosity()) + + logging.set_verbosity_warning() + self.assertEqual(logger.getEffectiveLevel(), logging.get_verbosity()) + + logging.set_verbosity_info() + self.assertEqual(logger.getEffectiveLevel(), logging.get_verbosity()) + + logging.set_verbosity_debug() + self.assertEqual(logger.getEffectiveLevel(), logging.get_verbosity()) + + # restore to the original level + logging.set_verbosity(level_origin) + + def test_integration(self): + level_origin = logging.get_verbosity() + + logger = logging.get_logger("transformers.models.bart.tokenization_bart") + msg = "Testing 1, 2, 3" + + # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) + if level_origin <= logging.WARNING: + with CaptureLogger(logger) as cl: + logger.warning(msg) + self.assertEqual(cl.out, msg + "\n") + + # this is setting the level for all of `transformers.*` loggers + logging.set_verbosity_error() + + # should not be able to log warnings + with CaptureLogger(logger) as cl: + logger.warning(msg) + self.assertEqual(cl.out, "") + + # should be able to log warnings again + logging.set_verbosity_warning() + with CaptureLogger(logger) as cl: + logger.warning(msg) + self.assertEqual(cl.out, msg + "\n") + + # restore to the original level + logging.set_verbosity(level_origin) + + @mockenv(TRANSFORMERS_VERBOSITY="error") + def test_env_override(self): + # reset for the env var to take effect, next time some logger call is made + transformers.utils.logging._reset_library_root_logger() + # this action activates the env var + _ = logging.get_logger("transformers.models.bart.tokenization_bart") + + env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None) + env_level = logging.log_levels[env_level_str] + + current_level = logging.get_verbosity() + self.assertEqual( + env_level, + current_level, + f"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}", + ) + + # restore to the original level + os.environ["TRANSFORMERS_VERBOSITY"] = "" + transformers.utils.logging._reset_library_root_logger() + + @mockenv(TRANSFORMERS_VERBOSITY="super-error") + def test_env_invalid_override(self): + # reset for the env var to take effect, next time some logger call is made + transformers.utils.logging._reset_library_root_logger() + logger = logging.logging.getLogger() + with CaptureLogger(logger) as cl: + # this action activates the env var + logging.get_logger("transformers.models.bart.tokenization_bart") + self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error", cl.out) + + # no need to restore as nothing was changed + + def test_advisory_warnings(self): + # testing `logger.warning_advice()` + transformers.utils.logging._reset_library_root_logger() + + logger = logging.get_logger("transformers.models.bart.tokenization_bart") + msg = "Testing 1, 2, 3" + + with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1"): + # nothing should be logged as env var disables this method + with CaptureLogger(logger) as cl: + logger.warning_advice(msg) + self.assertEqual(cl.out, "") + + with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=""): + # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset + with CaptureLogger(logger) as cl: + logger.warning_advice(msg) + self.assertEqual(cl.out, msg + "\n") + + +def test_set_progress_bar_enabled(): + disable_progress_bar() + assert are_progress_bars_disabled() + + enable_progress_bar() + assert not are_progress_bars_disabled() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_model_card.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_model_card.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0e8795e0aab9f920de802d8f15c716affc5f41 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_model_card.py @@ -0,0 +1,84 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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 tempfile +import unittest + +from transformers.modelcard import ModelCard + + +class ModelCardTester(unittest.TestCase): + def setUp(self): + self.inputs_dict = { + "model_details": { + "Organization": "testing", + "Model date": "today", + "Model version": "v2.1, Developed by Test Corp in 2019.", + "Architecture": "Convolutional Neural Network.", + }, + "metrics": "BLEU and ROUGE-1", + "evaluation_data": { + "Datasets": {"BLEU": "My-great-dataset-v1", "ROUGE-1": "My-short-dataset-v2.1"}, + "Preprocessing": "See details on https://arxiv.org/pdf/1810.03993.pdf", + }, + "training_data": { + "Dataset": "English Wikipedia dump dated 2018-12-01", + "Preprocessing": ( + "Using SentencePiece vocabulary of size 52k tokens. See details on" + " https://arxiv.org/pdf/1810.03993.pdf" + ), + }, + "quantitative_analyses": {"BLEU": 55.1, "ROUGE-1": 76}, + } + + def test_model_card_common_properties(self): + modelcard = ModelCard.from_dict(self.inputs_dict) + self.assertTrue(hasattr(modelcard, "model_details")) + self.assertTrue(hasattr(modelcard, "intended_use")) + self.assertTrue(hasattr(modelcard, "factors")) + self.assertTrue(hasattr(modelcard, "metrics")) + self.assertTrue(hasattr(modelcard, "evaluation_data")) + self.assertTrue(hasattr(modelcard, "training_data")) + self.assertTrue(hasattr(modelcard, "quantitative_analyses")) + self.assertTrue(hasattr(modelcard, "ethical_considerations")) + self.assertTrue(hasattr(modelcard, "caveats_and_recommendations")) + + def test_model_card_to_json_string(self): + modelcard = ModelCard.from_dict(self.inputs_dict) + obj = json.loads(modelcard.to_json_string()) + for key, value in self.inputs_dict.items(): + self.assertEqual(obj[key], value) + + def test_model_card_to_json_file(self): + model_card_first = ModelCard.from_dict(self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + filename = os.path.join(tmpdirname, "modelcard.json") + model_card_first.to_json_file(filename) + model_card_second = ModelCard.from_json_file(filename) + + self.assertEqual(model_card_second.to_dict(), model_card_first.to_dict()) + + def test_model_card_from_and_save_pretrained(self): + model_card_first = ModelCard.from_dict(self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + model_card_first.save_pretrained(tmpdirname) + model_card_second = ModelCard.from_pretrained(tmpdirname) + + self.assertEqual(model_card_second.to_dict(), model_card_first.to_dict()) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_model_output.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_model_output.py new file mode 100644 index 0000000000000000000000000000000000000000..cabdc5fc2d6b0f11c4c9edbf78ffa61de849cdb0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_model_output.py @@ -0,0 +1,167 @@ +# coding=utf-8 +# Copyright 2020 The Hugging Face Team. +# +# 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 unittest +from dataclasses import dataclass +from typing import Optional + +from transformers.testing_utils import require_torch +from transformers.utils import ModelOutput + + +@dataclass +class ModelOutputTest(ModelOutput): + a: float + b: Optional[float] = None + c: Optional[float] = None + + +class ModelOutputTester(unittest.TestCase): + def test_get_attributes(self): + x = ModelOutputTest(a=30) + self.assertEqual(x.a, 30) + self.assertIsNone(x.b) + self.assertIsNone(x.c) + with self.assertRaises(AttributeError): + _ = x.d + + def test_index_with_ints_and_slices(self): + x = ModelOutputTest(a=30, b=10) + self.assertEqual(x[0], 30) + self.assertEqual(x[1], 10) + self.assertEqual(x[:2], (30, 10)) + self.assertEqual(x[:], (30, 10)) + + x = ModelOutputTest(a=30, c=10) + self.assertEqual(x[0], 30) + self.assertEqual(x[1], 10) + self.assertEqual(x[:2], (30, 10)) + self.assertEqual(x[:], (30, 10)) + + def test_index_with_strings(self): + x = ModelOutputTest(a=30, b=10) + self.assertEqual(x["a"], 30) + self.assertEqual(x["b"], 10) + with self.assertRaises(KeyError): + _ = x["c"] + + x = ModelOutputTest(a=30, c=10) + self.assertEqual(x["a"], 30) + self.assertEqual(x["c"], 10) + with self.assertRaises(KeyError): + _ = x["b"] + + def test_dict_like_properties(self): + x = ModelOutputTest(a=30) + self.assertEqual(list(x.keys()), ["a"]) + self.assertEqual(list(x.values()), [30]) + self.assertEqual(list(x.items()), [("a", 30)]) + self.assertEqual(list(x), ["a"]) + + x = ModelOutputTest(a=30, b=10) + self.assertEqual(list(x.keys()), ["a", "b"]) + self.assertEqual(list(x.values()), [30, 10]) + self.assertEqual(list(x.items()), [("a", 30), ("b", 10)]) + self.assertEqual(list(x), ["a", "b"]) + + x = ModelOutputTest(a=30, c=10) + self.assertEqual(list(x.keys()), ["a", "c"]) + self.assertEqual(list(x.values()), [30, 10]) + self.assertEqual(list(x.items()), [("a", 30), ("c", 10)]) + self.assertEqual(list(x), ["a", "c"]) + + with self.assertRaises(Exception): + x = x.update({"d": 20}) + with self.assertRaises(Exception): + del x["a"] + with self.assertRaises(Exception): + _ = x.pop("a") + with self.assertRaises(Exception): + _ = x.setdefault("d", 32) + + def test_set_attributes(self): + x = ModelOutputTest(a=30) + x.a = 10 + self.assertEqual(x.a, 10) + self.assertEqual(x["a"], 10) + + def test_set_keys(self): + x = ModelOutputTest(a=30) + x["a"] = 10 + self.assertEqual(x.a, 10) + self.assertEqual(x["a"], 10) + + def test_instantiate_from_dict(self): + x = ModelOutputTest({"a": 30, "b": 10}) + self.assertEqual(list(x.keys()), ["a", "b"]) + self.assertEqual(x.a, 30) + self.assertEqual(x.b, 10) + + def test_instantiate_from_iterator(self): + x = ModelOutputTest([("a", 30), ("b", 10)]) + self.assertEqual(list(x.keys()), ["a", "b"]) + self.assertEqual(x.a, 30) + self.assertEqual(x.b, 10) + + with self.assertRaises(ValueError): + _ = ModelOutputTest([("a", 30), (10, 10)]) + + x = ModelOutputTest(a=(30, 30)) + self.assertEqual(list(x.keys()), ["a"]) + self.assertEqual(x.a, (30, 30)) + + @require_torch + def test_torch_pytree(self): + # ensure torch.utils._pytree treats ModelOutput subclasses as nodes (and not leaves) + # this is important for DistributedDataParallel gradient synchronization with static_graph=True + import torch.utils._pytree as pytree + + x = ModelOutput({"a": 1.0, "c": 2.0}) + self.assertFalse(pytree._is_leaf(x)) + + x = ModelOutputTest(a=1.0, c=2.0) + self.assertFalse(pytree._is_leaf(x)) + + expected_flat_outs = [1.0, 2.0] + expected_tree_spec = pytree.TreeSpec( + ModelOutputTest, (ModelOutputTest, ["a", "c"]), [pytree.LeafSpec(), pytree.LeafSpec()] + ) + + actual_flat_outs, actual_tree_spec = pytree.tree_flatten(x) + self.assertEqual(expected_flat_outs, actual_flat_outs) + self.assertEqual(expected_tree_spec, actual_tree_spec) + + unflattened_x = pytree.tree_unflatten(actual_flat_outs, actual_tree_spec) + self.assertEqual(x, unflattened_x) + + +class ModelOutputTestNoDataclass(ModelOutput): + """Invalid test subclass of ModelOutput where @dataclass decorator is not used""" + + a: float + b: Optional[float] = None + c: Optional[float] = None + + +class ModelOutputSubclassTester(unittest.TestCase): + def test_direct_model_output(self): + # Check that direct usage of ModelOutput instantiates without errors + ModelOutput({"a": 1.1}) + + def test_subclass_no_dataclass(self): + # Check that a subclass of ModelOutput without @dataclass is invalid + # A valid subclass is inherently tested other unit tests above. + with self.assertRaises(TypeError): + ModelOutputTestNoDataclass(a=1.1, b=2.2, c=3.3) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_modeling_tf_core.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_modeling_tf_core.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd5dfda6bc01989b82d5f8a9c5d6aa6297d90a1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_modeling_tf_core.py @@ -0,0 +1,417 @@ +# coding=utf-8 +# Copyright 2019 HuggingFace Inc. +# +# 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. + + +from __future__ import annotations + +import copy +import os +import tempfile +from importlib import import_module +from math import isnan + +from transformers import is_tf_available +from transformers.models.auto import get_values +from transformers.testing_utils import _tf_gpu_memory_limit, require_tf, slow + +from ..test_modeling_tf_common import ids_tensor + + +if is_tf_available(): + import numpy as np + import tensorflow as tf + + from transformers import ( + TF_MODEL_FOR_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_MASKED_LM_MAPPING, + TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, + TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, + TF_MODEL_FOR_PRETRAINING_MAPPING, + TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, + TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, + TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, + TFSharedEmbeddings, + ) + + if _tf_gpu_memory_limit is not None: + gpus = tf.config.list_physical_devices("GPU") + for gpu in gpus: + # Restrict TensorFlow to only allocate x GB of memory on the GPUs + try: + tf.config.set_logical_device_configuration( + gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)] + ) + logical_gpus = tf.config.list_logical_devices("GPU") + print("Logical GPUs", logical_gpus) + except RuntimeError as e: + # Virtual devices must be set before GPUs have been initialized + print(e) + + +@require_tf +class TFCoreModelTesterMixin: + model_tester = None + all_model_classes = () + all_generative_model_classes = () + test_mismatched_shapes = True + test_resize_embeddings = True + test_head_masking = True + is_encoder_decoder = False + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False) -> dict: + inputs_dict = copy.deepcopy(inputs_dict) + + if model_class in get_values(TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING): + inputs_dict = { + k: tf.tile(tf.expand_dims(v, 1), (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)) + if isinstance(v, tf.Tensor) and v.ndim > 0 + else v + for k, v in inputs_dict.items() + } + + if return_labels: + if model_class in get_values(TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING): + inputs_dict["labels"] = tf.ones(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in get_values(TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING): + inputs_dict["start_positions"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + inputs_dict["end_positions"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in [ + *get_values(TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING), + *get_values(TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING), + ]: + inputs_dict["labels"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in get_values(TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING): + inputs_dict["next_sentence_label"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) + elif model_class in [ + *get_values(TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING), + *get_values(TF_MODEL_FOR_CAUSAL_LM_MAPPING), + *get_values(TF_MODEL_FOR_MASKED_LM_MAPPING), + *get_values(TF_MODEL_FOR_PRETRAINING_MAPPING), + *get_values(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING), + ]: + inputs_dict["labels"] = tf.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=tf.int32 + ) + return inputs_dict + + @slow + def test_graph_mode(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes[:2]: + inputs = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @tf.function + def run_in_graph_mode(): + return model(inputs) + + outputs = run_in_graph_mode() + self.assertIsNotNone(outputs) + + @slow + def test_xla_mode(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes[:2]: + inputs = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + + @tf.function(experimental_compile=True) + def run_in_graph_mode(): + return model(inputs) + + outputs = run_in_graph_mode() + self.assertIsNotNone(outputs) + + @slow + def test_xla_fit(self): + # This is a copy of the test_keras_fit method, but we use XLA compilation instead of eager + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes[:2]: + model = model_class(config) + if getattr(model, "hf_compute_loss", None): + # Test that model correctly compute the loss with kwargs + prepared_for_class = self._prepare_for_class(inputs_dict.copy(), model_class, return_labels=True) + # Is there a better way to remove these decoder inputs? + prepared_for_class = { + key: val + for key, val in prepared_for_class.items() + if key not in ("head_mask", "decoder_head_mask", "cross_attn_head_mask", "decoder_input_ids") + } + + possible_label_cols = { + "labels", + "label", + "label_ids", + "start_positions", + "start_position", + "end_positions", + "end_position", + "next_sentence_label", + } + label_names = possible_label_cols.intersection(set(prepared_for_class)) + self.assertGreater(len(label_names), 0, msg="No matching label names found!") + labels = {key: val for key, val in prepared_for_class.items() if key in label_names} + inputs_minus_labels = {key: val for key, val in prepared_for_class.items() if key not in label_names} + self.assertGreater(len(inputs_minus_labels), 0) + + # Make sure it works with XLA! + model.compile(optimizer=tf.keras.optimizers.SGD(0.0), jit_compile=True) + # Make sure the model fits without crashing regardless of where we pass the labels + history = model.fit( + prepared_for_class, + validation_data=prepared_for_class, + steps_per_epoch=1, + validation_steps=1, + shuffle=False, + verbose=0, + ) + loss = history.history["loss"][0] + self.assertTrue(not isnan(loss)) + val_loss = history.history["val_loss"][0] + self.assertTrue(not isnan(val_loss)) + + # Now test it with separate labels, to make sure that path works in XLA too. + model = model_class(config) + model.compile(optimizer=tf.keras.optimizers.SGD(0.0), jit_compile=True) + history = model.fit( + inputs_minus_labels, + labels, + validation_data=(inputs_minus_labels, labels), + steps_per_epoch=1, + validation_steps=1, + shuffle=False, + verbose=0, + ) + + loss = history.history["loss"][0] + self.assertTrue(not isnan(loss)) + val_loss = history.history["val_loss"][0] + self.assertTrue(not isnan(val_loss)) + + @slow + def test_saved_model_creation_extended(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + config.output_attentions = True + + if hasattr(config, "use_cache"): + config.use_cache = True + + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", self.model_tester.seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + for model_class in self.all_model_classes[:2]: + class_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + model.build() + num_out = len(model(class_inputs_dict)) + + for key in list(class_inputs_dict.keys()): + # Remove keys not in the serving signature, as the SavedModel will not be compiled to deal with them + if key not in model.input_signature: + del class_inputs_dict[key] + # Check it's a tensor, in case the inputs dict has some bools in it too + elif isinstance(class_inputs_dict[key], tf.Tensor) and class_inputs_dict[key].dtype.is_integer: + class_inputs_dict[key] = tf.cast(class_inputs_dict[key], tf.int32) + + if set(class_inputs_dict.keys()) != set(model.input_signature.keys()): + continue # Some models have inputs that the preparation functions don't create, we skip those + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, saved_model=True) + saved_model_dir = os.path.join(tmpdirname, "saved_model", "1") + model = tf.keras.models.load_model(saved_model_dir) + outputs = model(class_inputs_dict) + + if self.is_encoder_decoder: + output_hidden_states = outputs["encoder_hidden_states"] + output_attentions = outputs["encoder_attentions"] + else: + output_hidden_states = outputs["hidden_states"] + output_attentions = outputs["attentions"] + + self.assertEqual(len(outputs), num_out) + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + + self.assertEqual(len(output_hidden_states), expected_num_layers) + self.assertListEqual( + list(output_hidden_states[0].shape[-2:]), + [self.model_tester.seq_length, self.model_tester.hidden_size], + ) + + self.assertEqual(len(output_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(output_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + @slow + def test_mixed_precision(self): + tf.keras.mixed_precision.set_global_policy("mixed_float16") + + # try/finally block to ensure subsequent tests run in float32 + try: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes[:2]: + class_inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config) + outputs = model(class_inputs_dict) + + self.assertIsNotNone(outputs) + finally: + tf.keras.mixed_precision.set_global_policy("float32") + + @slow + def test_train_pipeline_custom_model(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + # head_mask and decoder_head_mask has different shapes than other input args + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + if "decoder_head_mask" in inputs_dict: + del inputs_dict["decoder_head_mask"] + if "cross_attn_head_mask" in inputs_dict: + del inputs_dict["cross_attn_head_mask"] + tf_main_layer_classes = { + module_member + for model_class in self.all_model_classes + for module in (import_module(model_class.__module__),) + for module_member_name in dir(module) + if module_member_name.endswith("MainLayer") + for module_member in (getattr(module, module_member_name),) + if isinstance(module_member, type) + and tf.keras.layers.Layer in module_member.__bases__ + and getattr(module_member, "_keras_serializable", False) + } + + for main_layer_class in tf_main_layer_classes: + # T5MainLayer needs an embed_tokens parameter when called without the inputs_embeds parameter + if "T5" in main_layer_class.__name__: + # Take the same values than in TFT5ModelTester for this shared layer + shared = TFSharedEmbeddings(self.model_tester.vocab_size, self.model_tester.hidden_size, name="shared") + config.use_cache = False + main_layer = main_layer_class(config, embed_tokens=shared) + else: + main_layer = main_layer_class(config) + + symbolic_inputs = { + name: tf.keras.Input(tensor.shape[1:], dtype=tensor.dtype) for name, tensor in inputs_dict.items() + } + + if hasattr(self.model_tester, "num_labels"): + num_labels = self.model_tester.num_labels + else: + num_labels = 2 + + X = tf.data.Dataset.from_tensor_slices( + (inputs_dict, np.ones((self.model_tester.batch_size, self.model_tester.seq_length, num_labels, 1))) + ).batch(1) + + hidden_states = main_layer(symbolic_inputs)[0] + outputs = tf.keras.layers.Dense(num_labels, activation="softmax", name="outputs")(hidden_states) + model = tf.keras.models.Model(inputs=symbolic_inputs, outputs=[outputs]) + + model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["binary_accuracy"]) + model.fit(X, epochs=1) + + with tempfile.TemporaryDirectory() as tmpdirname: + filepath = os.path.join(tmpdirname, "keras_model.h5") + model.save(filepath) + if "T5" in main_layer_class.__name__: + model = tf.keras.models.load_model( + filepath, + custom_objects={ + main_layer_class.__name__: main_layer_class, + "TFSharedEmbeddings": TFSharedEmbeddings, + }, + ) + else: + model = tf.keras.models.load_model( + filepath, custom_objects={main_layer_class.__name__: main_layer_class} + ) + assert isinstance(model, tf.keras.Model) + model(inputs_dict) + + @slow + def test_graph_mode_with_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes[:2]: + model = model_class(config) + + inputs = copy.deepcopy(inputs_dict) + + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + del inputs["input_ids"] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + + if not self.is_encoder_decoder: + inputs["inputs_embeds"] = model.get_input_embeddings()(input_ids) + else: + inputs["inputs_embeds"] = model.get_input_embeddings()(encoder_input_ids) + inputs["decoder_inputs_embeds"] = model.get_input_embeddings()(decoder_input_ids) + + inputs = self._prepare_for_class(inputs, model_class) + + @tf.function + def run_in_graph_mode(): + return model(inputs) + + outputs = run_in_graph_mode() + self.assertIsNotNone(outputs) + + def _generate_random_bad_tokens(self, num_bad_tokens, model): + # special tokens cannot be bad tokens + special_tokens = [] + if model.config.bos_token_id is not None: + special_tokens.append(model.config.bos_token_id) + if model.config.pad_token_id is not None: + special_tokens.append(model.config.pad_token_id) + if model.config.eos_token_id is not None: + special_tokens.append(model.config.eos_token_id) + + # create random bad tokens that are not special tokens + bad_tokens = [] + while len(bad_tokens) < num_bad_tokens: + token = tf.squeeze(ids_tensor((1, 1), self.model_tester.vocab_size), 0).numpy()[0] + if token not in special_tokens: + bad_tokens.append(token) + return bad_tokens + + def _check_generated_ids(self, output_ids): + for token_id in output_ids[0].numpy().tolist(): + self.assertGreaterEqual(token_id, 0) + self.assertLess(token_id, self.model_tester.vocab_size) + + def _check_match_tokens(self, generated_ids, bad_words_ids): + # for all bad word tokens + for bad_word_ids in bad_words_ids: + # for all slices in batch + for generated_ids_slice in generated_ids: + # for all word idx + for i in range(len(bad_word_ids), len(generated_ids_slice)): + # if tokens match + if generated_ids_slice[i - len(bad_word_ids) : i] == bad_word_ids: + return True + return False diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_offline.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_offline.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc7938bf3802e6bf4758094c4041bc50f482098 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_offline.py @@ -0,0 +1,206 @@ +# 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 subprocess +import sys + +from transformers import BertConfig, BertModel, BertTokenizer, pipeline +from transformers.testing_utils import TestCasePlus, require_torch + + +class OfflineTests(TestCasePlus): + @require_torch + def test_offline_mode(self): + # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before + # `transformers` is loaded, and it's too late for inside pytest - so we are changing it + # while running an external program + + # python one-liner segments + + # this must be loaded before socket.socket is monkey-patched + load = """ +from transformers import BertConfig, BertModel, BertTokenizer, pipeline + """ + + run = """ +mname = "hf-internal-testing/tiny-random-bert" +BertConfig.from_pretrained(mname) +BertModel.from_pretrained(mname) +BertTokenizer.from_pretrained(mname) +pipe = pipeline(task="fill-mask", model=mname) +print("success") + """ + + mock = """ +import socket +def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn't access internet") +socket.socket = offline_socket + """ + + # Force fetching the files so that we can use the cache + mname = "hf-internal-testing/tiny-random-bert" + BertConfig.from_pretrained(mname) + BertModel.from_pretrained(mname) + BertTokenizer.from_pretrained(mname) + pipeline(task="fill-mask", model=mname) + + # baseline - just load from_pretrained with normal network + cmd = [sys.executable, "-c", "\n".join([load, run, mock])] + + # should succeed + env = self.get_env() + # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files + env["TRANSFORMERS_OFFLINE"] = "1" + result = subprocess.run(cmd, env=env, check=False, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("success", result.stdout.decode()) + + @require_torch + def test_offline_mode_no_internet(self): + # python one-liner segments + # this must be loaded before socket.socket is monkey-patched + load = """ +from transformers import BertConfig, BertModel, BertTokenizer, pipeline + """ + + run = """ +mname = "hf-internal-testing/tiny-random-bert" +BertConfig.from_pretrained(mname) +BertModel.from_pretrained(mname) +BertTokenizer.from_pretrained(mname) +pipe = pipeline(task="fill-mask", model=mname) +print("success") + """ + + mock = """ +import socket +def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet") +socket.socket = offline_socket + """ + + # Force fetching the files so that we can use the cache + mname = "hf-internal-testing/tiny-random-bert" + BertConfig.from_pretrained(mname) + BertModel.from_pretrained(mname) + BertTokenizer.from_pretrained(mname) + pipeline(task="fill-mask", model=mname) + + # baseline - just load from_pretrained with normal network + cmd = [sys.executable, "-c", "\n".join([load, run, mock])] + + # should succeed + env = self.get_env() + result = subprocess.run(cmd, env=env, check=False, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("success", result.stdout.decode()) + + @require_torch + def test_offline_mode_sharded_checkpoint(self): + # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before + # `transformers` is loaded, and it's too late for inside pytest - so we are changing it + # while running an external program + + # python one-liner segments + + # this must be loaded before socket.socket is monkey-patched + load = """ +from transformers import BertConfig, BertModel, BertTokenizer + """ + + run = """ +mname = "hf-internal-testing/tiny-random-bert-sharded" +BertConfig.from_pretrained(mname) +BertModel.from_pretrained(mname) +print("success") + """ + + mock = """ +import socket +def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled") +socket.socket = offline_socket + """ + + # baseline - just load from_pretrained with normal network + cmd = [sys.executable, "-c", "\n".join([load, run])] + + # should succeed + env = self.get_env() + result = subprocess.run(cmd, env=env, check=False, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("success", result.stdout.decode()) + + # next emulate no network + cmd = [sys.executable, "-c", "\n".join([load, mock, run])] + + # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. + # env["TRANSFORMERS_OFFLINE"] = "0" + # result = subprocess.run(cmd, env=env, check=False, capture_output=True) + # self.assertEqual(result.returncode, 1, result.stderr) + + # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files + env["TRANSFORMERS_OFFLINE"] = "1" + result = subprocess.run(cmd, env=env, check=False, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("success", result.stdout.decode()) + + @require_torch + def test_offline_mode_pipeline_exception(self): + load = """ +from transformers import pipeline + """ + run = """ +mname = "hf-internal-testing/tiny-random-bert" +pipe = pipeline(model=mname) + """ + + mock = """ +import socket +def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled") +socket.socket = offline_socket + """ + env = self.get_env() + env["TRANSFORMERS_OFFLINE"] = "1" + cmd = [sys.executable, "-c", "\n".join([load, mock, run])] + result = subprocess.run(cmd, env=env, check=False, capture_output=True) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn( + "You cannot infer task automatically within `pipeline` when using offline mode", + result.stderr.decode().replace("\n", ""), + ) + + @require_torch + def test_offline_model_dynamic_model(self): + load = """ +from transformers import AutoModel + """ + run = """ +mname = "hf-internal-testing/test_dynamic_model" +AutoModel.from_pretrained(mname, trust_remote_code=True) +print("success") + """ + + # baseline - just load from_pretrained with normal network + cmd = [sys.executable, "-c", "\n".join([load, run])] + + # should succeed + env = self.get_env() + result = subprocess.run(cmd, env=env, check=False, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("success", result.stdout.decode()) + + # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files + env["TRANSFORMERS_OFFLINE"] = "1" + result = subprocess.run(cmd, env=env, check=False, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("success", result.stdout.decode()) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_skip_decorators.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_skip_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..6888fea23cffd47c0930139ba04c2a339000cc57 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_skip_decorators.py @@ -0,0 +1,120 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# 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. +# +# +# +# this test validates that we can stack skip decorators in groups and whether +# they work correctly with other decorators +# +# since the decorators have already built their decision params (like checking +# env[], we can't mock the env and test each of the combinations), so ideally +# the following 4 should be run. But since we have different CI jobs running +# different configs, all combinations should get covered +# +# RUN_SLOW=1 pytest -rA tests/test_skip_decorators.py +# RUN_SLOW=1 CUDA_VISIBLE_DEVICES="" pytest -rA tests/test_skip_decorators.py +# RUN_SLOW=0 pytest -rA tests/test_skip_decorators.py +# RUN_SLOW=0 CUDA_VISIBLE_DEVICES="" pytest -rA tests/test_skip_decorators.py + +import os +import unittest + +import pytest +from parameterized import parameterized + +from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device + + +# skipping in unittest tests + +params = [(1,)] + + +# test that we can stack our skip decorators with 3rd party decorators +def check_slow(): + run_slow = bool(os.getenv("RUN_SLOW", 0)) + if run_slow: + assert True + else: + assert False, "should have been skipped" + + +# test that we can stack our skip decorators +def check_slow_torch_cuda(): + run_slow = bool(os.getenv("RUN_SLOW", 0)) + if run_slow and torch_device == "cuda": + assert True + else: + assert False, "should have been skipped" + + +@require_torch +class SkipTester(unittest.TestCase): + @slow + @require_torch_gpu + def test_2_skips_slow_first(self): + check_slow_torch_cuda() + + @require_torch_gpu + @slow + def test_2_skips_slow_last(self): + check_slow_torch_cuda() + + # The combination of any skip decorator, followed by parameterized fails to skip the tests + # 1. @slow manages to correctly skip `test_param_slow_first` + # 2. but then `parameterized` creates new tests, with a unique name for each parameter groups. + # It has no idea that they are to be skipped and so they all run, ignoring @slow + # Therefore skip decorators must come after `parameterized` + # + # @slow + # @parameterized.expand(params) + # def test_param_slow_first(self, param=None): + # check_slow() + + # This works as expected: + # 1. `parameterized` creates new tests with unique names + # 2. each of them gets an opportunity to be skipped + @parameterized.expand(params) + @slow + def test_param_slow_last(self, param=None): + check_slow() + + +# skipping in non-unittest tests +# no problem at all here + + +@slow +@require_torch_gpu +def test_pytest_2_skips_slow_first(): + check_slow_torch_cuda() + + +@require_torch_gpu +@slow +def test_pytest_2_skips_slow_last(): + check_slow_torch_cuda() + + +@slow +@pytest.mark.parametrize("param", [1]) +def test_pytest_param_slow_first(param): + check_slow() + + +@pytest.mark.parametrize("param", [1]) +@slow +def test_pytest_param_slow_last(param): + check_slow() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_versions_utils.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_versions_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..14839400c2cdefee7033b1d1985cb0e61b722946 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/test_versions_utils.py @@ -0,0 +1,97 @@ +# 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 importlib.metadata +import sys + +from transformers.testing_utils import TestCasePlus +from transformers.utils.versions import require_version, require_version_core + + +numpy_ver = importlib.metadata.version("numpy") +python_ver = ".".join([str(x) for x in sys.version_info[:3]]) + + +class DependencyVersionCheckTest(TestCasePlus): + def test_core(self): + # lt + different version strings + require_version_core("numpy<1000.4.5") + require_version_core("numpy<1000.4") + require_version_core("numpy<1000") + + # le + require_version_core("numpy<=1000.4.5") + require_version_core(f"numpy<={numpy_ver}") + + # eq + require_version_core(f"numpy=={numpy_ver}") + + # ne + require_version_core("numpy!=1000.4.5") + + # ge + require_version_core("numpy>=1.0") + require_version_core("numpy>=1.0.0") + require_version_core(f"numpy>={numpy_ver}") + + # gt + require_version_core("numpy>1.0.0") + + # mix + require_version_core("numpy>1.0.0,<1000") + + # requirement w/o version + require_version_core("numpy") + + # unmet requirements due to version conflict + for req in ["numpy==1.0.0", "numpy>=1000.0.0", f"numpy<{numpy_ver}"]: + try: + require_version_core(req) + except ImportError as e: + self.assertIn(f"{req} is required", str(e)) + self.assertIn("but found", str(e)) + + # unmet requirements due to missing module + for req in ["numpipypie>1", "numpipypie2"]: + try: + require_version_core(req) + except importlib.metadata.PackageNotFoundError as e: + self.assertIn(f"The '{req}' distribution was not found and is required by this application", str(e)) + self.assertIn("Try: pip install transformers -U", str(e)) + + # bogus requirements formats: + # 1. whole thing + for req in ["numpy??1.0.0", "numpy1.0.0"]: + try: + require_version_core(req) + except ValueError as e: + self.assertIn("requirement needs to be in the pip package format", str(e)) + # 2. only operators + for req in ["numpy=1.0.0", "numpy == 1.00", "numpy<>1.0.0", "numpy><1.00", "numpy>>1.0.0"]: + try: + require_version_core(req) + except ValueError as e: + self.assertIn("need one of ", str(e)) + + def test_python(self): + # matching requirement + require_version("python>=3.6.0") + + # not matching requirements + for req in ["python>9.9.9", "python<3.0.0"]: + try: + require_version_core(req) + except ImportError as e: + self.assertIn(f"{req} is required", str(e)) + self.assertIn(f"but found python=={python_ver}", str(e)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/tiny_model_summary.json b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/tiny_model_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..5f2c6c0b4e74389463e32b83f51c120b633c6953 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/tests/utils/tiny_model_summary.json @@ -0,0 +1,7290 @@ +{ + "ASTForAudioClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ASTFeatureExtractor" + ], + "model_classes": [ + "ASTForAudioClassification" + ], + "sha": "83d6e076db7768a3645401bad3204624985e1d08" + }, + "ASTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ASTFeatureExtractor" + ], + "model_classes": [ + "ASTModel" + ], + "sha": "75e68f956f6f2c0709b01e596e7a6aecb1b29dce" + }, + "AlbertForMaskedLM": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForMaskedLM", + "TFAlbertForMaskedLM" + ], + "sha": "d29de71ac29e1019c3a7762f7357f750730cb037" + }, + "AlbertForMultipleChoice": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForMultipleChoice", + "TFAlbertForMultipleChoice" + ], + "sha": "242aecce6a589a2964c0f695621fa22a83751579" + }, + "AlbertForPreTraining": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForPreTraining", + "TFAlbertForPreTraining" + ], + "sha": "41330be4b271687f4d88ddc96346c12aa11de983" + }, + "AlbertForQuestionAnswering": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForQuestionAnswering", + "TFAlbertForQuestionAnswering" + ], + "sha": "040b81c15f437f4722349dc5b41fccd17ebd7fdc" + }, + "AlbertForSequenceClassification": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForSequenceClassification", + "TFAlbertForSequenceClassification" + ], + "sha": "39c1a0e2c1c2623106d3211d751e9b32f23a91a0" + }, + "AlbertForTokenClassification": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForTokenClassification", + "TFAlbertForTokenClassification" + ], + "sha": "359c3f4a311a4053a6f6d6a880db5f82c8e3ff1f" + }, + "AlbertModel": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertModel", + "TFAlbertModel" + ], + "sha": "34a63314686b64aaeb595ddb95006f1ff2ffda17" + }, + "AlignModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "EfficientNetImageProcessor" + ], + "model_classes": [ + "AlignModel" + ], + "sha": "68a4f9d3f493f44efa7c1dde6fcca23350e2c92b" + }, + "AltCLIPModel": { + "tokenizer_classes": [ + "XLMRobertaTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "AltCLIPModel" + ], + "sha": "3106af0fd503970717c05f27218e5cacf19ba872" + }, + "BarkModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BarkModel" + ], + "sha": "187e590fd87359cea47693e8cb11a604cd7b673c" + }, + "BartForCausalLM": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartForCausalLM" + ], + "sha": "c25526ac67d2dbe79fe5462af4b7908ca2fbc3ff" + }, + "BartForConditionalGeneration": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartForConditionalGeneration", + "TFBartForConditionalGeneration" + ], + "sha": "3a489a21e4b04705f4a6047924b7616a67be7e37" + }, + "BartForQuestionAnswering": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartForQuestionAnswering" + ], + "sha": "3ebf9aab39a57ceab55128d5fc6f61e4db0dadd4" + }, + "BartForSequenceClassification": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartForSequenceClassification", + "TFBartForSequenceClassification" + ], + "sha": "ea452fd9a928cfebd71723afa50feb20326917bc" + }, + "BartModel": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartModel", + "TFBartModel" + ], + "sha": "e5df6d1aa75f03833b2df328b9c35463f73a421b" + }, + "BeitForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "BeitForImageClassification" + ], + "sha": "e997587bb890f82faad4bd25eb23d85ba21ecaaa" + }, + "BeitForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "BeitForSemanticSegmentation" + ], + "sha": "d4afa9e21e3fe5b087578ed68974d9b3ffc1fb22" + }, + "BeitModel": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "BeitModel" + ], + "sha": "5c4a051f0cca6f64d02c6168deb88413cae10d2c" + }, + "BertForMaskedLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForMaskedLM", + "TFBertForMaskedLM" + ], + "sha": "3e32baa52ce044c75edfb5c28abd51ee8d051282" + }, + "BertForMultipleChoice": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForMultipleChoice", + "TFBertForMultipleChoice" + ], + "sha": "0b8c3a6d411d1e19e5fd98d4d8631ae7616eeeaa" + }, + "BertForNextSentencePrediction": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForNextSentencePrediction", + "TFBertForNextSentencePrediction" + ], + "sha": "628e70debf8864bd0b63aff7901d17d9c4f7612c" + }, + "BertForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForPreTraining", + "TFBertForPreTraining" + ], + "sha": "c748ad37e6a200a6f64b2764191bfe13f976032f" + }, + "BertForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForQuestionAnswering", + "TFBertForQuestionAnswering" + ], + "sha": "4671ad0c21493b97c5eb2f0201192704c29876d5" + }, + "BertForSequenceClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForSequenceClassification", + "TFBertForSequenceClassification" + ], + "sha": "37a9d44022264c12bdf3ec257778f953b63d4aaf" + }, + "BertForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForTokenClassification", + "TFBertForTokenClassification" + ], + "sha": "d7dc3a0793ff6dfcb794b21130ee0f185d2c61a2" + }, + "BertLMHeadModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertLMHeadModel", + "TFBertLMHeadModel" + ], + "sha": "b4e3acc1990f3e365ffddbd54b620a26d9fb4b09" + }, + "BertModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertModel", + "TFBertModel" + ], + "sha": "3956d303d3cddf0708ff20660c1ea5f6ec30e434" + }, + "BigBirdForCausalLM": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForCausalLM" + ], + "sha": "5c7a487af5248d9c01b45d5481b7d7bb9b36e1b5" + }, + "BigBirdForMaskedLM": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForMaskedLM" + ], + "sha": "476ef8225c0f69270b577706ad4f1dda13e4dde5" + }, + "BigBirdForMultipleChoice": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForMultipleChoice" + ], + "sha": "cf93eaa1019987112c171a407745bc183a20513a" + }, + "BigBirdForPreTraining": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForPreTraining" + ], + "sha": "5fb9efa13334431e7c186a9fa314b89c4a1eee72" + }, + "BigBirdForQuestionAnswering": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForQuestionAnswering" + ], + "sha": "f82f88bd71fba819a8ffb0692915d3529e705417" + }, + "BigBirdForSequenceClassification": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForSequenceClassification" + ], + "sha": "ea398090858f9af93b54fc9a8d65cfed78ac27ff" + }, + "BigBirdForTokenClassification": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForTokenClassification" + ], + "sha": "2cdea118999fa58ba9fb0162d99e2ffa146c3df1" + }, + "BigBirdModel": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdModel" + ], + "sha": "9c55989f31df156194e6997606fb14d9897e0300" + }, + "BigBirdPegasusForCausalLM": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusForCausalLM" + ], + "sha": "49bc8816c666dee32e27cd8e00136b604eb85243" + }, + "BigBirdPegasusForConditionalGeneration": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusForConditionalGeneration" + ], + "sha": "e791aa6d1af5a76ca0926d95b1f28bd2d8adf376" + }, + "BigBirdPegasusForQuestionAnswering": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusForQuestionAnswering" + ], + "sha": "7650e076713ca707a37062adc8c9c1cd60dad7c7" + }, + "BigBirdPegasusForSequenceClassification": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusForSequenceClassification" + ], + "sha": "02500e8ebd9c53528750013fb963fbdc2be34034" + }, + "BigBirdPegasusModel": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusModel" + ], + "sha": "b07c5304dfba673cf8b9cf5cd1aa45fbfea1c2f3" + }, + "BioGptForCausalLM": { + "tokenizer_classes": [ + "BioGptTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BioGptForCausalLM" + ], + "sha": "07073b31da84054fd12226e3cae4cb3beb2547f9" + }, + "BioGptForSequenceClassification": { + "tokenizer_classes": [ + "BioGptTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BioGptForSequenceClassification" + ], + "sha": "8e18ad6218abd795e050dec324a8c827ccedacb4" + }, + "BioGptForTokenClassification": { + "tokenizer_classes": [ + "BioGptTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BioGptForTokenClassification" + ], + "sha": "67f8173c1a17273064d452a9031a51b67f327b6a" + }, + "BioGptModel": { + "tokenizer_classes": [ + "BioGptTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BioGptModel" + ], + "sha": "fe18551d0743538a990520b75707294ec57b4ebe" + }, + "BitBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "BitBackbone" + ], + "sha": "2f06f6b4395b6dce2b00ac839ff757410e743cd7" + }, + "BitForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "BitForImageClassification" + ], + "sha": "d0d8476f2d285ddda7c42c0d4a8e4bf6f5d2bfdf" + }, + "BitModel": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "BitModel" + ], + "sha": "30a8a9b1a6b253cc500c01cf41bc1fc9581ea5e5" + }, + "BlenderbotForCausalLM": { + "tokenizer_classes": [ + "BlenderbotTokenizer", + "BlenderbotTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotForCausalLM" + ], + "sha": "8aad2e13e8920bca3cf988ba45f8a7b008b51a81" + }, + "BlenderbotForConditionalGeneration": { + "tokenizer_classes": [ + "BlenderbotTokenizer", + "BlenderbotTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotForConditionalGeneration", + "TFBlenderbotForConditionalGeneration" + ], + "sha": "e8532878b9924fa02fb4b059b7f6e7fa372fff91" + }, + "BlenderbotModel": { + "tokenizer_classes": [ + "BlenderbotTokenizer", + "BlenderbotTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotModel", + "TFBlenderbotModel" + ], + "sha": "ff848a40c30ca98eb7c6870bbb02677d5af9db55" + }, + "BlenderbotSmallForCausalLM": { + "tokenizer_classes": [ + "BlenderbotSmallTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotSmallForCausalLM" + ], + "sha": "4c57c106630932eb9de4d76210a540d04616304d" + }, + "BlenderbotSmallForConditionalGeneration": { + "tokenizer_classes": [ + "BlenderbotSmallTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotSmallForConditionalGeneration", + "TFBlenderbotSmallForConditionalGeneration" + ], + "sha": "b8db01fcf3e37a5b369cd50e169bf383b8e905d8" + }, + "BlenderbotSmallModel": { + "tokenizer_classes": [ + "BlenderbotSmallTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotSmallModel", + "TFBlenderbotSmallModel" + ], + "sha": "0a10c70e225ec63278faffa8fabf759f063f0e55" + }, + "Blip2ForConditionalGeneration": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [ + "BlipImageProcessor" + ], + "model_classes": [ + "Blip2ForConditionalGeneration" + ], + "sha": "35e1ef43da3554af62eb29a7b3dbbef3f3bef48e" + }, + "Blip2Model": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [ + "BlipImageProcessor" + ], + "model_classes": [ + "Blip2Model" + ], + "sha": "c23378f225be31872fff33c103cf0ebc2454ffcc" + }, + "BlipForConditionalGeneration": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "BlipImageProcessor" + ], + "model_classes": [ + "BlipForConditionalGeneration", + "TFBlipForConditionalGeneration" + ], + "sha": "eaf32bc0369349deef0c777442fc185119171d1f" + }, + "BlipModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "BlipImageProcessor" + ], + "model_classes": [ + "BlipModel", + "TFBlipModel" + ], + "sha": "3d1d1c15eff22d6b2664a2d15757fa6f5d93827d" + }, + "BloomForCausalLM": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomForCausalLM" + ], + "sha": "0f4f06f162cd67d34d03ee156484e4001d468500" + }, + "BloomForQuestionAnswering": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomForQuestionAnswering" + ], + "sha": "23f369f163eef8c9c9685900440b0cbb0f3439fd" + }, + "BloomForSequenceClassification": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomForSequenceClassification" + ], + "sha": "b2280eef7172835f39b265eb0c46623257f67bbe" + }, + "BloomForTokenClassification": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomForTokenClassification" + ], + "sha": "9796aa45f99adff987c978089e11c0bd9d7b997f" + }, + "BloomModel": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomModel" + ], + "sha": "28b600fcfdc4f4938406fb518abf895620048cb2" + }, + "BrosForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BrosForTokenClassification" + ], + "sha": "4ec2c91936f96b93667e8946fc7abbdeeb08a6d7" + }, + "BrosModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BrosModel" + ], + "sha": "e2464830b1874eeaf9f4b425fbe0ce8e7c7643e9" + }, + "CLIPModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "CLIPModel", + "TFCLIPModel" + ], + "sha": "0452d344074485d0e7eb5d5c12447b7c9dbc9619" + }, + "CLIPSegModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "CLIPSegModel" + ], + "sha": "7b1305214ccc85d29b776ffbee06748693852a04" + }, + "CTRLForSequenceClassification": { + "tokenizer_classes": [ + "CTRLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CTRLForSequenceClassification", + "TFCTRLForSequenceClassification" + ], + "sha": "280b5a3502d607c55c9f8d9f198fe9c2802d6f73" + }, + "CTRLLMHeadModel": { + "tokenizer_classes": [ + "CTRLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CTRLLMHeadModel", + "TFCTRLLMHeadModel" + ], + "sha": "662381663b216f1dd3c9cd30e2e83cb4c6fc9552" + }, + "CTRLModel": { + "tokenizer_classes": [ + "CTRLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CTRLModel", + "TFCTRLModel" + ], + "sha": "68b19b4f132d5a191a73acd78d983cbdcf068e9c" + }, + "CanineForMultipleChoice": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineForMultipleChoice" + ], + "sha": "fa0451453ed202f903ff7dcf6071aab6630fb89f" + }, + "CanineForQuestionAnswering": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineForQuestionAnswering" + ], + "sha": "5e1012bb086ac2e0b1497eeb7ed14eb2183d4ecb" + }, + "CanineForSequenceClassification": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineForSequenceClassification" + ], + "sha": "75336dc9179153869c38a8047ce4b1e02677a260" + }, + "CanineForTokenClassification": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineForTokenClassification" + ], + "sha": "65a622ea8e12597e12f45e59d46d8dbe8461fc10" + }, + "CanineModel": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineModel" + ], + "sha": "531ef67ad4f0b3dc7a9e5d722c774096b7401b1b" + }, + "ChineseCLIPModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "ChineseCLIPImageProcessor" + ], + "model_classes": [ + "ChineseCLIPModel" + ], + "sha": "504271a3c5fd9c2e877f5b4c01848bc18778c7c3" + }, + "ClapModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [ + "ClapFeatureExtractor" + ], + "model_classes": [ + "ClapModel" + ], + "sha": "a7874595b900f9b2ddc79130dafc3ff48f4fbfb9" + }, + "ClvpModelForConditionalGeneration": { + "tokenizer_classes": [ + "ClvpTokenizer" + ], + "processor_classes": [ + "ClvpFeatureExtractor" + ], + "model_classes": [], + "sha": "45df7581535be337ff781707b6c20994ca221f05" + }, + "CodeGenForCausalLM": { + "tokenizer_classes": [ + "CodeGenTokenizer", + "CodeGenTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "CodeGenForCausalLM" + ], + "sha": "a3fc69d757fd1f0aa01bcbc4337f586651c7cb10" + }, + "CodeGenModel": { + "tokenizer_classes": [ + "CodeGenTokenizer", + "CodeGenTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "CodeGenModel" + ], + "sha": "dad4941a2b7429fc6e8206fcc4a04fc40f4a0beb" + }, + "ConditionalDetrForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "ConditionalDetrImageProcessor" + ], + "model_classes": [ + "ConditionalDetrForObjectDetection" + ], + "sha": "762c213a0285edc84eb813a2ed90063cf971ca43" + }, + "ConditionalDetrModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConditionalDetrImageProcessor" + ], + "model_classes": [ + "ConditionalDetrModel" + ], + "sha": "18b75874158cac520c63605293b06e0b1327c263" + }, + "ConvBertForMaskedLM": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForMaskedLM", + "TFConvBertForMaskedLM" + ], + "sha": "307c70e32c3d3c18aeb45e0cbdc9fcd2957d9aba" + }, + "ConvBertForMultipleChoice": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForMultipleChoice", + "TFConvBertForMultipleChoice" + ], + "sha": "d6561a21ffdb82d03c1822af0510eb7482ce5026" + }, + "ConvBertForQuestionAnswering": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForQuestionAnswering", + "TFConvBertForQuestionAnswering" + ], + "sha": "8a056da5cc421415c2a24b9f644dd95ca279411d" + }, + "ConvBertForSequenceClassification": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForSequenceClassification", + "TFConvBertForSequenceClassification" + ], + "sha": "8bb8b20e51d282d777cc567cacadd97a35f0811e" + }, + "ConvBertForTokenClassification": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForTokenClassification", + "TFConvBertForTokenClassification" + ], + "sha": "8db0dd3c2b8ccc958fa9a84801f4f837b42fcf2c" + }, + "ConvBertModel": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertModel", + "TFConvBertModel" + ], + "sha": "c9c5b1a74f0e468d8467473cabeaa67fcdbaddb7" + }, + "ConvNextBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextBackbone" + ], + "sha": "499c7d6a97825b79e19663b70f3b60c4813b6bf2" + }, + "ConvNextForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextForImageClassification", + "TFConvNextForImageClassification" + ], + "sha": "0b490fd6b19cdbf721025dbd6ee45dcc5828e6e3" + }, + "ConvNextModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextModel", + "TFConvNextModel" + ], + "sha": "7b3b47a57b9a9120e022b91d6067daeac55b794f" + }, + "ConvNextV2Backbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextV2Backbone" + ], + "sha": "c82fc526949dfd892a1fee3c34be6f8d80c4d3df" + }, + "ConvNextV2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextV2ForImageClassification", + "TFConvNextV2ForImageClassification" + ], + "sha": "ee22bae1cbb87d66fc7f62f7e15a43d6ff80d3cc" + }, + "ConvNextV2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextV2Model", + "TFConvNextV2Model" + ], + "sha": "c4dd68ee1102cba05bcc483da2a88e39427b7249" + }, + "CvtForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "CvtForImageClassification", + "TFCvtForImageClassification" + ], + "sha": "4b1938e252fdb26a06c1f5755e07fa8f6eed2d75" + }, + "CvtModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "CvtModel", + "TFCvtModel" + ], + "sha": "27fed12c174f4f4f1fe27075d1c29602fe0669f0" + }, + "DPRQuestionEncoder": { + "tokenizer_classes": [ + "DPRQuestionEncoderTokenizer", + "DPRQuestionEncoderTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DPRQuestionEncoder", + "TFDPRQuestionEncoder" + ], + "sha": "09ae0269780271e0a4916f7bab1dbc4f8a76070d" + }, + "DPTForDepthEstimation": { + "tokenizer_classes": [], + "processor_classes": [ + "DPTImageProcessor" + ], + "model_classes": [ + "DPTForDepthEstimation" + ], + "sha": "11b7735d64d95b6599811631b012d2dec6eaa2c1" + }, + "DPTForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "DPTImageProcessor" + ], + "model_classes": [ + "DPTForSemanticSegmentation" + ], + "sha": "e140c3c716a4bf11dad875e5f5f0abd2bd4cbbcb" + }, + "DPTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DPTImageProcessor" + ], + "model_classes": [ + "DPTModel" + ], + "sha": "1d6ae6c0b60868dffbef0dddeda381c51c6dcba5" + }, + "Data2VecAudioForAudioFrameClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioForAudioFrameClassification" + ], + "sha": "a64828b27e73fc8dd95aeb315108ca2f6a66b55f" + }, + "Data2VecAudioForCTC": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioForCTC" + ], + "sha": "bb161b6a181bd2c22cf30222f46fa6ef42225744" + }, + "Data2VecAudioForSequenceClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioForSequenceClassification" + ], + "sha": "8de17e0a959eca5f72b2ea59a11bc1fa744785d9" + }, + "Data2VecAudioForXVector": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioForXVector" + ], + "sha": "dcb92484cf28fb4fe1dcf5d6e8d78e04382fdce9" + }, + "Data2VecAudioModel": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioModel" + ], + "sha": "73f503fdff73b7616154f64dbe38a685cc48e8eb" + }, + "Data2VecTextForCausalLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForCausalLM" + ], + "sha": "1f3658ce623653338cd31516551e8181aa08bb38" + }, + "Data2VecTextForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForMaskedLM" + ], + "sha": "fb41ac30d0faa0899bf5afaa0986df8993395ca6" + }, + "Data2VecTextForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForMultipleChoice" + ], + "sha": "e7556d520ad90ebae5ad88554d45a37488d00040" + }, + "Data2VecTextForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForQuestionAnswering" + ], + "sha": "9630833d76a1fd7e96b904d87bb11b7c00ccd021" + }, + "Data2VecTextForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForSequenceClassification" + ], + "sha": "156e4019c37d9592f193ba80553cd245cbccecb3" + }, + "Data2VecTextForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForTokenClassification" + ], + "sha": "55b3a49fdbf22479d6eb939261d4b884ea288270" + }, + "Data2VecTextModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextModel" + ], + "sha": "c21be3e4f88e8357bf33bfba8f8e05ae2e735124" + }, + "Data2VecVisionForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "Data2VecVisionForImageClassification", + "TFData2VecVisionForImageClassification" + ], + "sha": "d640e7ced7a3fbbb8c8661a4f67b934e55406172" + }, + "Data2VecVisionForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "Data2VecVisionForSemanticSegmentation", + "TFData2VecVisionForSemanticSegmentation" + ], + "sha": "3eba3cd694fab6530b7e5da8f49d3951301c816a" + }, + "Data2VecVisionModel": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "Data2VecVisionModel", + "TFData2VecVisionModel" + ], + "sha": "2a7ad25e4359970dc70494a2f3eb98e2a3c9806d" + }, + "DebertaForMaskedLM": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaForMaskedLM", + "TFDebertaForMaskedLM" + ], + "sha": "e0f9ada9e0f6d4d7cc39d7cbd58369b0c84de33d" + }, + "DebertaForQuestionAnswering": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaForQuestionAnswering", + "TFDebertaForQuestionAnswering" + ], + "sha": "a3eb69cdb0b52f7d0fb730e882f1a54b9a7442ea" + }, + "DebertaForSequenceClassification": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaForSequenceClassification", + "TFDebertaForSequenceClassification" + ], + "sha": "32af91d12c4e9b6d62b420bee93311fd77d3c933" + }, + "DebertaForTokenClassification": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaForTokenClassification", + "TFDebertaForTokenClassification" + ], + "sha": "ba62ba2726d813e60e512476fc1b178aa3858175" + }, + "DebertaModel": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaModel", + "TFDebertaModel" + ], + "sha": "4273294e14cd04c0e2cd1dcff5cf7e5d4fe906ba" + }, + "DebertaV2ForMaskedLM": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForMaskedLM", + "TFDebertaV2ForMaskedLM" + ], + "sha": "a053dedc2cdf32918a84277cb0c05186604496a5" + }, + "DebertaV2ForMultipleChoice": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForMultipleChoice", + "TFDebertaV2ForMultipleChoice" + ], + "sha": "07e39f520ce239b39ef8cb24cd7874d06c791063" + }, + "DebertaV2ForQuestionAnswering": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForQuestionAnswering", + "TFDebertaV2ForQuestionAnswering" + ], + "sha": "9cecb3a7fc6b95099122283644ea1f8ced287d1b" + }, + "DebertaV2ForSequenceClassification": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForSequenceClassification", + "TFDebertaV2ForSequenceClassification" + ], + "sha": "df9ea1f5c0f2ccd139b21cfb3963a5a5ebfb5b81" + }, + "DebertaV2ForTokenClassification": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForTokenClassification", + "TFDebertaV2ForTokenClassification" + ], + "sha": "51fe01989df38a540ac1abca5ee71a51365defd5" + }, + "DebertaV2Model": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2Model", + "TFDebertaV2Model" + ], + "sha": "211df4bd1a4a9b66c97af3f9231a5d2af8de7b9f" + }, + "DeformableDetrForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "DeformableDetrImageProcessor" + ], + "model_classes": [ + "DeformableDetrForObjectDetection" + ], + "sha": "8fa0db215c458f60ae4d455d6fb067c1c5e39fdc" + }, + "DeformableDetrModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DeformableDetrImageProcessor" + ], + "model_classes": [ + "DeformableDetrModel" + ], + "sha": "0faac5624696b03edd14694642f9804f2cd8f3da" + }, + "DeiTForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "DeiTImageProcessor" + ], + "model_classes": [ + "DeiTForImageClassification", + "TFDeiTForImageClassification" + ], + "sha": "21fc864199dafa0130f16a45769c6b6ca22c7784" + }, + "DeiTForImageClassificationWithTeacher": { + "tokenizer_classes": [], + "processor_classes": [ + "DeiTImageProcessor" + ], + "model_classes": [ + "DeiTForImageClassificationWithTeacher", + "TFDeiTForImageClassificationWithTeacher" + ], + "sha": "5a5738a109e27f3d4b78a0db4cb1d3331140c10e" + }, + "DeiTForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "DeiTImageProcessor" + ], + "model_classes": [ + "DeiTForMaskedImageModeling", + "TFDeiTForMaskedImageModeling" + ], + "sha": "d5df5c538fe1efb8d668a3893d1691d505a0de06" + }, + "DeiTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DeiTImageProcessor" + ], + "model_classes": [ + "DeiTModel", + "TFDeiTModel" + ], + "sha": "0fdbff6f44b7c6933c2027fec1d7f87bec06b590" + }, + "DetaForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "DetaImageProcessor" + ], + "model_classes": [ + "DetaForObjectDetection" + ], + "sha": "a15ad6ce64fbcb5021b2b99e9587c4011ef3341d" + }, + "DetaModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DetaImageProcessor" + ], + "model_classes": [ + "DetaModel" + ], + "sha": "8820f2297ec0dec8f1875054559c8b7a162098e3" + }, + "DetrForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "DetrForObjectDetection" + ], + "sha": "7dc967c53f4b3f07904c42b255346b744d0ad84e" + }, + "DetrForSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "DetrForSegmentation" + ], + "sha": "e34330acdae359588ef853e961a78d419dc4e8eb" + }, + "DetrModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "DetrModel" + ], + "sha": "f15ce38a10c7447e8048b1681e4811322a005722" + }, + "DinatBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "DinatBackbone" + ], + "sha": "3ba13790a0796d90104c207f75bb3d5d79723d51" + }, + "DinatForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "DinatForImageClassification" + ], + "sha": "624cf2d864a7ea2f90e24014a213e34597e8bd76" + }, + "DinatModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "DinatModel" + ], + "sha": "d6c75bc51196f0a683afb12de6310fdda13efefd" + }, + "Dinov2Backbone": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "Dinov2Backbone" + ], + "sha": "dbf8d2ff3092ac53c11e6525e6cbae7ace84769a" + }, + "Dinov2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "Dinov2ForImageClassification" + ], + "sha": "ae44840966456aae33641df2c8c8a4af5b457b24" + }, + "Dinov2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "Dinov2Model" + ], + "sha": "6f560b1cc9806bcf84fe0b0c60b5faf9c29be959" + }, + "DistilBertForMaskedLM": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForMaskedLM", + "TFDistilBertForMaskedLM" + ], + "sha": "b2dfda30b012821996e6e603729562d9c900bc0f" + }, + "DistilBertForMultipleChoice": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForMultipleChoice", + "TFDistilBertForMultipleChoice" + ], + "sha": "ec6b83129a7d1be2a6b8d58303abcca5541a5cb3" + }, + "DistilBertForQuestionAnswering": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForQuestionAnswering", + "TFDistilBertForQuestionAnswering" + ], + "sha": "812406b226415044469b0e0a84c4fe0ff338c5d3" + }, + "DistilBertForSequenceClassification": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForSequenceClassification", + "TFDistilBertForSequenceClassification" + ], + "sha": "6f427ce7b3e5aaa596938fbd98437d3875581b7b" + }, + "DistilBertForTokenClassification": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForTokenClassification", + "TFDistilBertForTokenClassification" + ], + "sha": "166dbe3f5d6ecd871762567069454d6ec65234b4" + }, + "DistilBertModel": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertModel", + "TFDistilBertModel" + ], + "sha": "cc4425ad0676f3ec00e8bffe485fe83cae61041a" + }, + "DonutSwinModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DonutImageProcessor" + ], + "model_classes": [ + "DonutSwinModel" + ], + "sha": "1b10654fbfe2f2ea410a672ab605bd5c60d3f284" + }, + "EfficientFormerForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientFormerImageProcessor" + ], + "model_classes": [ + "EfficientFormerForImageClassification", + "TFEfficientFormerForImageClassification" + ], + "sha": "ebadb628e12f268e321fcc756fa4606f7b5b3178" + }, + "EfficientFormerForImageClassificationWithTeacher": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientFormerImageProcessor" + ], + "model_classes": [ + "EfficientFormerForImageClassificationWithTeacher", + "TFEfficientFormerForImageClassificationWithTeacher" + ], + "sha": "1beabce6da9cb4ebbeafcd1ef23fac36b4a269e2" + }, + "EfficientFormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientFormerImageProcessor" + ], + "model_classes": [ + "EfficientFormerModel", + "TFEfficientFormerModel" + ], + "sha": "200fae5b875844d09c8a91d1c155b72b06a517f6" + }, + "EfficientNetForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientNetImageProcessor" + ], + "model_classes": [ + "EfficientNetForImageClassification" + ], + "sha": "6ed195ee636d2c0b885139da8c7b45d57ebaeee0" + }, + "EfficientNetModel": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientNetImageProcessor" + ], + "model_classes": [ + "EfficientNetModel" + ], + "sha": "eb03c90d4aaad98af0f19e0dfbdc41106297ffff" + }, + "ElectraForCausalLM": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForCausalLM" + ], + "sha": "c78396bc8cdd8db247892339de8da80d691d1d04" + }, + "ElectraForMaskedLM": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForMaskedLM", + "TFElectraForMaskedLM" + ], + "sha": "631337703dbd8d41904c39891a41c6f1edd31813" + }, + "ElectraForMultipleChoice": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForMultipleChoice", + "TFElectraForMultipleChoice" + ], + "sha": "66fdea6e22cfcbd3caa49ea82f31871c460612fa" + }, + "ElectraForPreTraining": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForPreTraining", + "TFElectraForPreTraining" + ], + "sha": "7b2d0fa8726b1180c7d6cde4f4afc3800eba7e6f" + }, + "ElectraForQuestionAnswering": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForQuestionAnswering", + "TFElectraForQuestionAnswering" + ], + "sha": "c6b127fd9f3019462e4ca2373762836207e39ce2" + }, + "ElectraForSequenceClassification": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForSequenceClassification", + "TFElectraForSequenceClassification" + ], + "sha": "41f0089ab7876abe0e28dbbd565144acb31f8127" + }, + "ElectraForTokenClassification": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForTokenClassification", + "TFElectraForTokenClassification" + ], + "sha": "1fdbbe70c1ddd16503820a1443d6a379a15ed777" + }, + "ElectraModel": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraModel", + "TFElectraModel" + ], + "sha": "312b532cbef26610d80f2bd008650160cae4f7a1" + }, + "EncodecModel": { + "tokenizer_classes": [], + "processor_classes": [ + "EncodecFeatureExtractor" + ], + "model_classes": [ + "EncodecModel" + ], + "sha": "e14c5a2fd6529c85cd4ac5a05ee9e550ced6a006" + }, + "EncoderDecoderModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "EncoderDecoderModel", + "TFEncoderDecoderModel" + ], + "sha": "1038be9fd1b87b2e0a8f33721ff8e4612d34b3b6" + }, + "ErnieForCausalLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForCausalLM" + ], + "sha": "b49e00112ff06c2f0a0e54499921dddcf8c3c6a8" + }, + "ErnieForMaskedLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForMaskedLM" + ], + "sha": "30429830d1997222d885dcfdbd36d5e02d0d34b1" + }, + "ErnieForMultipleChoice": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForMultipleChoice" + ], + "sha": "5a21144bf35dfb60560ff8249116ad4459c0069a" + }, + "ErnieForNextSentencePrediction": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForNextSentencePrediction" + ], + "sha": "ed5868efb39bf6afb29f0cf444deafcf1e50b5bc" + }, + "ErnieForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForPreTraining" + ], + "sha": "e4ad30d291c310fea25e6f91f91393f993513b42" + }, + "ErnieForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForQuestionAnswering" + ], + "sha": "fe7c74b763f63a9fd864dad325385075df7c80c8" + }, + "ErnieForSequenceClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForSequenceClassification" + ], + "sha": "84e0be05fcd52f54e96a69f67a2481323a58a9db" + }, + "ErnieForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForTokenClassification" + ], + "sha": "91cf62c43a5a83332552ffa2d8e5e44d63a224ea" + }, + "ErnieMForMultipleChoice": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMForMultipleChoice" + ], + "sha": "c42ee7fcb132a323ace314c32e63c8a7d36ce18f" + }, + "ErnieMForQuestionAnswering": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMForQuestionAnswering" + ], + "sha": "2b90dee75ca87b214f96db00002aa18244ec8e84" + }, + "ErnieMForSequenceClassification": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMForSequenceClassification" + ], + "sha": "d8368646d8b1c67b1460af9c6ec13fd9d894cae6" + }, + "ErnieMForTokenClassification": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMForTokenClassification" + ], + "sha": "a9e29ba60fa0b7bedc2ed26a6b9911427df1ca6b" + }, + "ErnieMModel": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMModel" + ], + "sha": "7306eac3f38c3cf6211f0e741fdb81c6cc92bc09" + }, + "ErnieModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieModel" + ], + "sha": "b51478a9f40e353c41be3a29ccef103dcfe22b4b" + }, + "EsmForMaskedLM": { + "tokenizer_classes": [ + "EsmTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "EsmForMaskedLM", + "TFEsmForMaskedLM" + ], + "sha": "b56297b6cd64b9ba7c613d0cd146f1ecbea8115e" + }, + "EsmForSequenceClassification": { + "tokenizer_classes": [ + "EsmTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "EsmForSequenceClassification", + "TFEsmForSequenceClassification" + ], + "sha": "cc6d7ef0a4763540d67b7a4fb31bede9a7d3f245" + }, + "EsmForTokenClassification": { + "tokenizer_classes": [ + "EsmTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "EsmForTokenClassification", + "TFEsmForTokenClassification" + ], + "sha": "498953f66e260b974c504abbc863ee266d6c84a9" + }, + "EsmModel": { + "tokenizer_classes": [ + "EsmTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "EsmModel", + "TFEsmModel" + ], + "sha": "183838263b70809310117a0761542501acf64c21" + }, + "FNetForMaskedLM": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForMaskedLM" + ], + "sha": "91eaae1eac894af5d96c0221ec9bcef7f1af41c8" + }, + "FNetForMultipleChoice": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForMultipleChoice" + ], + "sha": "c15d98d5f7a6f3ef3099b1257949bee208d5466e" + }, + "FNetForNextSentencePrediction": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForNextSentencePrediction" + ], + "sha": "c59440b44d07d61fc45a90ded7fc11d6f25b143d" + }, + "FNetForPreTraining": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForPreTraining" + ], + "sha": "c05f55ccfb2f2533babd3c6e99de7749bc8081da" + }, + "FNetForQuestionAnswering": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForQuestionAnswering" + ], + "sha": "47788e49dd435653fa2aa4b3ccae3572a870758e" + }, + "FNetForSequenceClassification": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForSequenceClassification" + ], + "sha": "a3049b896ea6c5a32c364989c3afe604ee58b9fc" + }, + "FNetForTokenClassification": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForTokenClassification" + ], + "sha": "3bcdafca57d544bb81e2f7eead1e512c168582fc" + }, + "FNetModel": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetModel" + ], + "sha": "48fa66de37df126504db3b658806135eb877f505" + }, + "FSMTForConditionalGeneration": { + "tokenizer_classes": [ + "FSMTTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FSMTForConditionalGeneration" + ], + "sha": "6a1a981b29c8a98c1fd31bd0ad809f5575ca6c7a" + }, + "FSMTModel": { + "tokenizer_classes": [ + "FSMTTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FSMTModel" + ], + "sha": "683f6f73a2ab87801f1695a72d1af63cf173ab7c" + }, + "FalconForCausalLM": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconForCausalLM" + ], + "sha": "60076d5dafc5e33ba9c90dcd05e7c0834e44049a" + }, + "FalconForQuestionAnswering": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconForQuestionAnswering" + ], + "sha": "b1ee9cd5fad2d177ea5a46df4611cd02f66ae788" + }, + "FalconForSequenceClassification": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconForSequenceClassification" + ], + "sha": "007838c0991c2b6a87dc49a8a5c20f29149a00fa" + }, + "FalconForTokenClassification": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconForTokenClassification" + ], + "sha": "0ea6ae548773daa6e3317fddc058957e956eebf4" + }, + "FalconModel": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconModel" + ], + "sha": "ca15a579c946eb00c5b39cc8e0ea63d0c1460f84" + }, + "FlaubertForMultipleChoice": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertForMultipleChoice", + "TFFlaubertForMultipleChoice" + ], + "sha": "8b12bd87a63f2e86c3482431742f6d8abf6ec4fd" + }, + "FlaubertForQuestionAnsweringSimple": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertForQuestionAnsweringSimple", + "TFFlaubertForQuestionAnsweringSimple" + ], + "sha": "5c0e7ad1efae7e3497f5cd6d2d9519403df49d37" + }, + "FlaubertForSequenceClassification": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertForSequenceClassification", + "TFFlaubertForSequenceClassification" + ], + "sha": "762f12a8c99690be8ed2663b7af3011660174a7c" + }, + "FlaubertForTokenClassification": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertForTokenClassification", + "TFFlaubertForTokenClassification" + ], + "sha": "d2ab741c937bb69ef27c89e4c86a8c9d444874ca" + }, + "FlaubertModel": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertModel", + "TFFlaubertModel" + ], + "sha": "bdc2f8e17bb869393053429ec8c1c842bfeabb07" + }, + "FlaubertWithLMHeadModel": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertWithLMHeadModel", + "TFFlaubertWithLMHeadModel" + ], + "sha": "f20eb0932c90061003c9cc4e109c6ea22559c4f2" + }, + "FlavaForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "FlavaImageProcessor" + ], + "model_classes": [ + "FlavaForPreTraining" + ], + "sha": "6e9b2094060a5fa27984c7b49e5d0e820a88b487" + }, + "FlavaModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "FlavaImageProcessor" + ], + "model_classes": [ + "FlavaModel" + ], + "sha": "31ebf1b7a0ef1fd5059b98e28e5ab1c366d2c482" + }, + "FocalNetBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "FocalNetBackbone" + ], + "sha": "eb8c580969443cb87de7dd9a256deaface03692f" + }, + "FocalNetForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "FocalNetForImageClassification" + ], + "sha": "28d30ded26a3213e8fb7011a455afc3aa98b0a95" + }, + "FocalNetForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "FocalNetForMaskedImageModeling" + ], + "sha": "0ea7626d19c9dd2f3113d977f643a1babc720bd3" + }, + "FocalNetModel": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "FocalNetModel" + ], + "sha": "107b004e6aa14108a359b7d22bdb9aa141ec05d5" + }, + "FunnelBaseModel": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelBaseModel", + "TFFunnelBaseModel" + ], + "sha": "87fed4252812df23315a56531625333e315681c6" + }, + "FunnelForMaskedLM": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForMaskedLM", + "TFFunnelForMaskedLM" + ], + "sha": "5543daf29f185cd45f2599bd6f38c96064c9c8de" + }, + "FunnelForMultipleChoice": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForMultipleChoice", + "TFFunnelForMultipleChoice" + ], + "sha": "a8bf597e37dbefb1ac5c97c4cb162c3d522a33a1" + }, + "FunnelForPreTraining": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForPreTraining", + "TFFunnelForPreTraining" + ], + "sha": "cbcb300d60aacd5950a45409b6e3f0f240c9082e" + }, + "FunnelForQuestionAnswering": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForQuestionAnswering", + "TFFunnelForQuestionAnswering" + ], + "sha": "6a5675305e096434e818486a13892cb55daffd13" + }, + "FunnelForSequenceClassification": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForSequenceClassification", + "TFFunnelForSequenceClassification" + ], + "sha": "1bc557a1e4314da21a44dee57b799e95a7025e5c" + }, + "FunnelForTokenClassification": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForTokenClassification", + "TFFunnelForTokenClassification" + ], + "sha": "693bc1217a224efd558f410ddc8ffc63739bebc3" + }, + "FunnelModel": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelModel", + "TFFunnelModel" + ], + "sha": "bfbaa8fa21c3abf80b94e7168b5ecff8ec5b5f76" + }, + "FuyuForCausalLM": { + "tokenizer_classes": [ + "LlamaTokenizerFast" + ], + "processor_classes": [ + "FuyuImageProcessor" + ], + "model_classes": [ + "FuyuForCausalLM" + ], + "sha": "685d78258ea95c5c82e0e4555d0d4a2270ab8bff" + }, + "GLPNForDepthEstimation": { + "tokenizer_classes": [], + "processor_classes": [ + "GLPNImageProcessor" + ], + "model_classes": [ + "GLPNForDepthEstimation" + ], + "sha": "32ca1c1ef5d33242e5e7c0433bcd773c082f0260" + }, + "GLPNModel": { + "tokenizer_classes": [], + "processor_classes": [ + "GLPNImageProcessor" + ], + "model_classes": [ + "GLPNModel" + ], + "sha": "24a8dbb48b1aa0ba2eba44324fcd0c78cca64dd4" + }, + "GPT2ForQuestionAnswering": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2ForQuestionAnswering" + ], + "sha": "a5bdd6bd4d79feece85ea9a8bd4ee5fe54c1d45b" + }, + "GPT2ForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2ForSequenceClassification", + "TFGPT2ForSequenceClassification" + ], + "sha": "90a2d78e5c7f288152f8456c3d58a43b40a58449" + }, + "GPT2ForTokenClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2ForTokenClassification" + ], + "sha": "da78bc95b45fab2da9d43f2ca27164996e31ade1" + }, + "GPT2LMHeadModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2LMHeadModel", + "TFGPT2LMHeadModel" + ], + "sha": "78f56535d4ce19e9d7c0992e390085c5a4196b37" + }, + "GPT2Model": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2Model", + "TFGPT2Model" + ], + "sha": "d6694b0d8fe17978761c9305dc151780506b192e" + }, + "GPTBigCodeForCausalLM": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTBigCodeForCausalLM" + ], + "sha": "99f7aaadf9c29669c63ef6c16f6bc5c07dbb9126" + }, + "GPTBigCodeForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTBigCodeForSequenceClassification" + ], + "sha": "64a7398d5763161037b818314c60dd83d93d03e9" + }, + "GPTBigCodeForTokenClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTBigCodeForTokenClassification" + ], + "sha": "310537ecd22d45f71bf594b17922cf2abc338eaf" + }, + "GPTBigCodeModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTBigCodeModel" + ], + "sha": "3069419084a9dc36802d47de9df3d314ccfc2f28" + }, + "GPTJForCausalLM": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTJForCausalLM", + "TFGPTJForCausalLM" + ], + "sha": "1fff390baa45cb187903ebdd269c975bb9ed7386" + }, + "GPTJForQuestionAnswering": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTJForQuestionAnswering", + "TFGPTJForQuestionAnswering" + ], + "sha": "3d4ec61dbed01f844d4c309971eeb5ad722c6c84" + }, + "GPTJForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTJForSequenceClassification", + "TFGPTJForSequenceClassification" + ], + "sha": "4b5db259cd16ca84ae2cd79aa4851cdd14479128" + }, + "GPTJModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTJModel", + "TFGPTJModel" + ], + "sha": "d8e1db30d08fbf57da6fc139aea3ffd63ab6226e" + }, + "GPTNeoForCausalLM": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoForCausalLM" + ], + "sha": "e88934e402c15195dd99b2947632415dd7645268" + }, + "GPTNeoForQuestionAnswering": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoForQuestionAnswering" + ], + "sha": "623883e94bd08caf9b3f839b98debeea72d5bc2b" + }, + "GPTNeoForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoForSequenceClassification" + ], + "sha": "bf2090d5d91a70eb37ba51fbdcf23afc7031fea8" + }, + "GPTNeoForTokenClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoForTokenClassification" + ], + "sha": "d5208e73e24a1671219776b50fe5f96e0e4cd218" + }, + "GPTNeoModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoModel" + ], + "sha": "72a7cd49da613c3125a90884df4763545c594e56" + }, + "GPTNeoXForCausalLM": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXForCausalLM" + ], + "sha": "0229cfaaa843c6b492ac2abffabb00f1ff1936f8" + }, + "GPTNeoXForQuestionAnswering": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXForQuestionAnswering" + ], + "sha": "7d2f08c959c211129952ee03b5562add09fe6864" + }, + "GPTNeoXForSequenceClassification": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXForSequenceClassification" + ], + "sha": "17c4b845ee2e0bb780ca2dea2d59a3d9d5d3c651" + }, + "GPTNeoXForTokenClassification": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXForTokenClassification" + ], + "sha": "3aa4fe8a562f32230041d6d3616aa5ecc3f30192" + }, + "GPTNeoXJapaneseForCausalLM": { + "tokenizer_classes": [ + "GPTNeoXJapaneseTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXJapaneseForCausalLM" + ], + "sha": "5fca2479f1064fd22e17f944c8fcc14f7e73f1d5" + }, + "GPTNeoXJapaneseModel": { + "tokenizer_classes": [ + "GPTNeoXJapaneseTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXJapaneseModel" + ], + "sha": "5c6ed124150df845cfc701d70b97fdcde687be52" + }, + "GPTNeoXModel": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXModel" + ], + "sha": "33114ba2f72189d5a2bd63f0cdb78551189242ff" + }, + "GPTSanJapaneseForConditionalGeneration": { + "tokenizer_classes": [ + "GPTSanJapaneseTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "GPTSanJapaneseForConditionalGeneration" + ], + "sha": "ff6a41faaa713c7fbd5d9a1a50539745f9e1178e" + }, + "GitForCausalLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "GitForCausalLM" + ], + "sha": "60f9c50466ae0beeb11776ca5bfeb6473f441554" + }, + "GitModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "GitModel" + ], + "sha": "3d2eb6bddf95bb4a4e59b045d4e464c730c07f41" + }, + "GroupViTModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "GroupViTModel", + "TFGroupViTModel" + ], + "sha": "05a3a02dd46cb9eb078608dec98f633c0cf559ef" + }, + "HubertForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "HubertForCTC" + ], + "sha": "13431b76106f993eedcff48a75bae590a09b14f7" + }, + "HubertForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "HubertForSequenceClassification" + ], + "sha": "d23f46607a900b1a55dfee4b7ed205a6823035b1" + }, + "HubertModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "HubertModel", + "TFHubertModel" + ], + "sha": "3224562c86c4669db65ae7defdc5fb555b113e95" + }, + "IBertForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForMaskedLM" + ], + "sha": "e333a9c9d375f4d839b7e9e21d1a1c8dad58d7d1" + }, + "IBertForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForMultipleChoice" + ], + "sha": "a81f7d64cd7ce5fe6cd726b23d9d14ac5d17bf53" + }, + "IBertForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForQuestionAnswering" + ], + "sha": "7b66d13d4d6801a82cbeb7f9fd853ca1630d1f8b" + }, + "IBertForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForSequenceClassification" + ], + "sha": "309d57145c40f889222fe5df62f14dddf4496b38" + }, + "IBertForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForTokenClassification" + ], + "sha": "b032e9bff4b081b78c098b2d8bc610ac035c6ddf" + }, + "IBertModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertModel" + ], + "sha": "6749164c678d4883d455f98b1dfc98c62da8f08b" + }, + "IdeficsForVisionText2Text": { + "tokenizer_classes": [ + "LlamaTokenizerFast" + ], + "processor_classes": [ + "IdeficsImageProcessor" + ], + "model_classes": [ + "IdeficsForVisionText2Text" + ], + "sha": "2c2f2e2cd6b02a77d0cdd8c3767ba9a6267dbd20" + }, + "IdeficsModel": { + "tokenizer_classes": [ + "LlamaTokenizerFast" + ], + "processor_classes": [ + "IdeficsImageProcessor" + ], + "model_classes": [ + "IdeficsModel" + ], + "sha": "649df2e35e067efd573ff2d083784a5cf876545e" + }, + "ImageGPTForCausalImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "ImageGPTImageProcessor" + ], + "model_classes": [ + "ImageGPTForCausalImageModeling" + ], + "sha": "9a7d1fc04439ab1d9d690de9c3e7673f08568cdf" + }, + "ImageGPTForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ImageGPTImageProcessor" + ], + "model_classes": [ + "ImageGPTForImageClassification" + ], + "sha": "d92c7aed4ba5de74a1f542b736010090e4a58b42" + }, + "ImageGPTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ImageGPTImageProcessor" + ], + "model_classes": [ + "ImageGPTModel" + ], + "sha": "5a7983e48d5841704733dd0756177680ed50c074" + }, + "Kosmos2ForConditionalGeneration": { + "tokenizer_classes": [ + "XLMRobertaTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "Kosmos2ForConditionalGeneration" + ], + "sha": "d1d4607782b911411676f1ee79997dee645def58" + }, + "Kosmos2Model": { + "tokenizer_classes": [ + "XLMRobertaTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "Kosmos2Model" + ], + "sha": "379d8944a65312094d9ab1c4b8a82058a2d3274e" + }, + "LEDForConditionalGeneration": { + "tokenizer_classes": [ + "LEDTokenizer", + "LEDTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LEDForConditionalGeneration", + "TFLEDForConditionalGeneration" + ], + "sha": "a354b49a79351f3ea8ae7776d9f8352ae26cfc14" + }, + "LEDForQuestionAnswering": { + "tokenizer_classes": [ + "LEDTokenizer", + "LEDTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LEDForQuestionAnswering" + ], + "sha": "47c7a75a1e650dae60ff6e9bbab0f2386946670c" + }, + "LEDForSequenceClassification": { + "tokenizer_classes": [ + "LEDTokenizer", + "LEDTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LEDForSequenceClassification" + ], + "sha": "3571e2c9d9f2f2ec0b8fe47090330b128be05126" + }, + "LEDModel": { + "tokenizer_classes": [ + "LEDTokenizer", + "LEDTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LEDModel", + "TFLEDModel" + ], + "sha": "3c3f6eb142545afc570187bfdabfe65d43dafbe4" + }, + "LayoutLMForMaskedLM": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMForMaskedLM", + "TFLayoutLMForMaskedLM" + ], + "sha": "0368bd9bd8fd3eb43b8a3b38962b5345b8765514" + }, + "LayoutLMForQuestionAnswering": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMForQuestionAnswering", + "TFLayoutLMForQuestionAnswering" + ], + "sha": "0d6a4bc614fccfa313c1fb6d132a250929518f85" + }, + "LayoutLMForSequenceClassification": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMForSequenceClassification", + "TFLayoutLMForSequenceClassification" + ], + "sha": "1bd68c73dbf6c8c0526d24fbe2831be82998c440" + }, + "LayoutLMForTokenClassification": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMForTokenClassification", + "TFLayoutLMForTokenClassification" + ], + "sha": "155e7da3f1d786aa39d957b16080c52de4a7efd7" + }, + "LayoutLMModel": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMModel", + "TFLayoutLMModel" + ], + "sha": "14f77b30d267910f11f0fd532a91a6b85ab3a4de" + }, + "LayoutLMv2ForQuestionAnswering": { + "tokenizer_classes": [ + "LayoutLMv2Tokenizer", + "LayoutLMv2TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv2ImageProcessor" + ], + "model_classes": [ + "LayoutLMv2ForQuestionAnswering" + ], + "sha": "f452e28dd34d3c38cce046b1cc7b0ada69f587b1" + }, + "LayoutLMv2ForSequenceClassification": { + "tokenizer_classes": [ + "LayoutLMv2Tokenizer", + "LayoutLMv2TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv2ImageProcessor" + ], + "model_classes": [ + "LayoutLMv2ForSequenceClassification" + ], + "sha": "b483e08fd143113629ecda3dbfd57e69bfeb5f11" + }, + "LayoutLMv2ForTokenClassification": { + "tokenizer_classes": [ + "LayoutLMv2Tokenizer", + "LayoutLMv2TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv2ImageProcessor" + ], + "model_classes": [ + "LayoutLMv2ForTokenClassification" + ], + "sha": "0721ae69bff00ecfff1b3d1521a475cde0253299" + }, + "LayoutLMv2Model": { + "tokenizer_classes": [ + "LayoutLMv2Tokenizer", + "LayoutLMv2TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv2ImageProcessor" + ], + "model_classes": [ + "LayoutLMv2Model" + ], + "sha": "6a1b510769b344979a910a7d0bade613a9ec2dfc" + }, + "LayoutLMv3ForQuestionAnswering": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv3ImageProcessor" + ], + "model_classes": [ + "LayoutLMv3ForQuestionAnswering", + "TFLayoutLMv3ForQuestionAnswering" + ], + "sha": "4640242388e69cf77ea2dd3ac36ec6f1b26628c8" + }, + "LayoutLMv3ForSequenceClassification": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv3ImageProcessor" + ], + "model_classes": [ + "LayoutLMv3ForSequenceClassification", + "TFLayoutLMv3ForSequenceClassification" + ], + "sha": "96515f699874cfbfbec7a64c539ae92419e4c6dc" + }, + "LayoutLMv3ForTokenClassification": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv3ImageProcessor" + ], + "model_classes": [ + "LayoutLMv3ForTokenClassification", + "TFLayoutLMv3ForTokenClassification" + ], + "sha": "ed4ffc464f2028fe50dfc6823f4eda78d34be7e6" + }, + "LayoutLMv3Model": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv3ImageProcessor" + ], + "model_classes": [ + "LayoutLMv3Model", + "TFLayoutLMv3Model" + ], + "sha": "69725e5e2445e5c1c3aa8a2aa49cfd72e0a44565" + }, + "LevitForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "LevitImageProcessor" + ], + "model_classes": [ + "LevitForImageClassification" + ], + "sha": "5ae8ccaa1fe1c947cb8ae6499e4a150c668bb9f0" + }, + "LevitForImageClassificationWithTeacher": { + "tokenizer_classes": [], + "processor_classes": [ + "LevitImageProcessor" + ], + "model_classes": [ + "LevitForImageClassificationWithTeacher" + ], + "sha": "568cc0d965b9bd293f240e7724314db6d50f6722" + }, + "LevitModel": { + "tokenizer_classes": [], + "processor_classes": [ + "LevitImageProcessor" + ], + "model_classes": [ + "LevitModel" + ], + "sha": "172efa52b50c75c3b3e498fa638f55e65b2ebf87" + }, + "LiltForQuestionAnswering": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LiltForQuestionAnswering" + ], + "sha": "0a348441999e98ec003b29fc4d5a67ad22ee6ca2" + }, + "LiltForSequenceClassification": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LiltForSequenceClassification" + ], + "sha": "c53ab0ba33536fe564a4a1e4f1674d990c01b83a" + }, + "LiltForTokenClassification": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LiltForTokenClassification" + ], + "sha": "14f85076f9b3f7016917e324d51ebd22511a2ae5" + }, + "LiltModel": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LiltModel" + ], + "sha": "3f1166cc14c532388df7e82336a8e575a813bd3f" + }, + "LongT5ForConditionalGeneration": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongT5ForConditionalGeneration" + ], + "sha": "c685cbbe706ad5c9a28689631765726a1874dcc7" + }, + "LongT5Model": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongT5Model" + ], + "sha": "6b468e55e2490565e6155690201086ac00c72062" + }, + "LongformerForMaskedLM": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForMaskedLM", + "TFLongformerForMaskedLM" + ], + "sha": "929d3bda9a1485d9bae41f9dbfc1d149c1c4e78e" + }, + "LongformerForMultipleChoice": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForMultipleChoice", + "TFLongformerForMultipleChoice" + ], + "sha": "60b1ecac6b9385ce18c7e6978ab161cce8e7f9d4" + }, + "LongformerForQuestionAnswering": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForQuestionAnswering", + "TFLongformerForQuestionAnswering" + ], + "sha": "be45ab1321b703f2200cbbcae560aaf2e2afef88" + }, + "LongformerForSequenceClassification": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForSequenceClassification", + "TFLongformerForSequenceClassification" + ], + "sha": "8bc0de0b0f740bf397eb2770ec3ce3a24f3d7af9" + }, + "LongformerForTokenClassification": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForTokenClassification", + "TFLongformerForTokenClassification" + ], + "sha": "efa33a9b6f47f0f7979af08ae8d04a5a7363a14b" + }, + "LongformerModel": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerModel", + "TFLongformerModel" + ], + "sha": "b023d531688e8655fc09300ac36742588efb3240" + }, + "LukeForMaskedLM": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForMaskedLM" + ], + "sha": "954cf6cd2bf1f298a3956b10c36656c57387506d" + }, + "LukeForMultipleChoice": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForMultipleChoice" + ], + "sha": "d1310a9174ad50d60b30ad6049e165deb2539034" + }, + "LukeForQuestionAnswering": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForQuestionAnswering" + ], + "sha": "3ea38da4e32cb4e45bea82b2e81a8639aeba2c35" + }, + "LukeForSequenceClassification": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForSequenceClassification" + ], + "sha": "b5b11248aeb4f5976379d15a977aeb2677e0c0f9" + }, + "LukeForTokenClassification": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForTokenClassification" + ], + "sha": "8aab1a33ad26a344a6f4dfd68630e9661e174471" + }, + "LukeModel": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeModel" + ], + "sha": "ae23a674e7297d41f33c9af86e039757dfd2d531" + }, + "LxmertForPreTraining": { + "tokenizer_classes": [ + "LxmertTokenizer", + "LxmertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LxmertForPreTraining", + "TFLxmertForPreTraining" + ], + "sha": "7b0843403c187aef00f20d5087086468d9613d2c" + }, + "LxmertForQuestionAnswering": { + "tokenizer_classes": [ + "LxmertTokenizer", + "LxmertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LxmertForQuestionAnswering" + ], + "sha": "27a74bd2cd156e46656c43ceb432c4deda0df5c1" + }, + "LxmertModel": { + "tokenizer_classes": [ + "LxmertTokenizer", + "LxmertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LxmertModel", + "TFLxmertModel" + ], + "sha": "97612a0d6b14406ea9bfd7672e6974e0961cbef1" + }, + "M2M100ForConditionalGeneration": { + "tokenizer_classes": [ + "M2M100Tokenizer" + ], + "processor_classes": [], + "model_classes": [ + "M2M100ForConditionalGeneration" + ], + "sha": "32ac347092d51f658b41ffc111b67d49acdeab46" + }, + "M2M100Model": { + "tokenizer_classes": [ + "M2M100Tokenizer" + ], + "processor_classes": [], + "model_classes": [ + "M2M100Model" + ], + "sha": "e95c2ae168c7ba19f8114def40e1b1edd953b2f5" + }, + "MBartForCausalLM": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartForCausalLM" + ], + "sha": "a45044f8056328d20a764356eca3d0746a7a195e" + }, + "MBartForConditionalGeneration": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartForConditionalGeneration", + "TFMBartForConditionalGeneration" + ], + "sha": "171e918962d6c0ee56c6b070858e19e16c8dd09f" + }, + "MBartForQuestionAnswering": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartForQuestionAnswering" + ], + "sha": "1ee08565d24777335595e0d2940e454abdcff731" + }, + "MBartForSequenceClassification": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartForSequenceClassification" + ], + "sha": "53e9c88ecfa2475d27afe099ffa7a8bcdb7ef7e4" + }, + "MBartModel": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartModel", + "TFMBartModel" + ], + "sha": "2d492b34d69dd63b411990d5c8bb692fd637e91c" + }, + "MCTCTForCTC": { + "tokenizer_classes": [], + "processor_classes": [ + "MCTCTFeatureExtractor" + ], + "model_classes": [ + "MCTCTForCTC" + ], + "sha": "895a3d74f87b344b1f0a71eae4f085941d51b5cf" + }, + "MCTCTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "MCTCTFeatureExtractor" + ], + "model_classes": [ + "MCTCTModel" + ], + "sha": "ce73d5c2b6fe163de778697d7b0543bf00d7ffa8" + }, + "MPNetForMaskedLM": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForMaskedLM", + "TFMPNetForMaskedLM" + ], + "sha": "50af96e7d0202aef86e396c136e4c4fde8afe183" + }, + "MPNetForMultipleChoice": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForMultipleChoice", + "TFMPNetForMultipleChoice" + ], + "sha": "af4ff8bf296a3a51f5ab6cd9f56741e4c732487c" + }, + "MPNetForQuestionAnswering": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForQuestionAnswering", + "TFMPNetForQuestionAnswering" + ], + "sha": "3e1a25c0d3243f78f81580c312ada3b39c06b428" + }, + "MPNetForSequenceClassification": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForSequenceClassification", + "TFMPNetForSequenceClassification" + ], + "sha": "43da45c0a0d73c5a5567b4c7ec512ec5023e52dd" + }, + "MPNetForTokenClassification": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForTokenClassification", + "TFMPNetForTokenClassification" + ], + "sha": "4e825eff24df533321ebab823eb66ce67e4ab3d9" + }, + "MPNetModel": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetModel", + "TFMPNetModel" + ], + "sha": "847c68344c2922e9a71fa8835b87a0f6f72b9f47" + }, + "MarianForCausalLM": { + "tokenizer_classes": [ + "MarianTokenizer" + ], + "processor_classes": [], + "model_classes": [], + "sha": "5fb205e6db8e18e3c6cdd4e4709be292ba4599f3" + }, + "MarianMTModel": { + "tokenizer_classes": [ + "MarianTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "MarianMTModel", + "TFMarianMTModel" + ], + "sha": "0405f542b31561592231a86e3009d05256cbf49f" + }, + "MarianModel": { + "tokenizer_classes": [ + "MarianTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "MarianModel", + "TFMarianModel" + ], + "sha": "3649748c0286c6d5179a7013a716f7314db182a8" + }, + "MarkupLMForQuestionAnswering": { + "tokenizer_classes": [ + "MarkupLMTokenizer", + "MarkupLMTokenizerFast" + ], + "processor_classes": [ + "MarkupLMFeatureExtractor" + ], + "model_classes": [ + "MarkupLMForQuestionAnswering" + ], + "sha": "c8bb9f93591d980362547b0bdca9f23ace2f383e" + }, + "MarkupLMForSequenceClassification": { + "tokenizer_classes": [ + "MarkupLMTokenizer", + "MarkupLMTokenizerFast" + ], + "processor_classes": [ + "MarkupLMFeatureExtractor" + ], + "model_classes": [ + "MarkupLMForSequenceClassification" + ], + "sha": "c2cb7245d68d76e0a5f993fc8a3de099ecebc68b" + }, + "MarkupLMForTokenClassification": { + "tokenizer_classes": [ + "MarkupLMTokenizer", + "MarkupLMTokenizerFast" + ], + "processor_classes": [ + "MarkupLMFeatureExtractor" + ], + "model_classes": [ + "MarkupLMForTokenClassification" + ], + "sha": "b9f924e82f400de0b34b46ee4ba276d686bd4890" + }, + "MarkupLMModel": { + "tokenizer_classes": [ + "MarkupLMTokenizer", + "MarkupLMTokenizerFast" + ], + "processor_classes": [ + "MarkupLMFeatureExtractor" + ], + "model_classes": [ + "MarkupLMModel" + ], + "sha": "9687ba29f1c59d978e3d4b0fa702031f88eff53b" + }, + "Mask2FormerForUniversalSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "Mask2FormerImageProcessor" + ], + "model_classes": [ + "Mask2FormerForUniversalSegmentation" + ], + "sha": "6429a7349527c9ef140ae691b83c47702cce1bc0" + }, + "Mask2FormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "Mask2FormerImageProcessor" + ], + "model_classes": [ + "Mask2FormerModel" + ], + "sha": "9bee8709204024b3669d503cdfe8890182f2a075" + }, + "MaskFormerForInstanceSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "MaskFormerImageProcessor" + ], + "model_classes": [ + "MaskFormerForInstanceSegmentation" + ], + "sha": "f844aaa81f55cb199c115f1bf95c217a70685570" + }, + "MaskFormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "MaskFormerImageProcessor" + ], + "model_classes": [ + "MaskFormerModel" + ], + "sha": "473b54a464bc0ccee29bc23b4f6610f32eec05af" + }, + "MegaForCausalLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForCausalLM" + ], + "sha": "6642b9da860f8b62abcfb0660feabcebf6698418" + }, + "MegaForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForMaskedLM" + ], + "sha": "6b2d47ba03bec9e6f7eefdd4a67351fa191aae6f" + }, + "MegaForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForMultipleChoice" + ], + "sha": "2b1e751da36a4410473eef07a62b09227a26d504" + }, + "MegaForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForQuestionAnswering" + ], + "sha": "612acd9a53c351c42514adb3c04f2057d2870be7" + }, + "MegaForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForSequenceClassification" + ], + "sha": "4871572da1613b7e9cfd3640c6d1129af004eefb" + }, + "MegaForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForTokenClassification" + ], + "sha": "450d3722c3b995215d06b9c12544c99f958581c7" + }, + "MegaModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaModel" + ], + "sha": "ca0862db27428893fe22f9bb5d2eb0875c2156f3" + }, + "MegatronBertForCausalLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForCausalLM" + ], + "sha": "ff08d05ef8f98fdccf1f01560ec6ec4adbc8a3e3" + }, + "MegatronBertForMaskedLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForMaskedLM" + ], + "sha": "2ed25e2681d26b51b404ef1347a385c5f2c86a9a" + }, + "MegatronBertForMultipleChoice": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForMultipleChoice" + ], + "sha": "1485af4b75f8f234d2b4b5aea50ab2ec55223a15" + }, + "MegatronBertForNextSentencePrediction": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForNextSentencePrediction" + ], + "sha": "52bc9ee1d5145344f66b088ed278f07ed3d90584" + }, + "MegatronBertForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForPreTraining" + ], + "sha": "e580d0efd54e1c92789e39b32929234e36ee427f" + }, + "MegatronBertForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForQuestionAnswering" + ], + "sha": "7342ba042a3c30c15382d00fcb0521533fc43841" + }, + "MegatronBertForSequenceClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForSequenceClassification" + ], + "sha": "6a7cd480511d817a1e221c8f7558c55a93baed1b" + }, + "MegatronBertForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForTokenClassification" + ], + "sha": "8b5334b6ec5f025293ca861de474b57ca84bc005" + }, + "MegatronBertModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertModel" + ], + "sha": "f2457fbe535ba97ea13db049f53618b42e13f047" + }, + "MgpstrForSceneTextRecognition": { + "tokenizer_classes": [], + "processor_classes": [ + "MgpstrProcessor" + ], + "model_classes": [ + "MgpstrForSceneTextRecognition" + ], + "sha": "f197d5bfa1fe27b5f28a6e6d4e3ad229b753450a" + }, + "MistralForCausalLM": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MistralForCausalLM" + ], + "sha": "f7e06aeedbba8f4f665b438b868ed932d451f64b" + }, + "MistralForSequenceClassification": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MistralForSequenceClassification" + ], + "sha": "65045444ea1933309270d8b08b21d3fa94a84290" + }, + "MistralModel": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MistralModel" + ], + "sha": "becd727ad72b1e8a7c0fa0ea39b61904fa68aeac" + }, + "MobileBertForMaskedLM": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForMaskedLM", + "TFMobileBertForMaskedLM" + ], + "sha": "d689e737d73ad23aed3aabd3177591fc827d1c62" + }, + "MobileBertForMultipleChoice": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForMultipleChoice", + "TFMobileBertForMultipleChoice" + ], + "sha": "403d1f88be7eb0c769ff3a8e57eab21cc3e75afb" + }, + "MobileBertForNextSentencePrediction": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForNextSentencePrediction", + "TFMobileBertForNextSentencePrediction" + ], + "sha": "b4d8836a0f259ee3bca9f230093836c9117c5e4d" + }, + "MobileBertForPreTraining": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForPreTraining", + "TFMobileBertForPreTraining" + ], + "sha": "fbaa13ea6f9fcebb9fde620dd009d12510440d17" + }, + "MobileBertForQuestionAnswering": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForQuestionAnswering", + "TFMobileBertForQuestionAnswering" + ], + "sha": "ba6a55cf2daec55bfb220c9bab0bc4ad96510087" + }, + "MobileBertForSequenceClassification": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForSequenceClassification", + "TFMobileBertForSequenceClassification" + ], + "sha": "17ab35603bec351457e035eef2d0426538071f72" + }, + "MobileBertForTokenClassification": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForTokenClassification", + "TFMobileBertForTokenClassification" + ], + "sha": "dee83e820e6c4f069886a5d1875bf6775897313e" + }, + "MobileBertModel": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertModel", + "TFMobileBertModel" + ], + "sha": "09b2db33ea798a762eeaf7e727e95f9ea8a6d14f" + }, + "MobileNetV1ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV1ImageProcessor" + ], + "model_classes": [ + "MobileNetV1ForImageClassification" + ], + "sha": "55023dbd0935f147bf1bccf960cea01ca07e0f0c" + }, + "MobileNetV1Model": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV1ImageProcessor" + ], + "model_classes": [ + "MobileNetV1Model" + ], + "sha": "178bd24528147a028938d6ee5c7e65c969ea37b0" + }, + "MobileNetV2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV2ImageProcessor" + ], + "model_classes": [ + "MobileNetV2ForImageClassification" + ], + "sha": "ff907f740cf9ea91bc3cdf403a94ae28fbb2548a" + }, + "MobileNetV2ForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV2ImageProcessor" + ], + "model_classes": [ + "MobileNetV2ForSemanticSegmentation" + ], + "sha": "48adbc340e42882f52b54d4f5dd045e16e9ef2d6" + }, + "MobileNetV2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV2ImageProcessor" + ], + "model_classes": [ + "MobileNetV2Model" + ], + "sha": "e876885828825472a80ef1796d89d60b901813ba" + }, + "MobileViTForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTForImageClassification", + "TFMobileViTForImageClassification" + ], + "sha": "7d0b31864f856e00f9e34e8c6781dcc7a8cdaf1e" + }, + "MobileViTForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTForSemanticSegmentation", + "TFMobileViTForSemanticSegmentation" + ], + "sha": "215f727caa3c3fc94fa4df486aa706e5d99d4194" + }, + "MobileViTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTModel", + "TFMobileViTModel" + ], + "sha": "b3a1452e7cb44b600b21ee14f3d5382366855a46" + }, + "MobileViTV2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTV2ForImageClassification" + ], + "sha": "25752b0967ad594341d1b685401450d7f698433c" + }, + "MobileViTV2ForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTV2ForSemanticSegmentation" + ], + "sha": "13b953f50be33219d55a12f1098be38b88000897" + }, + "MobileViTV2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTV2Model" + ], + "sha": "2f46357659db2d6d54d870e28073deeea1c8cb64" + }, + "MptForCausalLM": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptForCausalLM" + ], + "sha": "500c869b956c65f6b1a7b4867727f124c6f5728a" + }, + "MptForQuestionAnswering": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptForQuestionAnswering" + ], + "sha": "6ee46572bf61eb5e7dbbdaf00b73c4d37efc42d9" + }, + "MptForSequenceClassification": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptForSequenceClassification" + ], + "sha": "f0b9153413b5dfceeb96b67d4b0f22c94bbaf64a" + }, + "MptForTokenClassification": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptForTokenClassification" + ], + "sha": "3f7c3ccd67cd0b2aae56d37613429a64ef813246" + }, + "MptModel": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptModel" + ], + "sha": "ea747f234556661b0c8b84a626f267066ce586bf" + }, + "MraForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForMaskedLM" + ], + "sha": "c00ee46cfd2b8fed29cc37f0a4ead40ad51a439c" + }, + "MraForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForMultipleChoice" + ], + "sha": "f397469ba8109f64dab2d75335ea7bf0c2dbeb74" + }, + "MraForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForQuestionAnswering" + ], + "sha": "c2ed75acd20e5440a76d6504d9a3ebc2513011f0" + }, + "MraForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForSequenceClassification" + ], + "sha": "f47672d3708508bda7774215bee44a92ec16ab2f" + }, + "MraForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForTokenClassification" + ], + "sha": "f0961ab5818bca473607fb94b391c186dc1d3492" + }, + "MraModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraModel" + ], + "sha": "315f34f30bcc4b0b66b11987726df2a80c50e271" + }, + "MusicgenForCausalLM": { + "tokenizer_classes": [ + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [], + "sha": "f67d387eaaa7c71ddf88af95eda4bf14ace08d49" + }, + "MusicgenForConditionalGeneration": { + "tokenizer_classes": [ + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MusicgenForConditionalGeneration" + ], + "sha": "16102cdf580e70cf0b4e0e2cda5bc75b934da92c" + }, + "MvpForCausalLM": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpForCausalLM" + ], + "sha": "105e5f2c8a0f20d404cb71795539cda5dd49716d" + }, + "MvpForConditionalGeneration": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpForConditionalGeneration" + ], + "sha": "b0b706f14b2f8aae288cba30ae0064e0be7e888b" + }, + "MvpForQuestionAnswering": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpForQuestionAnswering" + ], + "sha": "82f152b36a40a4c22edcb146e6eaec636d84fa2d" + }, + "MvpForSequenceClassification": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpForSequenceClassification" + ], + "sha": "506b68544d064001929ee9e6db3752e62972a6aa" + }, + "MvpModel": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpModel" + ], + "sha": "3f4653184721a2bc029b27706d335ef7ddd219d5" + }, + "NatBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "NatBackbone" + ], + "sha": "d5cc5eccba4da609c82e9f5c649301b9f9fee9fb" + }, + "NatForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "NatForImageClassification" + ], + "sha": "2ff4c9e73c49c392c02a467e87b5511fd924242a" + }, + "NatModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "NatModel" + ], + "sha": "75e9756bb94d0ccdce98a8e963eeecbc66f9d573" + }, + "NezhaForMaskedLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForMaskedLM" + ], + "sha": "5991cca4b78f0ed7299259a71f3eeed3f3452b72" + }, + "NezhaForMultipleChoice": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForMultipleChoice" + ], + "sha": "0f6e9ec791d85ad4503acdec50b3a120f984016b" + }, + "NezhaForNextSentencePrediction": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForNextSentencePrediction" + ], + "sha": "9a34316c14ec8ecc98ff08e46760915c80098a57" + }, + "NezhaForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForPreTraining" + ], + "sha": "6259db427a0073061de352ea819d38a74798edd7" + }, + "NezhaForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForQuestionAnswering" + ], + "sha": "31c6a34e85ae8c41294e0f4ef25044e00e511c4d" + }, + "NezhaForSequenceClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForSequenceClassification" + ], + "sha": "db057c308ba2e05f223404de11e1816ce4bd62a9" + }, + "NezhaForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForTokenClassification" + ], + "sha": "235f4e10b4a59709650c2bece3e342ec153d9cfc" + }, + "NezhaModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaModel" + ], + "sha": "80e05ba7c55bcdd7f4d1387ef9a09a7a8e95b5ac" + }, + "NllbMoeForConditionalGeneration": { + "tokenizer_classes": [ + "NllbTokenizer", + "NllbTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NllbMoeForConditionalGeneration" + ], + "sha": "2a7f87dffe826af3d52086888f3f3773246e5528" + }, + "NllbMoeModel": { + "tokenizer_classes": [ + "NllbTokenizer", + "NllbTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NllbMoeModel" + ], + "sha": "9f7a2261eed4658e1aa5623be4672ba64bee7da5" + }, + "NystromformerForMaskedLM": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForMaskedLM" + ], + "sha": "37036847783f1e65e81ecd43803270a1ecb276f3" + }, + "NystromformerForMultipleChoice": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForMultipleChoice" + ], + "sha": "42a077d5ab6830e20560466eaccc525eff10c3ae" + }, + "NystromformerForQuestionAnswering": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForQuestionAnswering" + ], + "sha": "1cfaf79051731824db4f09989f093f87f4fceec5" + }, + "NystromformerForSequenceClassification": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForSequenceClassification" + ], + "sha": "d75231203066df41e9b6b25dbee9ad40e8515c18" + }, + "NystromformerForTokenClassification": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForTokenClassification" + ], + "sha": "5a499dc96e106bf41fc9166f2ad06527ec7ca14e" + }, + "NystromformerModel": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerModel" + ], + "sha": "2b6adb37ec473b15d71e2eb459acea08df6940ce" + }, + "OPTForCausalLM": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OPTForCausalLM", + "TFOPTForCausalLM" + ], + "sha": "190d1f4fc0011d2eaeaa05282e0fbd2445e4b11f" + }, + "OPTForQuestionAnswering": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OPTForQuestionAnswering" + ], + "sha": "0fa9277ce10dbc3d0922b354befb684a136af00b" + }, + "OPTForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OPTForSequenceClassification" + ], + "sha": "784ab288ab7280b1853ee400ef10ee2a965df352" + }, + "OPTModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OPTModel", + "TFOPTModel" + ], + "sha": "901d92b8f51edb0ec9614cb185fb66a8b5d364c3" + }, + "OneFormerForUniversalSegmentation": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "OneFormerImageProcessor" + ], + "model_classes": [ + "OneFormerForUniversalSegmentation" + ], + "sha": "fee1cfd676acc40f09017702ddac6504f3090d14" + }, + "OneFormerModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "OneFormerImageProcessor" + ], + "model_classes": [ + "OneFormerModel" + ], + "sha": "4163a79328c78f93ec57942598698a138c19a577" + }, + "OpenAIGPTForSequenceClassification": { + "tokenizer_classes": [ + "OpenAIGPTTokenizer", + "OpenAIGPTTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OpenAIGPTForSequenceClassification", + "TFOpenAIGPTForSequenceClassification" + ], + "sha": "c513f7f952935085f7573bf70a1ac3ad8f33434c" + }, + "OpenAIGPTLMHeadModel": { + "tokenizer_classes": [ + "OpenAIGPTTokenizer", + "OpenAIGPTTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OpenAIGPTLMHeadModel", + "TFOpenAIGPTLMHeadModel" + ], + "sha": "33f59ecd860f7a998483ec7631fe32d257235461" + }, + "OpenAIGPTModel": { + "tokenizer_classes": [ + "OpenAIGPTTokenizer", + "OpenAIGPTTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OpenAIGPTModel", + "TFOpenAIGPTModel" + ], + "sha": "00f6ec0a3a5276af71d08a26199e0ccbf2556fc9" + }, + "OwlViTForObjectDetection": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "OwlViTImageProcessor" + ], + "model_classes": [ + "OwlViTForObjectDetection" + ], + "sha": "af958c9164f23d0f12921a8edf687f9aaa6af90e" + }, + "OwlViTModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "OwlViTImageProcessor" + ], + "model_classes": [ + "OwlViTModel" + ], + "sha": "f0e27b2b4e53ba70e05d13dcfea8e85272b292a5" + }, + "Owlv2ForObjectDetection": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "Owlv2ImageProcessor" + ], + "model_classes": [ + "Owlv2ForObjectDetection" + ], + "sha": "30439c0b2749726468dc13a755261e8101170052" + }, + "Owlv2Model": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "Owlv2ImageProcessor" + ], + "model_classes": [ + "Owlv2Model" + ], + "sha": "7aeebdad5f72b36cb07c74355afad8e6052e2377" + }, + "PLBartForCausalLM": { + "tokenizer_classes": [ + "PLBartTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "PLBartForCausalLM" + ], + "sha": "6ee51133246dbdb18fc3681ebd62d21e421b9bb4" + }, + "PLBartForConditionalGeneration": { + "tokenizer_classes": [ + "PLBartTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "PLBartForConditionalGeneration" + ], + "sha": "ba191d28f4678d20b4dfed5fca5944018282cf20" + }, + "PLBartForSequenceClassification": { + "tokenizer_classes": [ + "PLBartTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "PLBartForSequenceClassification" + ], + "sha": "02063b3d9707fcff619a4e37a0d6e58f76e39b18" + }, + "PLBartModel": { + "tokenizer_classes": [ + "PLBartTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "PLBartModel" + ], + "sha": "cfbba29169b3f40d800403fc1b53982e1f88c5f8" + }, + "PegasusForCausalLM": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusForCausalLM" + ], + "sha": "6e685a698302a3ba33e5379d3a37eb0bc1ae2f70" + }, + "PegasusForConditionalGeneration": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusForConditionalGeneration", + "TFPegasusForConditionalGeneration" + ], + "sha": "15e58ee2ebc14b6e80ef2891259057ee5f049be2" + }, + "PegasusModel": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusModel", + "TFPegasusModel" + ], + "sha": "fa36b24523db411ef77903453346b8be81ef73fe" + }, + "PegasusXForConditionalGeneration": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusXForConditionalGeneration" + ], + "sha": "7588a8120f26a36c1687c14bdf1e9f9656891c1a" + }, + "PegasusXModel": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusXModel" + ], + "sha": "a0bdff627416ac3c39c22d081f5d88d8b8fd99cc" + }, + "PerceiverForImageClassificationConvProcessing": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForImageClassificationConvProcessing" + ], + "sha": "2c1e5e62ebc9d0c931adc8c665fb05bde6c1c1f1" + }, + "PerceiverForImageClassificationFourier": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForImageClassificationFourier" + ], + "sha": "88da41b8851b76b8be0dacdb3de023db02bb031a" + }, + "PerceiverForImageClassificationLearned": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForImageClassificationLearned" + ], + "sha": "879bd1fa38d3baddb027bb2cacba2d160a741375" + }, + "PerceiverForMaskedLM": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForMaskedLM" + ], + "sha": "1d2459cbd281ef72da5682e65102aaca96183045" + }, + "PerceiverForSequenceClassification": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForSequenceClassification" + ], + "sha": "576f1f96348f0343458499fbf53d4102b5c0f2ff" + }, + "PerceiverModel": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverModel" + ], + "sha": "83ec4d2d61ed62525ee033e13d144817beb29d19" + }, + "PersimmonForCausalLM": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PersimmonForCausalLM" + ], + "sha": "454234d6496c3857f5bf3eafb784616e2cd3ea82" + }, + "PersimmonForSequenceClassification": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PersimmonForSequenceClassification" + ], + "sha": "1d2674846543a181ca67bafa8b8f3a48bd2eefd1" + }, + "PersimmonModel": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PersimmonModel" + ], + "sha": "b8c8d479e29e9ee048e2d0b05b001ac835ad8859" + }, + "PhiForCausalLM": { + "tokenizer_classes": [ + "CodeGenTokenizer", + "CodeGenTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PhiForCausalLM" + ], + "sha": "3fecc0109a4a3a230e3a5509eaf47a26eba85d79" + }, + "PhiForSequenceClassification": { + "tokenizer_classes": [ + "CodeGenTokenizer", + "CodeGenTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PhiForSequenceClassification" + ], + "sha": "e1c9f8ebf1317516acc1cd6338de71a53e770245" + }, + "PhiForTokenClassification": { + "tokenizer_classes": [ + "CodeGenTokenizer", + "CodeGenTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PhiForTokenClassification" + ], + "sha": "d3a8054903753b5c96c05eaf9877905a116a1d5e" + }, + "PhiModel": { + "tokenizer_classes": [ + "CodeGenTokenizer", + "CodeGenTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PhiModel" + ], + "sha": "99c38d5ce7ace35127d00ed3eeb3561308ea6b21" + }, + "Pix2StructForConditionalGeneration": { + "tokenizer_classes": [ + "T5TokenizerFast" + ], + "processor_classes": [ + "Pix2StructImageProcessor", + "Pix2StructProcessor" + ], + "model_classes": [ + "Pix2StructForConditionalGeneration" + ], + "sha": "42b3de00ad535076c4893e4ac5ae2d2748cc4ccb" + }, + "PoolFormerForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "PoolFormerImageProcessor" + ], + "model_classes": [ + "PoolFormerForImageClassification" + ], + "sha": "ef04de5a6896100d457fb9553dd9789c09cca98e" + }, + "PoolFormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "PoolFormerImageProcessor" + ], + "model_classes": [ + "PoolFormerModel" + ], + "sha": "e8037215ebdbf795329ef6525cdc6aa547f04ace" + }, + "ProphetNetForCausalLM": { + "tokenizer_classes": [ + "ProphetNetTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ProphetNetForCausalLM" + ], + "sha": "d40b1e75bbc5ea0839563457aff6eee5bc0bb03e" + }, + "ProphetNetForConditionalGeneration": { + "tokenizer_classes": [ + "ProphetNetTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ProphetNetForConditionalGeneration" + ], + "sha": "d842875c41278032af39c03c66902786bb5ff2c7" + }, + "ProphetNetModel": { + "tokenizer_classes": [ + "ProphetNetTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ProphetNetModel" + ], + "sha": "f1ddbbcc768c7ba54c4d75b319540c1635e65937" + }, + "PvtForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "PvtImageProcessor" + ], + "model_classes": [ + "PvtForImageClassification" + ], + "sha": "589b37bd6941aff6dd248259f9eee3c422a41fde" + }, + "PvtModel": { + "tokenizer_classes": [], + "processor_classes": [ + "PvtImageProcessor" + ], + "model_classes": [ + "PvtModel" + ], + "sha": "c40765c382515ae627652d60e9077b6478448d48" + }, + "ReformerForMaskedLM": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ReformerForMaskedLM" + ], + "sha": "1e6431e42c676b525e3215e9e3cc8f1404f9f82b" + }, + "ReformerForQuestionAnswering": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ReformerForQuestionAnswering" + ], + "sha": "62b43977f244474bd6982c6327d0c57310258fcd" + }, + "ReformerForSequenceClassification": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ReformerForSequenceClassification" + ], + "sha": "67bd534a990a7dcfa02406987e7f066caa2a30e8" + }, + "ReformerModel": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ReformerModel" + ], + "sha": "a34ddb1389067448e9bc1323de674951cfb4cff1" + }, + "ReformerModelWithLMHead": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [], + "sha": "e7a8addaea8407d4c55e144e48aee04be6cca618" + }, + "RegNetForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "RegNetForImageClassification", + "TFRegNetForImageClassification" + ], + "sha": "5ec67c84fc7944c0c5b386bd26820bc4d1f3b32a" + }, + "RegNetModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "RegNetModel", + "TFRegNetModel" + ], + "sha": "72375e1401dc8271d4abb6295c9cee376f7b8f1a" + }, + "RemBertForCausalLM": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForCausalLM", + "TFRemBertForCausalLM" + ], + "sha": "8d9ae3d74a0e0a8958b4ee8c9dca3632abf52ef9" + }, + "RemBertForMaskedLM": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForMaskedLM", + "TFRemBertForMaskedLM" + ], + "sha": "b7c27d01e1cc3bef9ddd6a78627d700b3bffd759" + }, + "RemBertForMultipleChoice": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForMultipleChoice", + "TFRemBertForMultipleChoice" + ], + "sha": "2fe192677b9740cf24dd559339d46925e8ac23d4" + }, + "RemBertForQuestionAnswering": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForQuestionAnswering", + "TFRemBertForQuestionAnswering" + ], + "sha": "22b8ba44681b96292a1cf7f6df4ba6bb7937ec6e" + }, + "RemBertForSequenceClassification": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForSequenceClassification", + "TFRemBertForSequenceClassification" + ], + "sha": "20f3e89341ea15266d2685a8798142fba03c3f98" + }, + "RemBertForTokenClassification": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForTokenClassification", + "TFRemBertForTokenClassification" + ], + "sha": "15712ff753708da3cf0550e76e73a5d0bba7784e" + }, + "RemBertModel": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertModel", + "TFRemBertModel" + ], + "sha": "59cc6d099b1ded0aaead8684457415b129f79e86" + }, + "ResNetBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ResNetBackbone" + ], + "sha": "c84a6bcf8af4b6a3403dea3cf4c55965ac39f239" + }, + "ResNetForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ResNetForImageClassification", + "TFResNetForImageClassification" + ], + "sha": "34a180ad24d80811d420d7aa4fbec4a17751aaf8" + }, + "ResNetModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ResNetModel", + "TFResNetModel" + ], + "sha": "fafa6cdf9986c6cfbae360596b3574162430bcd3" + }, + "RoCBertForCausalLM": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForCausalLM" + ], + "sha": "194d8dafc4f4142f8d31e6b4be14b55d812f923b" + }, + "RoCBertForMaskedLM": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForMaskedLM" + ], + "sha": "8bc285f32f3b932dbd56ddf91b1170734d638eeb" + }, + "RoCBertForMultipleChoice": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForMultipleChoice" + ], + "sha": "bb54e5ae021d728022d34b12fee3f087d9486af9" + }, + "RoCBertForPreTraining": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForPreTraining" + ], + "sha": "86ebbd5b0bc84660ad7f505082eff19b86c137c8" + }, + "RoCBertForQuestionAnswering": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForQuestionAnswering" + ], + "sha": "1bfc2dc3d6e76170e6dca1ff32a54a0887ff28a3" + }, + "RoCBertForSequenceClassification": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForSequenceClassification" + ], + "sha": "c329038802241f454273894128fea38b60f7c739" + }, + "RoCBertForTokenClassification": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForTokenClassification" + ], + "sha": "afe5ec22c2ad1d9ff6e3e64c87eb7555faaa936d" + }, + "RoCBertModel": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertModel" + ], + "sha": "29de5580d5f5d3461a88673e7b4c492a9d8a67a4" + }, + "RoFormerForCausalLM": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForCausalLM", + "TFRoFormerForCausalLM" + ], + "sha": "6e074219c6dd8f8b221bbfda64fba100f729f88d" + }, + "RoFormerForMaskedLM": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForMaskedLM", + "TFRoFormerForMaskedLM" + ], + "sha": "a3a4d05f9b29601553a77244f2adcf8194f9367c" + }, + "RoFormerForMultipleChoice": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForMultipleChoice", + "TFRoFormerForMultipleChoice" + ], + "sha": "aca3999a1d14f09644faed44e2cdfb28ed68a3d3" + }, + "RoFormerForQuestionAnswering": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForQuestionAnswering", + "TFRoFormerForQuestionAnswering" + ], + "sha": "b8a20b3a788f178b9ef64e2eb9587f693dca1b69" + }, + "RoFormerForSequenceClassification": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForSequenceClassification", + "TFRoFormerForSequenceClassification" + ], + "sha": "d092e2d5e62012bf4ec921e763b37865d6189216" + }, + "RoFormerForTokenClassification": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForTokenClassification", + "TFRoFormerForTokenClassification" + ], + "sha": "85d3a17062e1f3e0539abfe738a88203e25349b6" + }, + "RoFormerModel": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerModel", + "TFRoFormerModel" + ], + "sha": "22e7df2f4cd66caf449f2342f63d176005afccc9" + }, + "RobertaForCausalLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForCausalLM", + "TFRobertaForCausalLM" + ], + "sha": "5d1d24d56f9735402e50a2ea513ffde44487733e" + }, + "RobertaForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForMaskedLM", + "TFRobertaForMaskedLM" + ], + "sha": "b21c9daf0b3b66530bf5d45d67df5ec392b5059c" + }, + "RobertaForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForMultipleChoice", + "TFRobertaForMultipleChoice" + ], + "sha": "10020d9546d4d7318f4d514fe13daaad07e6269f" + }, + "RobertaForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForQuestionAnswering", + "TFRobertaForQuestionAnswering" + ], + "sha": "eea4a81306891746bac9e7715f805a2d9dbf4be7" + }, + "RobertaForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForSequenceClassification", + "TFRobertaForSequenceClassification" + ], + "sha": "6a6f53fc6ab98e29ed539e76b1cb76d25a2cd720" + }, + "RobertaForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForTokenClassification", + "TFRobertaForTokenClassification" + ], + "sha": "9190044c4091eb0d98ae7638c453e24846bca5d7" + }, + "RobertaModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaModel", + "TFRobertaModel" + ], + "sha": "181a0b8a7ad24500ec327ad07ddb225f0680ac0a" + }, + "RobertaPreLayerNormForCausalLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForCausalLM", + "TFRobertaPreLayerNormForCausalLM" + ], + "sha": "73b6d4531b41f295a5d310d7aa44736004a59865" + }, + "RobertaPreLayerNormForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForMaskedLM", + "TFRobertaPreLayerNormForMaskedLM" + ], + "sha": "a61723c77e5ab7adc95285e7823a0a49b99af395" + }, + "RobertaPreLayerNormForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForMultipleChoice", + "TFRobertaPreLayerNormForMultipleChoice" + ], + "sha": "3dcfa62e0771358c60232a18135bfe7c7f6d715e" + }, + "RobertaPreLayerNormForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForQuestionAnswering", + "TFRobertaPreLayerNormForQuestionAnswering" + ], + "sha": "a8e76a5a50f7df60055e5ed6a1c3af2e7d34cf01" + }, + "RobertaPreLayerNormForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForSequenceClassification", + "TFRobertaPreLayerNormForSequenceClassification" + ], + "sha": "7509cb0286d146ef2fc6beb8867ae31b92fb1b16" + }, + "RobertaPreLayerNormForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForTokenClassification", + "TFRobertaPreLayerNormForTokenClassification" + ], + "sha": "3ad5814ba126b41e18c1978c970e396fab6da9bf" + }, + "RobertaPreLayerNormModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormModel", + "TFRobertaPreLayerNormModel" + ], + "sha": "4830db38fd310404c5ab70bd00684eca0bc06ca8" + }, + "RwkvForCausalLM": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RwkvForCausalLM" + ], + "sha": "2f452fd46b39e39b1a6a95fa1d8232405bbb3e96" + }, + "RwkvModel": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RwkvModel" + ], + "sha": "88a52c9437dc3c06f65a8252490be7eb91197804" + }, + "SEWDForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWDForCTC" + ], + "sha": "5c7495c77ae9e0f12c0de05d3a5fb95bdcd91768" + }, + "SEWDForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWDForSequenceClassification" + ], + "sha": "d6cbf1164ce1999fdaf3deeb7a6eba19a3b1f873" + }, + "SEWDModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWDModel" + ], + "sha": "dde4e02219449f149bb3403bbeae127cafaf9c79" + }, + "SEWForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWForCTC" + ], + "sha": "4477c7a277059fba08772acf91cf3e3dd3cb073b" + }, + "SEWForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWForSequenceClassification" + ], + "sha": "3b90fbb1c0c3848fed18f91a0169bb297a3e6619" + }, + "SEWModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWModel" + ], + "sha": "0a0fbb844eeefa0dce62bd05db30a2bb91e5dc88" + }, + "SamModel": { + "tokenizer_classes": [], + "processor_classes": [ + "SamImageProcessor" + ], + "model_classes": [ + "SamModel", + "TFSamModel" + ], + "sha": "eca8651bc84e5ac3b1b62e784b744a6bd1b82575" + }, + "SegformerForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "SegformerImageProcessor" + ], + "model_classes": [ + "SegformerForImageClassification", + "TFSegformerForImageClassification" + ], + "sha": "c566ae0ed382be4ed61ed6dacffa2ba663e9cc19" + }, + "SegformerForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "SegformerImageProcessor" + ], + "model_classes": [ + "SegformerForSemanticSegmentation", + "TFSegformerForSemanticSegmentation" + ], + "sha": "b73798972cdf24daafa858994713aca60e2bf90d" + }, + "SegformerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "SegformerImageProcessor" + ], + "model_classes": [ + "SegformerModel", + "TFSegformerModel" + ], + "sha": "3d4ba8ed2bdf801e6afa855b9d77893f2b7f9e10" + }, + "Speech2TextForConditionalGeneration": { + "tokenizer_classes": [ + "Speech2TextTokenizer" + ], + "processor_classes": [ + "Speech2TextFeatureExtractor" + ], + "model_classes": [ + "Speech2TextForConditionalGeneration", + "TFSpeech2TextForConditionalGeneration" + ], + "sha": "1da80293ec78762e136cf6dd64b652693f9ab364" + }, + "Speech2TextModel": { + "tokenizer_classes": [ + "Speech2TextTokenizer" + ], + "processor_classes": [ + "Speech2TextFeatureExtractor" + ], + "model_classes": [ + "Speech2TextModel", + "TFSpeech2TextModel" + ], + "sha": "7c6e63bd0c15dd99ef01573d4c43f90e4920cc91" + }, + "SpeechEncoderDecoderModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SpeechEncoderDecoderModel" + ], + "sha": "78602ae0857728e95de4042bdca8a31ef818890a" + }, + "SpeechT5ForSpeechToText": { + "tokenizer_classes": [ + "SpeechT5Tokenizer" + ], + "processor_classes": [ + "SpeechT5FeatureExtractor" + ], + "model_classes": [ + "SpeechT5ForSpeechToText" + ], + "sha": "d46f0a83324e5865420a27a738ef203292de3479" + }, + "SpeechT5ForTextToSpeech": { + "tokenizer_classes": [ + "SpeechT5Tokenizer" + ], + "processor_classes": [ + "SpeechT5FeatureExtractor" + ], + "model_classes": [ + "SpeechT5ForTextToSpeech" + ], + "sha": "922e748d9e1ea256a8d9259782021cd3820d5924" + }, + "SpeechT5Model": { + "tokenizer_classes": [ + "SpeechT5Tokenizer" + ], + "processor_classes": [ + "SpeechT5FeatureExtractor" + ], + "model_classes": [ + "SpeechT5Model" + ], + "sha": "7b248f77ca88ffddcdb538e772f6de63a86a4f9b" + }, + "SplinterForPreTraining": { + "tokenizer_classes": [ + "SplinterTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "SplinterForPreTraining" + ], + "sha": "e8a94efa740f1d685fa553f49132c6f022de5389" + }, + "SplinterForQuestionAnswering": { + "tokenizer_classes": [ + "SplinterTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "SplinterForQuestionAnswering" + ], + "sha": "d038b7b683face4a361ab0f474d8a5b111c44c4d" + }, + "SplinterModel": { + "tokenizer_classes": [ + "SplinterTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "SplinterModel" + ], + "sha": "a35b13cbb7faba46dc265761bb839267eb53d248" + }, + "SqueezeBertForMaskedLM": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForMaskedLM" + ], + "sha": "33ce239408c22d2c98be63c9ab4607ef9ceb6d49" + }, + "SqueezeBertForMultipleChoice": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForMultipleChoice" + ], + "sha": "7e9e666896420c7839e27dcb280981d034ba4da5" + }, + "SqueezeBertForQuestionAnswering": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForQuestionAnswering" + ], + "sha": "bceb045a9ac6eb2ded7d358ed577c6dc28ea487a" + }, + "SqueezeBertForSequenceClassification": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForSequenceClassification" + ], + "sha": "c5aeb1f454a1d059d41a5f8dacaf784b9de0b899" + }, + "SqueezeBertForTokenClassification": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForTokenClassification" + ], + "sha": "70ba60ca44a380e6aa983a37b163c57217219df7" + }, + "SqueezeBertModel": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertModel" + ], + "sha": "e0a3ac56a4047da3f921638252ead5e44438bbdb" + }, + "SwiftFormerForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwiftFormerForImageClassification" + ], + "sha": "a249b14a525d29e675b6e4af4baacd9ba7df7598" + }, + "SwiftFormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwiftFormerModel" + ], + "sha": "25ba2d88c770533f8c69811d2a454a00c1d09f5d" + }, + "Swin2SRForImageSuperResolution": { + "tokenizer_classes": [], + "processor_classes": [ + "Swin2SRImageProcessor" + ], + "model_classes": [ + "Swin2SRForImageSuperResolution" + ], + "sha": "3a2780de0b455084c018ac8a62b56040969e26ec" + }, + "Swin2SRModel": { + "tokenizer_classes": [], + "processor_classes": [ + "Swin2SRImageProcessor" + ], + "model_classes": [ + "Swin2SRModel" + ], + "sha": "c67f6ecff9ef8675c3869c987277b0a1e040f4be" + }, + "SwinBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwinBackbone" + ], + "sha": "89b28b8ec05a7b3357be75a77eb7809e6fd5cfef" + }, + "SwinForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwinForImageClassification", + "TFSwinForImageClassification" + ], + "sha": "e3c2e80f380ef79781313981da1a993dd8b8d34d" + }, + "SwinForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwinForMaskedImageModeling", + "TFSwinForMaskedImageModeling" + ], + "sha": "d84b061fbace1bc6e697e3253e222de42053f978" + }, + "SwinModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwinModel", + "TFSwinModel" + ], + "sha": "23ff641295660ec4fea399be8aa1bc14565961f8" + }, + "Swinv2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "Swinv2ForImageClassification" + ], + "sha": "3fd755cdf4cf611db83f72f9c9b00eb9257a38ca" + }, + "Swinv2ForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "Swinv2ForMaskedImageModeling" + ], + "sha": "8375c31eb6231fde36ec6533a34ba5b28e296163" + }, + "Swinv2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "Swinv2Model" + ], + "sha": "70aeb72e8a266f668c8b51a517ec01003b8d6804" + }, + "SwitchTransformersForConditionalGeneration": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SwitchTransformersForConditionalGeneration" + ], + "sha": "c8fcd2bb735894c78db7f1e5b51afc78aced7adb" + }, + "SwitchTransformersModel": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SwitchTransformersModel" + ], + "sha": "275bbf6d389bfd0540b9f824c609c6b22a577328" + }, + "T5EncoderModel": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5EncoderModel", + "TFT5EncoderModel" + ], + "sha": "1c75090036a2b3740dfe2d570b889332ad8e59e8" + }, + "T5ForConditionalGeneration": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5ForConditionalGeneration", + "TFT5ForConditionalGeneration" + ], + "sha": "593fd6072a4e265f5cc73b1973cd8af76b261f29" + }, + "T5ForQuestionAnswering": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5ForQuestionAnswering" + ], + "sha": "b9edf2de494244ff032f67d2d7bdf6c591000c94" + }, + "T5ForSequenceClassification": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5ForSequenceClassification" + ], + "sha": "105b5c4c8e1efe927444108f1388c4f102ebad15" + }, + "T5Model": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5Model", + "TFT5Model" + ], + "sha": "eb3d20dda0ba77c1de618d78116a1a0c784c515c" + }, + "TableTransformerForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "TableTransformerForObjectDetection" + ], + "sha": "9cf1e3f5c3555a727672a32b49f8b96c5aa20be6" + }, + "TableTransformerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "TableTransformerModel" + ], + "sha": "7b446244d8739b0c29d98f7d537b15ad578577d5" + }, + "TapasForMaskedLM": { + "tokenizer_classes": [ + "TapasTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTapasForMaskedLM", + "TapasForMaskedLM" + ], + "sha": "2cedb92dd9a3dc37ffb7d35ad5190b110992577c" + }, + "TapasForQuestionAnswering": { + "tokenizer_classes": [ + "TapasTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTapasForQuestionAnswering", + "TapasForQuestionAnswering" + ], + "sha": "4cc91b9e5db662e6e392d8052587ae419896d72b" + }, + "TapasForSequenceClassification": { + "tokenizer_classes": [ + "TapasTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTapasForSequenceClassification", + "TapasForSequenceClassification" + ], + "sha": "7c37bfb87a6fce2f8604bb3cab2a14e09a285e14" + }, + "TapasModel": { + "tokenizer_classes": [ + "TapasTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTapasModel", + "TapasModel" + ], + "sha": "bc004af0a415afe1f566c3afe8dd4d48d08c1ce0" + }, + "TimesformerForVideoClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "TimesformerForVideoClassification" + ], + "sha": "0b3b8e314618d7af34fb44477745491b44bf556d" + }, + "TimesformerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "TimesformerModel" + ], + "sha": "ea51f7ebb6426ad2b1fa1396e83f8e8ad5bc3b44" + }, + "TransfoXLForSequenceClassification": { + "tokenizer_classes": [ + "TransfoXLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTransfoXLForSequenceClassification", + "TransfoXLForSequenceClassification" + ], + "sha": "f3d370184350667d74056b979081b0bf5b0083c1" + }, + "TransfoXLLMHeadModel": { + "tokenizer_classes": [ + "TransfoXLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTransfoXLLMHeadModel", + "TransfoXLLMHeadModel" + ], + "sha": "e0d4cebcdde52d8d4c81782a1edc606830bd6afd" + }, + "TransfoXLModel": { + "tokenizer_classes": [ + "TransfoXLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTransfoXLModel", + "TransfoXLModel" + ], + "sha": "6938eeae35662a862accb01412dfc486454bdc8f" + }, + "TvltForPreTraining": { + "tokenizer_classes": [], + "processor_classes": [ + "TvltProcessor" + ], + "model_classes": [ + "TvltForPreTraining" + ], + "sha": "f7bd2833764eb6d55a921aaed81d3f21119016ae" + }, + "TvltModel": { + "tokenizer_classes": [], + "processor_classes": [ + "TvltProcessor" + ], + "model_classes": [ + "TvltModel" + ], + "sha": "c3cbf7a6159c038f333ce7adda2480ea3396b2b3" + }, + "UMT5EncoderModel": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "UMT5EncoderModel" + ], + "sha": "2894e49c9fbd17ea4b3dab56ec388be354c1a5f0" + }, + "UMT5ForQuestionAnswering": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "UMT5ForQuestionAnswering" + ], + "sha": "b381aa068a44200db539f2f48f4e34a5ed1cb093" + }, + "UMT5ForSequenceClassification": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "UMT5ForSequenceClassification" + ], + "sha": "aa9f77b7b3cff21425b7512e7c0f478af7b5db14" + }, + "UMT5Model": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "UMT5Model" + ], + "sha": "9180d850b24e5494442a4f7a8ca1a4c102f9babd" + }, + "UniSpeechForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechForCTC" + ], + "sha": "102b56d76f4d74cface309801c0ad80892583751" + }, + "UniSpeechForPreTraining": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechForPreTraining" + ], + "sha": "830be5b3e85aaae7bcc961218e417c29743d6042" + }, + "UniSpeechForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechForSequenceClassification" + ], + "sha": "a30ac1516944757ccd8efcbcf94033a03f8708bf" + }, + "UniSpeechModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechModel" + ], + "sha": "18e170eb1091715b74ace28c8c380b6bf2b6202d" + }, + "UniSpeechSatForAudioFrameClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForAudioFrameClassification" + ], + "sha": "7eba5a1c6cd610928b27ecb217bb17c729a07a57" + }, + "UniSpeechSatForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForCTC" + ], + "sha": "a8617538d3a2ae990f022bb0c36b8428a4870822" + }, + "UniSpeechSatForPreTraining": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForPreTraining" + ], + "sha": "a772f66db0ab49e1050e524d7fcbe5106ebdaf96" + }, + "UniSpeechSatForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForSequenceClassification" + ], + "sha": "f1c16567bd829a6d8a7a2d167d22e9653149e625" + }, + "UniSpeechSatForXVector": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForXVector" + ], + "sha": "71cb3780cf3678f74fba00e19df82df76dca6133" + }, + "UniSpeechSatModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatModel" + ], + "sha": "ea755bbc7c6c6aa649c58b4b000f243acbbd6b5a" + }, + "UperNetForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "SegformerImageProcessor" + ], + "model_classes": [ + "UperNetForSemanticSegmentation" + ], + "sha": "f1871cb388bc0b203f5397bfc06a373736c2fb9c" + }, + "VanForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "VanForImageClassification" + ], + "sha": "694eb147bc4768aeabeffbfb97732281b71a621d" + }, + "VanModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "VanModel" + ], + "sha": "d8ac60ce952020f2b0355fc566d634b2c5ba635d" + }, + "ViTForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFViTForImageClassification", + "ViTForImageClassification" + ], + "sha": "5b3b44a3ed492070c273e481e30ecf4deddc5ec3" + }, + "ViTForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "ViTForMaskedImageModeling" + ], + "sha": "d984e0b432fe195c2c26952d4f249031e7b1e2ea" + }, + "ViTHybridForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTHybridImageProcessor" + ], + "model_classes": [ + "ViTHybridForImageClassification" + ], + "sha": "69c7c396032ffe60d54953b584394899fb95ccc1" + }, + "ViTHybridModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTHybridImageProcessor" + ], + "model_classes": [ + "ViTHybridModel" + ], + "sha": "077443bfefe40d625314dbd274d2ff8089624797" + }, + "ViTMAEForPreTraining": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFViTMAEForPreTraining", + "ViTMAEForPreTraining" + ], + "sha": "2d98d80d9c45eef0d5b6f5426d7196bb546fe9fc" + }, + "ViTMAEModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFViTMAEModel", + "ViTMAEModel" + ], + "sha": "c7c2f12c19d2dbec08851a9dac7485909629a5fd" + }, + "ViTMSNForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "ViTMSNForImageClassification" + ], + "sha": "feda819aa7dbb55d850130f4cf1d210858d7eb89" + }, + "ViTMSNModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "ViTMSNModel" + ], + "sha": "0733abf168cb47a149821fdd2113d546e15c47de" + }, + "ViTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFViTModel", + "ViTModel" + ], + "sha": "31817b7a64ebc3333fcd4801dfbb356ab07b13dd" + }, + "VideoMAEForPreTraining": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "VideoMAEForPreTraining" + ], + "sha": "9de66c4bb759dc7269a7af17bf70b3194550acaa" + }, + "VideoMAEForVideoClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "VideoMAEForVideoClassification" + ], + "sha": "d3f743408386bc0ffe2d979de35335e87bc34aec" + }, + "VideoMAEModel": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "VideoMAEModel" + ], + "sha": "a2be96beba888817d92b67525601569d830342ff" + }, + "ViltForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "ViltImageProcessor" + ], + "model_classes": [ + "ViltForQuestionAnswering" + ], + "sha": "faeffbf43da6621717d8b13e7ebe87d58d750cb2" + }, + "ViltModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "ViltImageProcessor" + ], + "model_classes": [ + "ViltModel" + ], + "sha": "3a89b7b5782947c4f4125162ffe1c9cc18c9c800" + }, + "VisionEncoderDecoderModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFVisionEncoderDecoderModel", + "VisionEncoderDecoderModel" + ], + "sha": "23917761070cf16b26a6d033b6bff9100bbc618b" + }, + "VisionTextDualEncoderModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFVisionTextDualEncoderModel", + "VisionTextDualEncoderModel" + ], + "sha": "c3569ef17f66acbacb76f7ceb6f71e02d075dd6c" + }, + "VisualBertForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "VisualBertForPreTraining" + ], + "sha": "ce5a4d93ce762971cd216cda9aef8b9ce3f0450b" + }, + "VisualBertModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "VisualBertModel" + ], + "sha": "85020189fb7bf1217eb9370b09bca8ec5bcfdafa" + }, + "VitsModel": { + "tokenizer_classes": [ + "VitsTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "VitsModel" + ], + "sha": "b9a20ca5b6a7874576e485850260578895587dd2" + }, + "Wav2Vec2ConformerForAudioFrameClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForAudioFrameClassification" + ], + "sha": "e316a18a1d165b4cb51a7f28f8e8dab676da4b56" + }, + "Wav2Vec2ConformerForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForCTC" + ], + "sha": "a2ecb2985fcbb9f3ed000c12c1af6da36f5eaa3a" + }, + "Wav2Vec2ConformerForPreTraining": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForPreTraining" + ], + "sha": "099279b69e5da19efb05589804ccee210a0e57ae" + }, + "Wav2Vec2ConformerForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForSequenceClassification" + ], + "sha": "e8c1bca543c54bf15a6c026cb3761993b52cf617" + }, + "Wav2Vec2ConformerForXVector": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForXVector" + ], + "sha": "ba206a55998f16e134960728bd02006eaf39114f" + }, + "Wav2Vec2ConformerModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerModel" + ], + "sha": "ef2fe3aa8c23e6f8696e6612061aaddecae49994" + }, + "Wav2Vec2ForAudioFrameClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForAudioFrameClassification" + ], + "sha": "ab219f119e10f56e1059966c66d23f0df3c2c343" + }, + "Wav2Vec2ForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForCTC" + ], + "sha": "6245fbb1cb99cea5c4de1e73f81fba978fb275ac" + }, + "Wav2Vec2ForMaskedLM": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForMaskedLM" + ], + "sha": "e083cf4fefec4df3c241dbbe5e17a84a794a89bd" + }, + "Wav2Vec2ForPreTraining": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForPreTraining" + ], + "sha": "a8d71e216334260353ccbf5ce84cd6924f7457da" + }, + "Wav2Vec2ForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "TFWav2Vec2ForSequenceClassification", + "Wav2Vec2ForSequenceClassification" + ], + "sha": "2000b2022abcc37100241485f5872126b70164c9" + }, + "Wav2Vec2ForXVector": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForXVector" + ], + "sha": "f4c422db53aae061ea609f4407af7cd5b33c8942" + }, + "Wav2Vec2Model": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "TFWav2Vec2Model", + "Wav2Vec2Model" + ], + "sha": "7a998ee3ee0619a52828a79c3eed6872fd053f37" + }, + "WavLMForAudioFrameClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMForAudioFrameClassification" + ], + "sha": "b135610f8d5de0b1a5bf5ed7212966135c63d6ec" + }, + "WavLMForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMForCTC" + ], + "sha": "f1139c5ddf34d2327ae1f6917edd7da180b06971" + }, + "WavLMForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMForSequenceClassification" + ], + "sha": "4ba5f2019b46866ce2011c993194ebda60afc028" + }, + "WavLMForXVector": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMForXVector" + ], + "sha": "faf9264eac56a56d5510a0984d7e1146e4c8cf62" + }, + "WavLMModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMModel" + ], + "sha": "e932275e37cb643be271f655bd1d649f4f4b4bd5" + }, + "WhisperForAudioClassification": { + "tokenizer_classes": [ + "WhisperTokenizer" + ], + "processor_classes": [ + "WhisperFeatureExtractor" + ], + "model_classes": [ + "WhisperForAudioClassification" + ], + "sha": "d71b13674b1a67443cd19d0594a3b5b1e5968f0d" + }, + "WhisperForCausalLM": { + "tokenizer_classes": [ + "WhisperTokenizer" + ], + "processor_classes": [ + "WhisperFeatureExtractor" + ], + "model_classes": [ + "WhisperForCausalLM" + ], + "sha": "e7febfd7f4512e029293c677e6d2633e23fc459a" + }, + "WhisperForConditionalGeneration": { + "tokenizer_classes": [ + "WhisperTokenizer", + "WhisperTokenizerFast" + ], + "processor_classes": [ + "WhisperFeatureExtractor" + ], + "model_classes": [ + "TFWhisperForConditionalGeneration", + "WhisperForConditionalGeneration" + ], + "sha": "598101b885b24508042d9292e54aa04bff96318e" + }, + "WhisperModel": { + "tokenizer_classes": [ + "WhisperTokenizer", + "WhisperTokenizerFast" + ], + "processor_classes": [ + "WhisperFeatureExtractor" + ], + "model_classes": [ + "TFWhisperModel", + "WhisperModel" + ], + "sha": "c04c50216bb6b0a8f4d55f2fa9f9f4cf61c8a77c" + }, + "XCLIPModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "XCLIPModel" + ], + "sha": "299ffffc6b94c3558bf7dbc38e24074c99490046" + }, + "XGLMForCausalLM": { + "tokenizer_classes": [ + "XGLMTokenizer", + "XGLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXGLMForCausalLM", + "XGLMForCausalLM" + ], + "sha": "d5381ce297c249d559937c6bb6316cf1fdad2613" + }, + "XGLMModel": { + "tokenizer_classes": [ + "XGLMTokenizer", + "XGLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXGLMModel", + "XGLMModel" + ], + "sha": "2b5cef167822cfaa558d259af1722e2f785cd3d5" + }, + "XLMForMultipleChoice": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMForMultipleChoice", + "XLMForMultipleChoice" + ], + "sha": "f0c8cc6462449ac9eb9b4158e433bd3c923db3af" + }, + "XLMForQuestionAnsweringSimple": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMForQuestionAnsweringSimple", + "XLMForQuestionAnsweringSimple" + ], + "sha": "82e93a2653cf3646eaaf02d8cc5f8ff9a4551523" + }, + "XLMForSequenceClassification": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMForSequenceClassification", + "XLMForSequenceClassification" + ], + "sha": "2d6892f5f703be9b481bca91477032bd0e36dbe5" + }, + "XLMForTokenClassification": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMForTokenClassification", + "XLMForTokenClassification" + ], + "sha": "9a591395e7a0643a03f5d2debb98caa3966e021c" + }, + "XLMModel": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMModel", + "XLMModel" + ], + "sha": "022b86df246414ff712475d9ca55db690ff1d3bf" + }, + "XLMRobertaXLForCausalLM": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForCausalLM" + ], + "sha": "fc05408e5b33a31638476ef337719dfbb7615ef3" + }, + "XLMRobertaXLForMaskedLM": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForMaskedLM" + ], + "sha": "e96f198eede757e5ae2c87632fdcfb341073ef6e" + }, + "XLMRobertaXLForMultipleChoice": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForMultipleChoice" + ], + "sha": "52732625f1bfbbb7cb4ba1cf0963de596d81822d" + }, + "XLMRobertaXLForQuestionAnswering": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForQuestionAnswering" + ], + "sha": "da388fdd2d28e0757eb0c2b2c612a8ff03af2223" + }, + "XLMRobertaXLForSequenceClassification": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForSequenceClassification" + ], + "sha": "980721187633bcf21ac0b8edbed933527f4611df" + }, + "XLMRobertaXLForTokenClassification": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForTokenClassification" + ], + "sha": "37a97280faf6fef0bd946d3934d77a1b60fbf473" + }, + "XLMRobertaXLModel": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLModel" + ], + "sha": "8fbeb39a984912e47f5d24a31be61639031a0fc3" + }, + "XLMWithLMHeadModel": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMWithLMHeadModel", + "XLMWithLMHeadModel" + ], + "sha": "db70bdefbaf095e88b8097e4b601d9105a511afa" + }, + "XLNetForMultipleChoice": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetForMultipleChoice", + "XLNetForMultipleChoice" + ], + "sha": "8bb7e28d0cd1e93154d3232baf5e9c79acaf9f1a" + }, + "XLNetForQuestionAnsweringSimple": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetForQuestionAnsweringSimple", + "XLNetForQuestionAnsweringSimple" + ], + "sha": "fabd06a45d947f3d46f1b8dce2186cf3b27776dc" + }, + "XLNetForSequenceClassification": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetForSequenceClassification", + "XLNetForSequenceClassification" + ], + "sha": "e3c194f24537ebf2c474ade60becb9397696edec" + }, + "XLNetForTokenClassification": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetForTokenClassification", + "XLNetForTokenClassification" + ], + "sha": "16aa15029aa667046d504c4a88ceddfdd5b5fb40" + }, + "XLNetLMHeadModel": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetLMHeadModel", + "XLNetLMHeadModel" + ], + "sha": "c9a98cc982a16ca162832a8cbea25116479bb938" + }, + "XLNetModel": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetModel", + "XLNetModel" + ], + "sha": "1d6e231942135faf32b8d9a97773d8f6c85ca561" + }, + "XmodForCausalLM": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForCausalLM" + ], + "sha": "c6b746071f2f067099a8fb4f57ce3c27a7e4b67d" + }, + "XmodForMaskedLM": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForMaskedLM" + ], + "sha": "e1085818f4ed3c6073b2038635e5f3061208923d" + }, + "XmodForMultipleChoice": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForMultipleChoice" + ], + "sha": "c63042cdf196be3fed846421b345d439b2483f69" + }, + "XmodForQuestionAnswering": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForQuestionAnswering" + ], + "sha": "75acd3071fae9978c82618cd0f090c87aabc1f23" + }, + "XmodForSequenceClassification": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForSequenceClassification" + ], + "sha": "523a16570be048618913ac17ccd00d343bcb5e99" + }, + "XmodForTokenClassification": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForTokenClassification" + ], + "sha": "a0f0a02732b4579670dad11a69ae244ebd777b49" + }, + "XmodModel": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodModel" + ], + "sha": "bc286de0035450e7dcd6bcce78098a967b9c2b6c" + }, + "YolosForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "YolosImageProcessor" + ], + "model_classes": [ + "YolosForObjectDetection" + ], + "sha": "0a4aae25bfbe8b5edd4815cb00d697a6ba7d2126" + }, + "YolosModel": { + "tokenizer_classes": [], + "processor_classes": [ + "YolosImageProcessor" + ], + "model_classes": [ + "YolosModel" + ], + "sha": "339bc51f1914f031a550e5f95095ed4a4c22a7de" + }, + "YosoForMaskedLM": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForMaskedLM" + ], + "sha": "cb291bedcbec199ea195f086e3ebea6fab026bba" + }, + "YosoForMultipleChoice": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForMultipleChoice" + ], + "sha": "cf2d3a3f0628bc9d0da68ea8de26b12016453fee" + }, + "YosoForQuestionAnswering": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForQuestionAnswering" + ], + "sha": "e8c3091f674588adfa3371b3de0427a9b39dd03f" + }, + "YosoForSequenceClassification": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForSequenceClassification" + ], + "sha": "88132cbaa1a9a87f65b6f9813c388011377f18cf" + }, + "YosoForTokenClassification": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForTokenClassification" + ], + "sha": "fd2219856608d3dba70dc7b1a06af629903dec31" + }, + "YosoModel": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoModel" + ], + "sha": "e144d9f1fe39c21eda1177702640e126892605ce" + } +} \ No newline at end of file diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/add_pipeline_model_mapping_to_test.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/add_pipeline_model_mapping_to_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ebefcff9afe2ecd59ed9910371694000ef34cb5e --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/add_pipeline_model_mapping_to_test.py @@ -0,0 +1,337 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +"""A script to add and/or update the attribute `pipeline_model_mapping` in model test files. + +This script will be (mostly) used in the following 2 situations: + + - run within a (scheduled) CI job to: + - check if model test files in the library have updated `pipeline_model_mapping`, + - and/or update test files and (possibly) open a GitHub pull request automatically + - being run by a `transformers` member to quickly check and update some particular test file(s) + +This script is **NOT** intended to be run (manually) by community contributors. +""" + + +import argparse +import glob +import inspect +import os +import re +import unittest + +from get_test_info import get_test_classes + +from tests.test_pipeline_mixin import pipeline_test_mapping + + +PIPELINE_TEST_MAPPING = {} +for task, _ in pipeline_test_mapping.items(): + PIPELINE_TEST_MAPPING[task] = {"pt": None, "tf": None} + + +# DO **NOT** add item to this set (unless the reason is approved) +TEST_FILE_TO_IGNORE = { + "tests/models/esm/test_modeling_esmfold.py", # The pipeline test mapping is added to `test_modeling_esm.py` +} + + +def get_framework(test_class): + """Infer the framework from the test class `test_class`.""" + + if "ModelTesterMixin" in [x.__name__ for x in test_class.__bases__]: + return "pt" + elif "TFModelTesterMixin" in [x.__name__ for x in test_class.__bases__]: + return "tf" + elif "FlaxModelTesterMixin" in [x.__name__ for x in test_class.__bases__]: + return "flax" + else: + return None + + +def get_mapping_for_task(task, framework): + """Get mappings defined in `XXXPipelineTests` for the task `task`.""" + # Use the cached results + if PIPELINE_TEST_MAPPING[task].get(framework, None) is not None: + return PIPELINE_TEST_MAPPING[task][framework] + + pipeline_test_class = pipeline_test_mapping[task]["test"] + mapping = None + + if framework == "pt": + mapping = getattr(pipeline_test_class, "model_mapping", None) + elif framework == "tf": + mapping = getattr(pipeline_test_class, "tf_model_mapping", None) + + if mapping is not None: + mapping = dict(mapping.items()) + + # cache the results + PIPELINE_TEST_MAPPING[task][framework] = mapping + return mapping + + +def get_model_for_pipeline_test(test_class, task): + """Get the model architecture(s) related to the test class `test_class` for a pipeline `task`.""" + framework = get_framework(test_class) + if framework is None: + return None + mapping = get_mapping_for_task(task, framework) + if mapping is None: + return None + + config_classes = list({model_class.config_class for model_class in test_class.all_model_classes}) + if len(config_classes) != 1: + raise ValueError("There should be exactly one configuration class from `test_class.all_model_classes`.") + + # This could be a list/tuple of model classes, but it's rare. + model_class = mapping.get(config_classes[0], None) + if isinstance(model_class, (tuple, list)): + model_class = sorted(model_class, key=lambda x: x.__name__) + + return model_class + + +def get_pipeline_model_mapping(test_class): + """Get `pipeline_model_mapping` for `test_class`.""" + mapping = [(task, get_model_for_pipeline_test(test_class, task)) for task in pipeline_test_mapping] + mapping = sorted([(task, model) for task, model in mapping if model is not None], key=lambda x: x[0]) + + return dict(mapping) + + +def get_pipeline_model_mapping_string(test_class): + """Get `pipeline_model_mapping` for `test_class` as a string (to be added to the test file). + + This will be a 1-line string. After this is added to a test file, `make style` will format it beautifully. + """ + framework = get_framework(test_class) + if framework == "pt": + framework = "torch" + default_value = "{}" + + mapping = get_pipeline_model_mapping(test_class) + if len(mapping) == 0: + return "" + + texts = [] + for task, model_classes in mapping.items(): + if isinstance(model_classes, (tuple, list)): + # A list/tuple of model classes + value = "(" + ", ".join([x.__name__ for x in model_classes]) + ")" + else: + # A single model class + value = model_classes.__name__ + texts.append(f'"{task}": {value}') + text = "{" + ", ".join(texts) + "}" + text = f"pipeline_model_mapping = {text} if is_{framework}_available() else {default_value}" + + return text + + +def is_valid_test_class(test_class): + """Restrict to `XXXModelTesterMixin` and should be a subclass of `unittest.TestCase`.""" + base_class_names = {"ModelTesterMixin", "TFModelTesterMixin", "FlaxModelTesterMixin"} + if not issubclass(test_class, unittest.TestCase): + return False + return len(base_class_names.intersection([x.__name__ for x in test_class.__bases__])) > 0 + + +def find_test_class(test_file): + """Find a test class in `test_file` to which we will add `pipeline_model_mapping`.""" + test_classes = [x for x in get_test_classes(test_file) if is_valid_test_class(x)] + + target_test_class = None + for test_class in test_classes: + # If a test class has defined `pipeline_model_mapping`, let's take it + if getattr(test_class, "pipeline_model_mapping", None) is not None: + target_test_class = test_class + break + # Take the test class with the shortest name (just a heuristic) + if target_test_class is None and len(test_classes) > 0: + target_test_class = sorted(test_classes, key=lambda x: (len(x.__name__), x.__name__))[0] + + return target_test_class + + +def find_block_ending(lines, start_idx, indent_level): + end_idx = start_idx + for idx, line in enumerate(lines[start_idx:]): + indent = len(line) - len(line.lstrip()) + if idx == 0 or indent > indent_level or (indent == indent_level and line.strip() == ")"): + end_idx = start_idx + idx + elif idx > 0 and indent <= indent_level: + # Outside the definition block of `pipeline_model_mapping` + break + + return end_idx + + +def add_pipeline_model_mapping(test_class, overwrite=False): + """Add `pipeline_model_mapping` to `test_class`.""" + if getattr(test_class, "pipeline_model_mapping", None) is not None: + if not overwrite: + return "", -1 + + line_to_add = get_pipeline_model_mapping_string(test_class) + if len(line_to_add) == 0: + return "", -1 + line_to_add = line_to_add + "\n" + + # The code defined the class `test_class` + class_lines, class_start_line_no = inspect.getsourcelines(test_class) + # `inspect` gives the code for an object, including decorator(s) if any. + # We (only) need the exact line of the class definition. + for idx, line in enumerate(class_lines): + if line.lstrip().startswith("class "): + class_lines = class_lines[idx:] + class_start_line_no += idx + break + class_end_line_no = class_start_line_no + len(class_lines) - 1 + + # The index in `class_lines` that starts the definition of `all_model_classes`, `all_generative_model_classes` or + # `pipeline_model_mapping`. This assumes they are defined in such order, and we take the start index of the last + # block that appears in a `test_class`. + start_idx = None + # The indent level of the line at `class_lines[start_idx]` (if defined) + indent_level = 0 + # To record if `pipeline_model_mapping` is found in `test_class`. + def_line = None + for idx, line in enumerate(class_lines): + if line.strip().startswith("all_model_classes = "): + indent_level = len(line) - len(line.lstrip()) + start_idx = idx + elif line.strip().startswith("all_generative_model_classes = "): + indent_level = len(line) - len(line.lstrip()) + start_idx = idx + elif line.strip().startswith("pipeline_model_mapping = "): + indent_level = len(line) - len(line.lstrip()) + start_idx = idx + def_line = line + break + + if start_idx is None: + return "", -1 + # Find the ending index (inclusive) of the above found block. + end_idx = find_block_ending(class_lines, start_idx, indent_level) + + # Extract `is_xxx_available()` from existing blocks: some models require specific libraries like `timm` and use + # `is_timm_available()` instead of `is_torch_available()`. + # Keep leading and trailing whitespaces + r = re.compile(r"\s(is_\S+?_available\(\))\s") + for line in class_lines[start_idx : end_idx + 1]: + backend_condition = r.search(line) + if backend_condition is not None: + # replace the leading and trailing whitespaces to the space character " ". + target = " " + backend_condition[0][1:-1] + " " + line_to_add = r.sub(target, line_to_add) + break + + if def_line is None: + # `pipeline_model_mapping` is not defined. The target index is set to the ending index (inclusive) of + # `all_model_classes` or `all_generative_model_classes`. + target_idx = end_idx + else: + # `pipeline_model_mapping` is defined. The target index is set to be one **BEFORE** its start index. + target_idx = start_idx - 1 + # mark the lines of the currently existing `pipeline_model_mapping` to be removed. + for idx in range(start_idx, end_idx + 1): + # These lines are going to be removed before writing to the test file. + class_lines[idx] = None # noqa + + # Make sure the test class is a subclass of `PipelineTesterMixin`. + parent_classes = [x.__name__ for x in test_class.__bases__] + if "PipelineTesterMixin" not in parent_classes: + # Put `PipelineTesterMixin` just before `unittest.TestCase` + _parent_classes = [x for x in parent_classes if x != "TestCase"] + ["PipelineTesterMixin"] + if "TestCase" in parent_classes: + # Here we **assume** the original string is always with `unittest.TestCase`. + _parent_classes.append("unittest.TestCase") + parent_classes = ", ".join(_parent_classes) + for idx, line in enumerate(class_lines): + # Find the ending of the declaration of `test_class` + if line.strip().endswith("):"): + # mark the lines of the declaration of `test_class` to be removed + for _idx in range(idx + 1): + class_lines[_idx] = None # noqa + break + # Add the new, one-line, class declaration for `test_class` + class_lines[0] = f"class {test_class.__name__}({parent_classes}):\n" + + # Add indentation + line_to_add = " " * indent_level + line_to_add + # Insert `pipeline_model_mapping` to `class_lines`. + # (The line at `target_idx` should be kept by definition!) + class_lines = class_lines[: target_idx + 1] + [line_to_add] + class_lines[target_idx + 1 :] + # Remove the lines that are marked to be removed + class_lines = [x for x in class_lines if x is not None] + + # Move from test class to module (in order to write to the test file) + module_lines = inspect.getsourcelines(inspect.getmodule(test_class))[0] + # Be careful with the 1-off between line numbers and array indices + module_lines = module_lines[: class_start_line_no - 1] + class_lines + module_lines[class_end_line_no:] + code = "".join(module_lines) + + moddule_file = inspect.getsourcefile(test_class) + with open(moddule_file, "w", encoding="UTF-8", newline="\n") as fp: + fp.write(code) + + return line_to_add + + +def add_pipeline_model_mapping_to_test_file(test_file, overwrite=False): + """Add `pipeline_model_mapping` to `test_file`.""" + test_class = find_test_class(test_file) + if test_class: + add_pipeline_model_mapping(test_class, overwrite=overwrite) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--test_file", type=str, help="A path to the test file, starting with the repository's `tests` directory." + ) + parser.add_argument( + "--all", + action="store_true", + help="If to check and modify all test files.", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help="If to overwrite a test class if it has already defined `pipeline_model_mapping`.", + ) + args = parser.parse_args() + + if not args.all and not args.test_file: + raise ValueError("Please specify either `test_file` or pass `--all` to check/modify all test files.") + elif args.all and args.test_file: + raise ValueError("Only one of `--test_file` and `--all` could be specified.") + + test_files = [] + if args.test_file: + test_files = [args.test_file] + else: + pattern = os.path.join("tests", "models", "**", "test_modeling_*.py") + for test_file in glob.glob(pattern): + # `Flax` is not concerned at this moment + if not test_file.startswith("test_modeling_flax_"): + test_files.append(test_file) + + for test_file in test_files: + if test_file in TEST_FILE_TO_IGNORE: + print(f"[SKIPPED] {test_file} is skipped as it is in `TEST_FILE_TO_IGNORE` in the file {__file__}.") + continue + add_pipeline_model_mapping_to_test_file(test_file, overwrite=args.overwrite) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_build.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_build.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cca31f837fb043cff97c7d44607c0827c41a26 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_build.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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 argparse +import importlib +from pathlib import Path + + +# Test all the extensions added in the setup +FILES_TO_FIND = [ + "kernels/rwkv/wkv_cuda.cu", + "kernels/rwkv/wkv_op.cpp", + "kernels/deformable_detr/ms_deform_attn.h", + "kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh", + "models/graphormer/algos_graphormer.pyx", +] + + +def test_custom_files_are_present(transformers_path): + # Test all the extensions added in the setup + for file in FILES_TO_FIND: + if not (transformers_path / file).exists(): + return False + return True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check_lib", action="store_true", help="Whether to check the build or the actual package.") + args = parser.parse_args() + if args.check_lib: + transformers_module = importlib.import_module("transformers") + transformers_path = Path(transformers_module.__file__).parent + else: + transformers_path = Path.cwd() / "build/lib/transformers" + if not test_custom_files_are_present(transformers_path): + raise ValueError("The built release does not contain the custom files. Fix this before going further!") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_config_attributes.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_config_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..e1682fb07589ba1f562b97457996baece9fe2e77 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_config_attributes.py @@ -0,0 +1,326 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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 os +import re + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_config_docstrings.py +PATH_TO_TRANSFORMERS = "src/transformers" + + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + +CONFIG_MAPPING = transformers.models.auto.configuration_auto.CONFIG_MAPPING + +SPECIAL_CASES_TO_ALLOW = { + # used to compute the property `self.chunk_length` + "EncodecConfig": ["overlap"], + # used as `self.bert_model = BertModel(config, ...)` + "DPRConfig": True, + "FuyuConfig": True, + # not used in modeling files, but it's an important information + "FSMTConfig": ["langs"], + # used internally in the configuration class file + "GPTNeoConfig": ["attention_types"], + # used internally in the configuration class file + "EsmConfig": ["is_folding_model"], + # used during training (despite we don't have training script for these models yet) + "Mask2FormerConfig": ["ignore_value"], + # `ignore_value` used during training (despite we don't have training script for these models yet) + # `norm` used in conversion script (despite not using in the modeling file) + "OneFormerConfig": ["ignore_value", "norm"], + # used during preprocessing and collation, see `collating_graphormer.py` + "GraphormerConfig": ["spatial_pos_max"], + # used internally in the configuration class file + "T5Config": ["feed_forward_proj"], + # used internally in the configuration class file + # `tokenizer_class` get default value `T5Tokenizer` intentionally + "MT5Config": ["feed_forward_proj", "tokenizer_class"], + "UMT5Config": ["feed_forward_proj", "tokenizer_class"], + # used internally in the configuration class file + "LongT5Config": ["feed_forward_proj"], + # used internally in the configuration class file + "Pop2PianoConfig": ["feed_forward_proj"], + # used internally in the configuration class file + "SwitchTransformersConfig": ["feed_forward_proj"], + # having default values other than `1e-5` - we can't fix them without breaking + "BioGptConfig": ["layer_norm_eps"], + # having default values other than `1e-5` - we can't fix them without breaking + "GLPNConfig": ["layer_norm_eps"], + # having default values other than `1e-5` - we can't fix them without breaking + "SegformerConfig": ["layer_norm_eps"], + # having default values other than `1e-5` - we can't fix them without breaking + "CvtConfig": ["layer_norm_eps"], + # having default values other than `1e-5` - we can't fix them without breaking + "PerceiverConfig": ["layer_norm_eps"], + # used internally to calculate the feature size + "InformerConfig": ["num_static_real_features", "num_time_features"], + # used internally to calculate the feature size + "TimeSeriesTransformerConfig": ["num_static_real_features", "num_time_features"], + # used internally to calculate the feature size + "AutoformerConfig": ["num_static_real_features", "num_time_features"], + # used internally to calculate `mlp_dim` + "SamVisionConfig": ["mlp_ratio"], + # For (head) training, but so far not implemented + "ClapAudioConfig": ["num_classes"], + # Not used, but providing useful information to users + "SpeechT5HifiGanConfig": ["sampling_rate"], + # Actually used in the config or generation config, in that case necessary for the sub-components generation + "SeamlessM4TConfig": [ + "max_new_tokens", + "t2u_max_new_tokens", + "t2u_decoder_attention_heads", + "t2u_decoder_ffn_dim", + "t2u_decoder_layers", + "t2u_encoder_attention_heads", + "t2u_encoder_ffn_dim", + "t2u_encoder_layers", + "t2u_max_position_embeddings", + ], + # Actually used in the config or generation config, in that case necessary for the sub-components generation + "SeamlessM4Tv2Config": [ + "max_new_tokens", + "t2u_decoder_attention_heads", + "t2u_decoder_ffn_dim", + "t2u_decoder_layers", + "t2u_encoder_attention_heads", + "t2u_encoder_ffn_dim", + "t2u_encoder_layers", + "t2u_max_position_embeddings", + "t2u_variance_pred_dropout", + "t2u_variance_predictor_embed_dim", + "t2u_variance_predictor_hidden_dim", + "t2u_variance_predictor_kernel_size", + ], +} + + +# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure +SPECIAL_CASES_TO_ALLOW.update( + { + "CLIPSegConfig": True, + "DeformableDetrConfig": True, + "DetaConfig": True, + "DinatConfig": True, + "DonutSwinConfig": True, + "EfficientFormerConfig": True, + "FSMTConfig": True, + "JukeboxConfig": True, + "LayoutLMv2Config": True, + "MaskFormerSwinConfig": True, + "MT5Config": True, + # For backward compatibility with trust remote code models + "MptConfig": True, + "MptAttentionConfig": True, + "NatConfig": True, + "OneFormerConfig": True, + "PerceiverConfig": True, + "RagConfig": True, + "SpeechT5Config": True, + "SwinConfig": True, + "Swin2SRConfig": True, + "Swinv2Config": True, + "SwitchTransformersConfig": True, + "TableTransformerConfig": True, + "TapasConfig": True, + "UniSpeechConfig": True, + "UniSpeechSatConfig": True, + "WavLMConfig": True, + "WhisperConfig": True, + # TODO: @Arthur (for `alignment_head` and `alignment_layer`) + "JukeboxPriorConfig": True, + # TODO: @Younes (for `is_decoder`) + "Pix2StructTextConfig": True, + "IdeficsConfig": True, + "IdeficsVisionConfig": True, + "IdeficsPerceiverConfig": True, + } +) + + +def check_attribute_being_used(config_class, attributes, default_value, source_strings): + """Check if any name in `attributes` is used in one of the strings in `source_strings` + + Args: + config_class (`type`): + The configuration class for which the arguments in its `__init__` will be checked. + attributes (`List[str]`): + The name of an argument (or attribute) and its variant names if any. + default_value (`Any`): + A default value for the attribute in `attributes` assigned in the `__init__` of `config_class`. + source_strings (`List[str]`): + The python source code strings in the same modeling directory where `config_class` is defined. The file + containing the definition of `config_class` should be excluded. + """ + attribute_used = False + for attribute in attributes: + for modeling_source in source_strings: + # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` + if ( + f"config.{attribute}" in modeling_source + or f'getattr(config, "{attribute}"' in modeling_source + or f'getattr(self.config, "{attribute}"' in modeling_source + ): + attribute_used = True + # Deal with multi-line cases + elif ( + re.search( + rf'getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"', + modeling_source, + ) + is not None + ): + attribute_used = True + # `SequenceSummary` is called with `SequenceSummary(config)` + elif attribute in [ + "summary_type", + "summary_use_proj", + "summary_activation", + "summary_last_dropout", + "summary_proj_to_labels", + "summary_first_dropout", + ]: + if "SequenceSummary" in modeling_source: + attribute_used = True + if attribute_used: + break + if attribute_used: + break + + # common and important attributes, even if they do not always appear in the modeling files + attributes_to_allow = [ + "bos_index", + "eos_index", + "pad_index", + "unk_index", + "mask_index", + "image_size", + "use_cache", + "out_features", + "out_indices", + "sampling_rate", + ] + attributes_used_in_generation = ["encoder_no_repeat_ngram_size"] + + # Special cases to be allowed + case_allowed = True + if not attribute_used: + case_allowed = False + for attribute in attributes: + # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` + if attribute in ["is_encoder_decoder"] and default_value is True: + case_allowed = True + elif attribute in ["tie_word_embeddings"] and default_value is False: + case_allowed = True + + # Allow cases without checking the default value in the configuration class + elif attribute in attributes_to_allow + attributes_used_in_generation: + case_allowed = True + elif attribute.endswith("_token_id"): + case_allowed = True + + # configuration class specific cases + if not case_allowed: + allowed_cases = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__, []) + case_allowed = allowed_cases is True or attribute in allowed_cases + + return attribute_used or case_allowed + + +def check_config_attributes_being_used(config_class): + """Check the arguments in `__init__` of `config_class` are used in the modeling files in the same directory + + Args: + config_class (`type`): + The configuration class for which the arguments in its `__init__` will be checked. + """ + # Get the parameters in `__init__` of the configuration class, and the default values if any + signature = dict(inspect.signature(config_class.__init__).parameters) + parameter_names = [x for x in list(signature.keys()) if x not in ["self", "kwargs"]] + parameter_defaults = [signature[param].default for param in parameter_names] + + # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long + # as one variant is used, the test should pass + reversed_attribute_map = {} + if len(config_class.attribute_map) > 0: + reversed_attribute_map = {v: k for k, v in config_class.attribute_map.items()} + + # Get the path to modeling source files + config_source_file = inspect.getsourcefile(config_class) + model_dir = os.path.dirname(config_source_file) + # Let's check against all frameworks: as long as one framework uses an attribute, we are good. + modeling_paths = [os.path.join(model_dir, fn) for fn in os.listdir(model_dir) if fn.startswith("modeling_")] + + # Get the source code strings + modeling_sources = [] + for path in modeling_paths: + if os.path.isfile(path): + with open(path, encoding="utf8") as fp: + modeling_sources.append(fp.read()) + + unused_attributes = [] + for config_param, default_value in zip(parameter_names, parameter_defaults): + # `attributes` here is all the variant names for `config_param` + attributes = [config_param] + # some configuration classes have non-empty `attribute_map`, and both names could be used in the + # corresponding modeling files. As long as one of them appears, it is fine. + if config_param in reversed_attribute_map: + attributes.append(reversed_attribute_map[config_param]) + + if not check_attribute_being_used(config_class, attributes, default_value, modeling_sources): + unused_attributes.append(attributes[0]) + + return sorted(unused_attributes) + + +def check_config_attributes(): + """Check the arguments in `__init__` of all configuration classes are used in python files""" + configs_with_unused_attributes = {} + for _config_class in list(CONFIG_MAPPING.values()): + # Skip deprecated models + if "models.deprecated" in _config_class.__module__: + continue + # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) + config_classes_in_module = [ + cls + for name, cls in inspect.getmembers( + inspect.getmodule(_config_class), + lambda x: inspect.isclass(x) + and issubclass(x, PretrainedConfig) + and inspect.getmodule(x) == inspect.getmodule(_config_class), + ) + ] + for config_class in config_classes_in_module: + unused_attributes = check_config_attributes_being_used(config_class) + if len(unused_attributes) > 0: + configs_with_unused_attributes[config_class.__name__] = unused_attributes + + if len(configs_with_unused_attributes) > 0: + error = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" + for name, attributes in configs_with_unused_attributes.items(): + error += f"{name}: {attributes}\n" + + raise ValueError(error) + + +if __name__ == "__main__": + check_config_attributes() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_config_docstrings.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_config_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..02ec510baba64ffd5ccdda8e7b4c0d4df994576d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_config_docstrings.py @@ -0,0 +1,97 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# 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 re + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_config_docstrings.py +PATH_TO_TRANSFORMERS = "src/transformers" + + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + +CONFIG_MAPPING = transformers.models.auto.configuration_auto.CONFIG_MAPPING + +# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. +# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` +_re_checkpoint = re.compile(r"\[(.+?)\]\((https://huggingface\.co/.+?)\)") + + +CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK = { + "DecisionTransformerConfig", + "EncoderDecoderConfig", + "MusicgenConfig", + "RagConfig", + "SpeechEncoderDecoderConfig", + "TimmBackboneConfig", + "VisionEncoderDecoderConfig", + "VisionTextDualEncoderConfig", + "LlamaConfig", +} + + +def get_checkpoint_from_config_class(config_class): + checkpoint = None + + # source code of `config_class` + config_source = inspect.getsource(config_class) + checkpoints = _re_checkpoint.findall(config_source) + + # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. + # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` + for ckpt_name, ckpt_link in checkpoints: + # allow the link to end with `/` + if ckpt_link.endswith("/"): + ckpt_link = ckpt_link[:-1] + + # verify the checkpoint name corresponds to the checkpoint link + ckpt_link_from_name = f"https://huggingface.co/{ckpt_name}" + if ckpt_link == ckpt_link_from_name: + checkpoint = ckpt_name + break + + return checkpoint + + +def check_config_docstrings_have_checkpoints(): + configs_without_checkpoint = [] + + for config_class in list(CONFIG_MAPPING.values()): + # Skip deprecated models + if "models.deprecated" in config_class.__module__: + continue + checkpoint = get_checkpoint_from_config_class(config_class) + + name = config_class.__name__ + if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: + configs_without_checkpoint.append(name) + + if len(configs_without_checkpoint) > 0: + message = "\n".join(sorted(configs_without_checkpoint)) + raise ValueError( + f"The following configurations don't contain any valid checkpoint:\n{message}\n\n" + "The requirement is to include a link pointing to one of the models of this architecture in the " + "docstring of the config classes listed above. The link should have be a markdown format like " + "[myorg/mymodel](https://huggingface.co/myorg/mymodel)." + ) + + +if __name__ == "__main__": + check_config_docstrings_have_checkpoints() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_copies.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_copies.py new file mode 100644 index 0000000000000000000000000000000000000000..3d352cc8310e4fa6ab68b02586aa9d7bf84caae3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_copies.py @@ -0,0 +1,1129 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. +""" +Utility that checks whether the copies defined in the library match the original or not. This includes: +- All code commented with `# Copied from` comments, +- The list of models in the main README.md matches the ones in the localized READMEs, +- Files that are registered as full copies of one another in the `FULL_COPIES` constant of this script. + +This also checks the list of models in the README is complete (has all models) and add a line to complete if there is +a model missing. + +Use from the root of the repo with: + +```bash +python utils/check_copies.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`) or + +```bash +python utils/check_copies.py --fix_and_overwrite +``` + +for a check that will fix all inconsistencies automatically (used by `make fix-copies`). +""" + +import argparse +import glob +import os +import re +import subprocess +from collections import OrderedDict +from typing import List, Optional, Tuple, Union + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_copies.py +TRANSFORMERS_PATH = "src/transformers" +MODEL_TEST_PATH = "tests/models" +PATH_TO_DOCS = "docs/source/en" +REPO_PATH = "." + +# Mapping for files that are full copies of others (keys are copies, values the file to keep them up to data with) +FULL_COPIES = { + "examples/tensorflow/question-answering/utils_qa.py": "examples/pytorch/question-answering/utils_qa.py", + "examples/flax/question-answering/utils_qa.py": "examples/pytorch/question-answering/utils_qa.py", +} + + +LOCALIZED_READMES = { + # If the introduction or the conclusion of the list change, the prompts may need to be updated. + "README.md": { + "start_prompt": "🤗 Transformers currently provides the following architectures", + "end_prompt": "1. Want to contribute a new model?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_zh-hans.md": { + "start_prompt": "🤗 Transformers 目前支持如下的架构", + "end_prompt": "1. 想要贡献新的模型?", + "format_model_list": ( + "**[{title}]({model_link})** (来自 {paper_affiliations}) 伴随论文 {paper_title_link} 由 {paper_authors}" + " 发布。{supplements}" + ), + }, + "README_zh-hant.md": { + "start_prompt": "🤗 Transformers 目前支援以下的架構", + "end_prompt": "1. 想要貢獻新的模型?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_ko.md": { + "start_prompt": "🤗 Transformers는 다음 모델들을 제공합니다", + "end_prompt": "1. 새로운 모델을 올리고 싶나요?", + "format_model_list": ( + "**[{title}]({model_link})** ({paper_affiliations} 에서 제공)은 {paper_authors}.{supplements}의" + " {paper_title_link}논문과 함께 발표했습니다." + ), + }, + "README_es.md": { + "start_prompt": "🤗 Transformers actualmente proporciona las siguientes arquitecturas", + "end_prompt": "1. ¿Quieres aportar un nuevo modelo?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_ja.md": { + "start_prompt": "🤗Transformersは現在、以下のアーキテクチャを提供しています", + "end_prompt": "1. 新しいモデルを投稿したいですか?", + "format_model_list": ( + "**[{title}]({model_link})** ({paper_affiliations} から) {paper_authors}.{supplements} から公開された研究論文" + " {paper_title_link}" + ), + }, + "README_hd.md": { + "start_prompt": "🤗 ट्रांसफॉर्मर वर्तमान में निम्नलिखित आर्किटेक्चर का समर्थन करते हैं", + "end_prompt": "1. एक नए मॉडल में योगदान देना चाहते हैं?", + "format_model_list": ( + "**[{title}]({model_link})** ({paper_affiliations} से) {paper_authors}.{supplements} द्वारा" + "अनुसंधान पत्र {paper_title_link} के साथ जारी किया गया" + ), + }, +} + + +# This is to make sure the transformers module imported is the one in the repo. +transformers_module = direct_transformers_import(TRANSFORMERS_PATH) + + +def _is_definition_header_ending_line(line: str) -> bool: + # Helper function. Returns `True` if `line` is the end parenthesis of a class/function definition + return re.search(r"^\s*\)(\s*->.*:|:)\s*$", line) is not None + + +def _should_continue(line: str, indent: str) -> bool: + # Helper function. Returns `True` if `line` is empty, starts with the `indent` or is the end parenthesis of a + # class/function definition + return line.startswith(indent) or len(line.strip()) == 0 or _is_definition_header_ending_line(line) + + +def _sanity_check_splits(splits_1, splits_2, is_class): + """Check the two (inner) block structures of the corresponding code block given by `split_code_into_blocks` match. + + For the case of `class`, they must be of one of the following 3 cases: + + - a single block without name: + + class foo: + a = 1 + + - a consecutive sequence of (1 or more) blocks with name + + class foo: + + def f(x): + return x + + - a block without name, followed by a consecutive sequence of (1 or more) blocks with name + + class foo: + a = 1 + + def f(x): + return x + + def g(x): + return None + + The 2 code snippets that give `splits_1` and `splits_2` have to be in the same case to pass this check, but the + number of blocks with name in the consecutive sequence is not taken into account. + + For the case of `function or method`, we don't require it to be in one of the above 3 cases. However, the structure + of`splits_1` and `splits_2` have to match exactly. In particular, the number of blocks with name in a consecutive + sequence is taken into account. + """ + block_names_1 = [] + block_names_2 = [] + + for block in splits_1[1:]: + if block[0].startswith("_block_without_name_"): + block_names_1.append("block_without_name") + elif not block[0].startswith("_empty_block_") and ( + not is_class or len(block_names_1) == 0 or block_names_1[-1].startswith("block_without_name") + ): + block_names_1.append("block_with_name") + + for block in splits_2[1:]: + if block[0].startswith("_block_without_name_"): + block_names_2.append("block_without_name") + elif not block[0].startswith("_empty_block_") and ( + not is_class or len(block_names_2) == 0 or block_names_2[-1].startswith("block_without_name") + ): + block_names_2.append("block_with_name") + + if is_class: + if block_names_1 not in [ + ["block_without_name"], + ["block_with_name"], + ["block_without_name", "block_with_name"], + ]: + raise ValueError( + "For a class, it must have a specific structure. See the docstring of `_sanity_check_splits` in the file `utils/check_copies.py`" + ) + + if block_names_1 != block_names_2: + raise ValueError("The structures in the 2 code blocks differ.") + + +def find_block_end(lines: List[str], start_index: int, indent: int) -> int: + """ + Find the end of the class/func block starting at `start_index` in a source code (defined by `lines`). + + Args: + lines (`List[str]`): + The source code, represented by a list of lines. + start_index (`int`): + The starting index of the target class/func block. + indent (`int`): + The indent of the class/func body. + + Returns: + `int`: The index of the block's ending line plus by 1 (i.e. exclusive). + """ + indent = " " * indent + # enter the block body + line_index = start_index + 1 + + while line_index < len(lines) and _should_continue(lines[line_index], indent): + line_index += 1 + # Clean up empty lines at the end (if any). + while len(lines[line_index - 1]) <= 1: + line_index -= 1 + + return line_index + + +def split_code_into_blocks( + lines: List[str], start_index: int, end_index: int, indent: int, backtrace: bool = False +) -> List[Tuple[str, int, int]]: + """ + Split the class/func block starting at `start_index` in a source code (defined by `lines`) into *inner blocks*. + + The block's header is included as the first element. The contiguous regions (without empty lines) that are not + inside any inner block are included as blocks. The contiguous regions of empty lines that are not inside any inner + block are also included as (dummy) blocks. + + Args: + lines (`List[str]`): + The source code, represented by a list of lines. + start_index (`int`): + The starting index of the target class/func block. + end_index (`int`): + The ending index of the target class/func block. + indent (`int`): + The indent of the class/func body. + backtrace (`bool`, *optional*, defaults to `False`): + Whether or not to include the lines before the inner class/func block's header (e.g. comments, decorators, + etc.) until an empty line is encountered. + + Returns: + `List[Tuple[str, int, int]]`: A list of elements with the form `(block_name, start_index, end_index)`. + """ + splits = [] + # `indent - 4` is the indent level of the target class/func header + target_block_name = re.search(rf"^{' ' * (indent - 4)}((class|def)\s+\S+)(\(|\:)", lines[start_index]).groups()[0] + + # from now on, the `block` means inner blocks unless explicitly specified + indent_str = " " * indent + block_without_name_idx = 0 + empty_block_idx = 0 + + # Find the lines for the definition header + index = start_index + if "(" in lines[start_index] and "):" not in lines[start_index] in lines[start_index]: + while index < end_index: + if _is_definition_header_ending_line(lines[index]): + break + index += 1 + + # the first line outside the definition header + index += 1 + splits.append((target_block_name, start_index, index)) + + block_start_index, prev_block_end_index = index, index + while index < end_index: + # if found, it will be an inner block + block_found = re.search(rf"^{indent_str}((class|def)\s+\S+)(\(|\:)", lines[index]) + if block_found: + name = block_found.groups()[0] + + block_end_index = find_block_end(lines, index, indent + 4) + + # backtrace to include the lines before the found block's definition header (e.g. comments, decorators, + # etc.) until an empty line is encountered. + block_start_index = index + if index > prev_block_end_index and backtrace: + idx = index - 1 + for idx in range(index - 1, prev_block_end_index - 2, -1): + if not (len(lines[idx].strip()) > 0 and lines[idx].startswith(indent_str)): + break + idx += 1 + if idx < index: + block_start_index = idx + + # between the current found block and the previous found block + if block_start_index > prev_block_end_index: + # give it a dummy name + if len("".join(lines[prev_block_end_index:block_start_index]).strip()) == 0: + prev_block_name = f"_empty_block_{empty_block_idx}" + empty_block_idx += 1 + else: + prev_block_name = f"_block_without_name_{block_without_name_idx}" + block_without_name_idx += 1 + # Add it as a block + splits.append((prev_block_name, prev_block_end_index, block_start_index)) + + # Add the current found block + splits.append((name, block_start_index, block_end_index)) + prev_block_end_index = block_end_index + index = block_end_index - 1 + + index += 1 + + if index > prev_block_end_index: + if len("".join(lines[prev_block_end_index:index]).strip()) == 0: + prev_block_name = f"_empty_block_{empty_block_idx}" + else: + prev_block_name = f"_block_without_name_{block_without_name_idx}" + splits.append((prev_block_name, prev_block_end_index, index)) + + return splits + + +def find_code_in_transformers( + object_name: str, base_path: str = None, return_indices: bool = False +) -> Union[str, Tuple[List[str], int, int]]: + """ + Find and return the source code of an object. + + Args: + object_name (`str`): + The name of the object we want the source code of. + base_path (`str`, *optional*): + The path to the base folder where files are checked. If not set, it will be set to `TRANSFORMERS_PATH`. + return_indices(`bool`, *optional*, defaults to `False`): + If `False`, will only return the code (as a string), otherwise it will also return the whole lines of the + file where the object specified by `object_name` is defined, together the start/end indices of the block in + the file that defines the object. + + Returns: + `Union[str, Tuple[List[str], int, int]]`: If `return_indices=False`, only the source code of the object will be + returned. Otherwise, it also returns the whole lines of the file where the object specified by `object_name` is + defined, together the start/end indices of the block in the file that defines the object. + """ + parts = object_name.split(".") + i = 0 + + # We can't set this as the default value in the argument, otherwise `CopyCheckTester` will fail, as it uses a + # patched temp directory. + if base_path is None: + base_path = TRANSFORMERS_PATH + + # Detail: the `Copied from` statement is originally designed to work with the last part of `TRANSFORMERS_PATH`, + # (which is `transformers`). The same should be applied for `MODEL_TEST_PATH`. However, its last part is `models` + # (to only check and search in it) which is a bit confusing. So we keep the copied statement staring with + # `tests.models.` and change it to `tests` here. + if base_path == MODEL_TEST_PATH: + base_path = "tests" + + # First let's find the module where our object lives. + module = parts[i] + while i < len(parts) and not os.path.isfile(os.path.join(base_path, f"{module}.py")): + i += 1 + if i < len(parts): + module = os.path.join(module, parts[i]) + if i >= len(parts): + raise ValueError( + f"`object_name` should begin with the name of a module of transformers but got {object_name}." + ) + + with open(os.path.join(base_path, f"{module}.py"), "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Now let's find the class / func in the code! + indent = "" + line_index = 0 + for name in parts[i + 1 :]: + while ( + line_index < len(lines) and re.search(rf"^{indent}(class|def)\s+{name}(\(|\:)", lines[line_index]) is None + ): + line_index += 1 + # find the target specified in the current level in `parts` -> increase `indent` so we can search the next + indent += " " + # the index of the first line in the (currently found) block *body* + line_index += 1 + + if line_index >= len(lines): + raise ValueError(f" {object_name} does not match any function or class in {module}.") + + # `indent` is already one level deeper than the (found) class/func block's definition header + + # We found the beginning of the class / func, now let's find the end (when the indent diminishes). + # `start_index` is the index of the class/func block's definition header + start_index = line_index - 1 + end_index = find_block_end(lines, start_index, len(indent)) + + code = "".join(lines[start_index:end_index]) + return (code, (lines, start_index, end_index)) if return_indices else code + + +def replace_code(code: str, replace_pattern: str) -> str: + """Replace `code` by a pattern of the form `with X1->X2,Y1->Y2,Z1->Z2`. + + Args: + code (`str`): The code to be modified. + replace_pattern (`str`): The pattern used to modify `code`. + + Returns: + `str`: The modified code. + """ + if len(replace_pattern) > 0: + patterns = replace_pattern.replace("with", "").split(",") + patterns = [_re_replace_pattern.search(p) for p in patterns] + for pattern in patterns: + if pattern is None: + continue + obj1, obj2, option = pattern.groups() + code = re.sub(obj1, obj2, code) + if option.strip() == "all-casing": + code = re.sub(obj1.lower(), obj2.lower(), code) + code = re.sub(obj1.upper(), obj2.upper(), code) + + return code + + +def find_code_and_splits(object_name: str, base_path: str, buffer: dict = None): + """Find the code of an object (specified by `object_name`) and split it into blocks. + + Args: + object_name (`str`): + The name of the object, e.g. `transformers.models.bert.modeling_bert.BertAttention` or + `tests.models.llama.test_modeling_llama.LlamaModelTest.test_config`. + base_path (`str`): + The path to the base directory within which the search will be performed. It could be either + `TRANSFORMERS_PATH` or `MODEL_TEST_PATH`. + buffer (`dict`, *optional*): + The buffer used to store the previous results in order to speed up the process. + + Returns: + lines (`List[str]`): + The lines of the whole file where the object is defined. + code (`str`): + The object's code. + code_splits (`List[Tuple[str, int, int]]`): + `code` splitted into blocks. See `split_code_into_blocks`. + """ + if buffer is None: + buffer = {} + + if (object_name, base_path) in buffer: + lines, code, code_splits = buffer[(object_name, base_path)] + else: + code, (lines, target_start_index, target_end_index) = find_code_in_transformers( + object_name, base_path=base_path, return_indices=True + ) + indent = get_indent(code) + + # Split the code into blocks + # `indent` is the indent of the class/func definition header, but `code_splits` expects the indent level of the + # block body. + code_splits = split_code_into_blocks( + lines, target_start_index, target_end_index, len(indent) + 4, backtrace=True + ) + buffer[(object_name, base_path)] = lines, code, code_splits + + return lines, code, code_splits + + +_re_copy_warning = re.compile(r"^(\s*)#\s*Copied from\s+transformers\.(\S+\.\S+)\s*($|\S.*$)") +_re_copy_warning_for_test_file = re.compile(r"^(\s*)#\s*Copied from\s+tests\.(\S+\.\S+)\s*($|\S.*$)") +_re_replace_pattern = re.compile(r"^\s*(\S+)->(\S+)(\s+.*|$)") +_re_fill_pattern = re.compile(r"]*>") + + +def get_indent(code: str) -> str: + """ + Find the indent in the first non empty line in a code sample. + + Args: + code (`str`): The code to inspect. + + Returns: + `str`: The indent looked at (as string). + """ + lines = code.split("\n") + idx = 0 + while idx < len(lines) and len(lines[idx]) == 0: + idx += 1 + if idx < len(lines): + return re.search(r"^(\s*)\S", lines[idx]).groups()[0] + return "" + + +def run_ruff(code): + command = ["ruff", "format", "-", "--config", "pyproject.toml", "--silent"] + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + stdout, _ = process.communicate(input=code.encode()) + return stdout.decode() + + +def stylify(code: str) -> str: + """ + Applies the ruff part of our `make style` command to some code. This formats the code using `ruff format`. + As `ruff` does not provide a python api this cannot be done on the fly. + + Args: + code (`str`): The code to format. + + Returns: + `str`: The formatted code. + """ + has_indent = len(get_indent(code)) > 0 + if has_indent: + code = f"class Bla:\n{code}" + formatted_code = run_ruff(code) + return formatted_code[len("class Bla:\n") :] if has_indent else formatted_code + + +def check_codes_match(observed_code: str, theoretical_code: str) -> Optional[int]: + """ + Checks if two version of a code match with the exception of the class/function name. + + Args: + observed_code (`str`): The code found. + theoretical_code (`str`): The code to match. + + Returns: + `Optional[int]`: The index of the first line where there is a difference (if any) and `None` if the codes + match. + """ + observed_code_header = observed_code.split("\n")[0] + theoretical_code_header = theoretical_code.split("\n")[0] + + # Catch the function/class name: it is expected that those do not match. + _re_class_match = re.compile(r"class\s+([^\(:]+)(?:\(|:)") + _re_func_match = re.compile(r"def\s+([^\(]+)\(") + for re_pattern in [_re_class_match, _re_func_match]: + if re_pattern.match(observed_code_header) is not None: + observed_obj_name = re_pattern.search(observed_code_header).groups()[0] + theoretical_name = re_pattern.search(theoretical_code_header).groups()[0] + theoretical_code_header = theoretical_code_header.replace(theoretical_name, observed_obj_name) + + # Find the first diff. Line 0 is special since we need to compare with the function/class names ignored. + diff_index = 0 + if theoretical_code_header != observed_code_header: + return 0 + + diff_index = 1 + for observed_line, theoretical_line in zip(observed_code.split("\n")[1:], theoretical_code.split("\n")[1:]): + if observed_line != theoretical_line: + return diff_index + diff_index += 1 + + +def is_copy_consistent(filename: str, overwrite: bool = False, buffer: dict = None) -> Optional[List[Tuple[str, int]]]: + """ + Check if the code commented as a copy in a file matches the original. + + Args: + filename (`str`): + The name of the file to check. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the copies when they don't match. + buffer (`dict`, *optional*): + The buffer used to store the previous results in order to speed up the process. + + Returns: + `Optional[List[Tuple[str, int]]]`: If `overwrite=False`, returns the list of differences as tuples `(str, int)` + with the name of the object having a diff and the line number where theere is the first diff. + """ + base_path = TRANSFORMERS_PATH if not filename.startswith("tests") else MODEL_TEST_PATH + + with open(filename, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + diffs = [] + line_index = 0 + # Not a for loop cause `lines` is going to change (if `overwrite=True`). + while line_index < len(lines): + search_re = _re_copy_warning + if filename.startswith("tests"): + search_re = _re_copy_warning_for_test_file + + search = search_re.search(lines[line_index]) + if search is None: + line_index += 1 + continue + + # There is some copied code here, let's retrieve the original. + indent, object_name, replace_pattern = search.groups() + + # Find the file lines, the object's code, and its blocks + target_lines, theoretical_code, theoretical_code_splits = find_code_and_splits( + object_name, base_path, buffer=buffer + ) + + # code replaced by the patterns + theoretical_code_blocks = OrderedDict() + for name, start, end in theoretical_code_splits: + name = replace_code(name, replace_pattern) + code = "".join(target_lines[start:end]) + code = replace_code(code, replace_pattern) + theoretical_code_blocks[name] = code + + theoretical_indent = get_indent(theoretical_code) + + # `start_index` is the index of the first line (the definition header) after `# Copied from`. + # (`indent != theoretical_indent` doesn't seem to occur so far, not sure what this case is for.) + start_index = line_index + 1 if indent == theoretical_indent else line_index + # enter the block body + line_index = start_index + 1 + + subcode = "\n".join(theoretical_code.split("\n")[1:]) + indent = get_indent(subcode) + # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. + # We can't call `find_block_end` directly as there is sth. special `# End copy"` here. + should_continue = True + while line_index < len(lines) and should_continue: + line_index += 1 + if line_index >= len(lines): + break + line = lines[line_index] + # There is a special pattern `# End copy` to stop early. It's not documented cause it shouldn't really be + # used. + should_continue = _should_continue(line, indent) and re.search(f"^{indent}# End copy", line) is None + # `line_index` is outside the block + # Clean up empty lines at the end (if any). + while len(lines[line_index - 1]) <= 1: + line_index -= 1 + + # Split the observed code into blocks + observed_code_splits = split_code_into_blocks(lines, start_index, line_index, len(indent), backtrace=True) + + is_class = lines[start_index].startswith(f"{' ' * (len(indent) - 4)}class ") + # sanity check + _sanity_check_splits(theoretical_code_splits, observed_code_splits, is_class=is_class) + + # observed code in a structured way (a dict mapping block names to blocks' code) + observed_code_blocks = OrderedDict() + for name, start, end in observed_code_splits: + code = "".join(lines[start:end]) + observed_code_blocks[name] = code + + # Below, we change some names in `theoretical_code_blocks` and `observed_code_blocks`. These mappings map the + # original names to the modified names: this is used to restore the original order of the code blocks. + name_mappings_1 = {k: k for k in theoretical_code_blocks.keys()} + name_mappings_2 = {k: k for k in observed_code_blocks.keys()} + + # Update code blocks' name and content: + # If `"# Ignore copy"` is found in a block of the observed code: + # 1. if it's a block only in the observed code --> add it to the theoretical code. + # 2. if it's also in the theoretical code () --> put its content (body) to the corresponding block under the + # same name in the theoretical code. + # In both cases, we change the name to have a prefix `_ignored_` so we know if we can discard them during the + # comparison. + ignored_existing_block_index = 0 + ignored_new_block_index = 0 + for name in list(observed_code_blocks.keys()): + code = observed_code_blocks[name] + if "# Ignore copy" in code: + if name in theoretical_code_blocks: + # in the target --> just copy the content + del theoretical_code_blocks[name] + theoretical_code_blocks[f"_ignored_existing_block_{ignored_existing_block_index}"] = code + name_mappings_1[name] = f"_ignored_existing_block_{ignored_existing_block_index}" + + del observed_code_blocks[name] + observed_code_blocks[f"_ignored_existing_block_{ignored_existing_block_index}"] = code + name_mappings_2[name] = f"_ignored_existing_block_{ignored_existing_block_index}" + ignored_existing_block_index += 1 + else: + # not in the target --> add it + theoretical_code_blocks[f"_ignored_new_block_{ignored_new_block_index}"] = code + name_mappings_1[ + f"_ignored_new_block_{ignored_new_block_index}" + ] = f"_ignored_new_block_{ignored_new_block_index}" + + del observed_code_blocks[name] + observed_code_blocks[f"_ignored_new_block_{ignored_new_block_index}"] = code + name_mappings_2[name] = f"_ignored_new_block_{ignored_new_block_index}" + ignored_new_block_index += 1 + + # Respect the original block order: + # 1. in `theoretical_code_blocks`: the new blocks will follow the existing ones + # 2. in `observed_code_blocks`: the original order are kept with names modified potentially. This is necessary + # to compute the correct `diff_index` if `overwrite=True` and there is a diff. + theoretical_code_blocks = { + name_mappings_1[orig_name]: theoretical_code_blocks[name_mappings_1[orig_name]] + for orig_name in name_mappings_1 + } + observed_code_blocks = { + name_mappings_2[orig_name]: observed_code_blocks[name_mappings_2[orig_name]] + for orig_name in name_mappings_2 + } + + # Ignore the blocks specified to be ignored. This is the version used to check if there is a mismatch + theoretical_code_blocks_clean = { + k: v + for k, v in theoretical_code_blocks.items() + if not (k.startswith(("_ignored_existing_block_", "_ignored_new_block_"))) + } + theoretical_code = "".join(list(theoretical_code_blocks_clean.values())) + + # stylify `theoretical_code` before compare (this is needed only when `replace_pattern` is not empty) + if replace_pattern: + theoretical_code = stylify(theoretical_code) + # Remove `\n\n` in `theoretical_code` before compare (so no empty line) + while "\n\n" in theoretical_code: + theoretical_code = theoretical_code.replace("\n\n", "\n") + + # Compute `observed_code` where we don't include any empty line + keep track the line index between the + # original/processed `observed_code` so we can have the correct `diff_index`. + idx_to_orig_idx_mapping_for_observed_code_lines = {} + idx = -1 + orig_idx = -1 + observed_code = "" + for name, code in observed_code_blocks.items(): + if code.endswith("\n"): + code = code[:-1] + for code_line in code.split("\n"): + orig_idx += 1 + if code_line.strip() and not name.startswith(("_ignored_existing_block_", "_ignored_new_block_")): + idx += 1 + observed_code += code_line + "\n" + idx_to_orig_idx_mapping_for_observed_code_lines[idx] = orig_idx + + # Test for a diff and act accordingly. + diff_index = check_codes_match(observed_code, theoretical_code) + if diff_index is not None: + # switch to the index in the original `observed_code` (i.e. before removing empty lines) + diff_index = idx_to_orig_idx_mapping_for_observed_code_lines[diff_index] + diffs.append([object_name, diff_index + start_index + 1]) + if overwrite: + # `theoretical_code_to_write` is a single string but may have several lines. + theoretical_code_to_write = stylify("".join(list(theoretical_code_blocks.values()))) + lines = lines[:start_index] + [theoretical_code_to_write] + lines[line_index:] + # Here we treat it as a single entry in `lines`. + line_index = start_index + 1 + + if overwrite and len(diffs) > 0: + # Warn the user a file has been modified. + print(f"Detected changes, rewriting {filename}.") + with open(filename, "w", encoding="utf-8", newline="\n") as f: + f.writelines(lines) + return diffs + + +def check_copies(overwrite: bool = False, file: str = None): + """ + Check every file is copy-consistent with the original. Also check the model list in the main README and other + READMEs are consistent. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the copies when they don't match. + file (`bool`, *optional*): + The path to a specific file to check and/or fix. + """ + buffer = {} + + if file is None: + all_files = glob.glob(os.path.join(TRANSFORMERS_PATH, "**/*.py"), recursive=True) + all_test_files = glob.glob(os.path.join(MODEL_TEST_PATH, "**/*.py"), recursive=True) + all_files = list(all_files) + list(all_test_files) + else: + all_files = [file] + + diffs = [] + for filename in all_files: + new_diffs = is_copy_consistent(filename, overwrite, buffer) + diffs += [f"- {filename}: copy does not match {d[0]} at line {d[1]}" for d in new_diffs] + if not overwrite and len(diffs) > 0: + diff = "\n".join(diffs) + raise Exception( + "Found the following copy inconsistencies:\n" + + diff + + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." + ) + check_model_list_copy(overwrite=overwrite) + + +def check_full_copies(overwrite: bool = False): + """ + Check the files that are full copies of others (as indicated in `FULL_COPIES`) are copy-consistent. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the copies when they don't match. + """ + diffs = [] + for target, source in FULL_COPIES.items(): + with open(source, "r", encoding="utf-8") as f: + source_code = f.read() + with open(target, "r", encoding="utf-8") as f: + target_code = f.read() + if source_code != target_code: + if overwrite: + with open(target, "w", encoding="utf-8") as f: + print(f"Replacing the content of {target} by the one of {source}.") + f.write(source_code) + else: + diffs.append(f"- {target}: copy does not match {source}.") + + if not overwrite and len(diffs) > 0: + diff = "\n".join(diffs) + raise Exception( + "Found the following copy inconsistencies:\n" + + diff + + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." + ) + + +def get_model_list(filename: str, start_prompt: str, end_prompt: str) -> str: + """ + Extracts the model list from a README. + + Args: + filename (`str`): The name of the README file to check. + start_prompt (`str`): The string to look for that introduces the model list. + end_prompt (`str`): The string to look for that ends the model list. + + Returns: + `str`: The model list. + """ + with open(os.path.join(REPO_PATH, filename), "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + # Find the start of the list. + start_index = 0 + while not lines[start_index].startswith(start_prompt): + start_index += 1 + start_index += 1 + + result = [] + current_line = "" + end_index = start_index + + # Keep going until the end of the list. + while not lines[end_index].startswith(end_prompt): + if lines[end_index].startswith("1."): + if len(current_line) > 1: + result.append(current_line) + current_line = lines[end_index] + elif len(lines[end_index]) > 1: + current_line = f"{current_line[:-1]} {lines[end_index].lstrip()}" + end_index += 1 + if len(current_line) > 1: + result.append(current_line) + + return "".join(result) + + +def convert_to_localized_md(model_list: str, localized_model_list: str, format_str: str) -> Tuple[bool, str]: + """ + Compare the model list from the main README to the one in a localized README. + + Args: + model_list (`str`): The model list in the main README. + localized_model_list (`str`): The model list in one of the localized README. + format_str (`str`): + The template for a model entry in the localized README (look at the `format_model_list` in the entries of + `LOCALIZED_READMES` for examples). + + Returns: + `Tuple[bool, str]`: A tuple where the first value indicates if the READMEs match or not, and the second value + is the correct localized README. + """ + + def _rep(match): + title, model_link, paper_affiliations, paper_title_link, paper_authors, supplements = match.groups() + return format_str.format( + title=title, + model_link=model_link, + paper_affiliations=paper_affiliations, + paper_title_link=paper_title_link, + paper_authors=paper_authors, + supplements=" " + supplements.strip() if len(supplements) != 0 else "", + ) + + # This regex captures metadata from an English model description, including model title, model link, + # affiliations of the paper, title of the paper, authors of the paper, and supplemental data (see DistilBERT for + # example). + _re_capture_meta = re.compile( + r"\*\*\[([^\]]*)\]\(([^\)]*)\)\*\* \(from ([^)]*)\)[^\[]*([^\)]*\)).*?by (.*?[A-Za-z\*]{2,}?)\. (.*)$" + ) + # This regex is used to synchronize link. + _re_capture_title_link = re.compile(r"\*\*\[([^\]]*)\]\(([^\)]*)\)\*\*") + + if len(localized_model_list) == 0: + localized_model_index = {} + else: + try: + localized_model_index = { + re.search(r"\*\*\[([^\]]*)", line).groups()[0]: line + for line in localized_model_list.strip().split("\n") + } + except AttributeError: + raise AttributeError("A model name in localized READMEs cannot be recognized.") + + model_keys = [re.search(r"\*\*\[([^\]]*)", line).groups()[0] for line in model_list.strip().split("\n")] + + # We exclude keys in localized README not in the main one. + readmes_match = not any(k not in model_keys for k in localized_model_index) + localized_model_index = {k: v for k, v in localized_model_index.items() if k in model_keys} + + for model in model_list.strip().split("\n"): + title, model_link = _re_capture_title_link.search(model).groups() + if title not in localized_model_index: + readmes_match = False + # Add an anchor white space behind a model description string for regex. + # If metadata cannot be captured, the English version will be directly copied. + localized_model_index[title] = _re_capture_meta.sub(_rep, model + " ") + elif _re_fill_pattern.search(localized_model_index[title]) is not None: + update = _re_capture_meta.sub(_rep, model + " ") + if update != localized_model_index[title]: + readmes_match = False + localized_model_index[title] = update + else: + # Synchronize link + localized_model_index[title] = _re_capture_title_link.sub( + f"**[{title}]({model_link})**", localized_model_index[title], count=1 + ) + + sorted_index = sorted(localized_model_index.items(), key=lambda x: x[0].lower()) + + return readmes_match, "\n".join((x[1] for x in sorted_index)) + "\n" + + +def _find_text_in_file(filename: str, start_prompt: str, end_prompt: str) -> Tuple[str, int, int, List[str]]: + """ + Find the text in a file between two prompts. + + Args: + filename (`str`): The name of the file to look into. + start_prompt (`str`): The string to look for that introduces the content looked for. + end_prompt (`str`): The string to look for that ends the content looked for. + + Returns: + Tuple[str, int, int, List[str]]: The content between the two prompts, the index of the start line in the + original file, the index of the end line in the original file and the list of lines of that file. + """ + with open(filename, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + # Find the start prompt. + start_index = 0 + while not lines[start_index].startswith(start_prompt): + start_index += 1 + start_index += 1 + + end_index = start_index + while not lines[end_index].startswith(end_prompt): + end_index += 1 + end_index -= 1 + + while len(lines[start_index]) <= 1: + start_index += 1 + while len(lines[end_index]) <= 1: + end_index -= 1 + end_index += 1 + return "".join(lines[start_index:end_index]), start_index, end_index, lines + + +def check_model_list_copy(overwrite: bool = False): + """ + Check the model lists in the README is consistent with the ones in the other READMES and also with `index.nmd`. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the copies when they don't match. + """ + # Fix potential doc links in the README + with open(os.path.join(REPO_PATH, "README.md"), "r", encoding="utf-8", newline="\n") as f: + readme = f.read() + new_readme = readme.replace("https://huggingface.co/transformers", "https://huggingface.co/docs/transformers") + new_readme = new_readme.replace( + "https://huggingface.co/docs/main/transformers", "https://huggingface.co/docs/transformers/main" + ) + if new_readme != readme: + if overwrite: + with open(os.path.join(REPO_PATH, "README.md"), "w", encoding="utf-8", newline="\n") as f: + f.write(new_readme) + else: + raise ValueError( + "The main README contains wrong links to the documentation of Transformers. Run `make fix-copies` to " + "automatically fix them." + ) + + md_list = get_model_list( + filename="README.md", + start_prompt=LOCALIZED_READMES["README.md"]["start_prompt"], + end_prompt=LOCALIZED_READMES["README.md"]["end_prompt"], + ) + + # Build the converted Markdown. + converted_md_lists = [] + for filename, value in LOCALIZED_READMES.items(): + _start_prompt = value["start_prompt"] + _end_prompt = value["end_prompt"] + _format_model_list = value["format_model_list"] + + localized_md_list = get_model_list(filename, _start_prompt, _end_prompt) + readmes_match, converted_md_list = convert_to_localized_md(md_list, localized_md_list, _format_model_list) + + converted_md_lists.append((filename, readmes_match, converted_md_list, _start_prompt, _end_prompt)) + + # Compare the converted Markdowns + for converted_md_list in converted_md_lists: + filename, readmes_match, converted_md, _start_prompt, _end_prompt = converted_md_list + + if filename == "README.md": + continue + if overwrite: + _, start_index, end_index, lines = _find_text_in_file( + filename=os.path.join(REPO_PATH, filename), start_prompt=_start_prompt, end_prompt=_end_prompt + ) + with open(os.path.join(REPO_PATH, filename), "w", encoding="utf-8", newline="\n") as f: + f.writelines(lines[:start_index] + [converted_md] + lines[end_index:]) + elif not readmes_match: + raise ValueError( + f"The model list in the README changed and the list in `{filename}` has not been updated. Run " + "`make fix-copies` to fix this." + ) + + +# Map a model name with the name it has in the README for the check_readme check +SPECIAL_MODEL_NAMES = { + "Bert Generation": "BERT For Sequence Generation", + "BigBird": "BigBird-RoBERTa", + "Data2VecAudio": "Data2Vec", + "Data2VecText": "Data2Vec", + "Data2VecVision": "Data2Vec", + "DonutSwin": "Swin Transformer", + "Marian": "MarianMT", + "MaskFormerSwin": "Swin Transformer", + "OpenAI GPT-2": "GPT-2", + "OpenAI GPT": "GPT", + "Perceiver": "Perceiver IO", + "SAM": "Segment Anything", + "ViT": "Vision Transformer (ViT)", +} + +# Update this list with the models that shouldn't be in the README. This only concerns modular models or those who do +# not have an associated paper. +MODELS_NOT_IN_README = [ + "BertJapanese", + "Encoder decoder", + "FairSeq Machine-Translation", + "HerBERT", + "RetriBERT", + "Speech Encoder decoder", + "Speech2Text", + "Speech2Text2", + "TimmBackbone", + "Vision Encoder decoder", + "VisionTextDualEncoder", + "CLIPVisionModel", +] + +# Template for new entries to add in the main README when we have missing models. +README_TEMPLATE = ( + "1. **[{model_name}](https://huggingface.co/docs/main/transformers/model_doc/{model_type})** (from " + ") released with the paper []() by ." +) + + +def check_readme(overwrite: bool = False): + """ + Check if the main README contains all the models in the library or not. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to add an entry for the missing models using `README_TEMPLATE`. + """ + info = LOCALIZED_READMES["README.md"] + models, start_index, end_index, lines = _find_text_in_file( + os.path.join(REPO_PATH, "README.md"), + info["start_prompt"], + info["end_prompt"], + ) + models_in_readme = [re.search(r"\*\*\[([^\]]*)", line).groups()[0] for line in models.strip().split("\n")] + + model_names_mapping = transformers_module.models.auto.configuration_auto.MODEL_NAMES_MAPPING + absents = [ + (key, name) + for key, name in model_names_mapping.items() + if SPECIAL_MODEL_NAMES.get(name, name) not in models_in_readme + ] + # Remove exceptions + absents = [(key, name) for key, name in absents if name not in MODELS_NOT_IN_README] + if len(absents) > 0 and not overwrite: + print(absents) + raise ValueError( + "The main README doesn't contain all models, run `make fix-copies` to fill it with the missing model(s)" + " then complete the generated entries.\nIf the model is not supposed to be in the main README, add it to" + " the list `MODELS_NOT_IN_README` in utils/check_copies.py.\nIf it has a different name in the repo than" + " in the README, map the correspondence in `SPECIAL_MODEL_NAMES` in utils/check_copies.py." + ) + + new_models = [README_TEMPLATE.format(model_name=name, model_type=key) for key, name in absents] + + all_models = models.strip().split("\n") + new_models + all_models = sorted(all_models, key=lambda x: re.search(r"\*\*\[([^\]]*)", x).groups()[0].lower()) + all_models = "\n".join(all_models) + "\n" + + if all_models != models: + if overwrite: + print("Fixing the main README.") + with open(os.path.join(REPO_PATH, "README.md"), "w", encoding="utf-8", newline="\n") as f: + f.writelines(lines[:start_index] + [all_models] + lines[end_index:]) + else: + raise ValueError("The main README model list is not properly sorted. Run `make fix-copies` to fix this.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--file", type=str, default=None, help="A specific file to check and/or fix") + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + check_readme(args.fix_and_overwrite) + check_copies(args.fix_and_overwrite, args.file) + check_full_copies(args.fix_and_overwrite) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_doc_toc.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_doc_toc.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbff5e0b648ee179298711ae223639e33906d3a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_doc_toc.py @@ -0,0 +1,135 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# 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. +""" +This script is responsible for cleaning the model section of the table of content by removing duplicates and sorting +the entries in alphabetical order. + +Usage (from the root of the repo): + +Check that the table of content is properly sorted (used in `make quality`): + +```bash +python utils/check_doc_toc.py +``` + +Auto-sort the table of content if it is not properly sorted (used in `make style`): + +```bash +python utils/check_doc_toc.py --fix_and_overwrite +``` +""" + + +import argparse +from collections import defaultdict +from typing import List + +import yaml + + +PATH_TO_TOC = "docs/source/en/_toctree.yml" + + +def clean_model_doc_toc(model_doc: List[dict]) -> List[dict]: + """ + Cleans a section of the table of content of the model documentation (one specific modality) by removing duplicates + and sorting models alphabetically. + + Args: + model_doc (`List[dict]`): + The list of dictionaries extracted from the `_toctree.yml` file for this specific modality. + + Returns: + `List[dict]`: List of dictionaries like the input, but cleaned up and sorted. + """ + counts = defaultdict(int) + for doc in model_doc: + counts[doc["local"]] += 1 + duplicates = [key for key, value in counts.items() if value > 1] + + new_doc = [] + for duplicate_key in duplicates: + titles = list({doc["title"] for doc in model_doc if doc["local"] == duplicate_key}) + if len(titles) > 1: + raise ValueError( + f"{duplicate_key} is present several times in the documentation table of content at " + "`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the " + "others." + ) + # Only add this once + new_doc.append({"local": duplicate_key, "title": titles[0]}) + + # Add none duplicate-keys + new_doc.extend([doc for doc in model_doc if counts[doc["local"]] == 1]) + + # Sort + return sorted(new_doc, key=lambda s: s["title"].lower()) + + +def check_model_doc(overwrite: bool = False): + """ + Check that the content of the table of content in `_toctree.yml` is clean (no duplicates and sorted for the model + API doc) and potentially auto-cleans it. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether to just check if the TOC is clean or to auto-clean it (when `overwrite=True`). + """ + with open(PATH_TO_TOC, encoding="utf-8") as f: + content = yaml.safe_load(f.read()) + + # Get to the API doc + api_idx = 0 + while content[api_idx]["title"] != "API": + api_idx += 1 + api_doc = content[api_idx]["sections"] + + # Then to the model doc + model_idx = 0 + while api_doc[model_idx]["title"] != "Models": + model_idx += 1 + + model_doc = api_doc[model_idx]["sections"] + + # Extract the modalities and clean them one by one. + modalities_docs = [(idx, section) for idx, section in enumerate(model_doc) if "sections" in section] + diff = False + for idx, modality_doc in modalities_docs: + old_modality_doc = modality_doc["sections"] + new_modality_doc = clean_model_doc_toc(old_modality_doc) + + if old_modality_doc != new_modality_doc: + diff = True + if overwrite: + model_doc[idx]["sections"] = new_modality_doc + + if diff: + if overwrite: + api_doc[model_idx]["sections"] = model_doc + content[api_idx]["sections"] = api_doc + with open(PATH_TO_TOC, "w", encoding="utf-8") as f: + f.write(yaml.dump(content, allow_unicode=True)) + else: + raise ValueError( + "The model doc part of the table of content is not properly sorted, run `make style` to fix this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + check_model_doc(args.fix_and_overwrite) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_docstrings.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a1f0fde1c0cfe9feb924051b41d87744f50a6b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_docstrings.py @@ -0,0 +1,1235 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +""" +Utility that checks all docstrings of public objects have an argument section matching their signature. + +Use from the root of the repo with: + +```bash +python utils/check_docstrings.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`). + +To auto-fix issues run: + +```bash +python utils/check_docstrings.py --fix_and_overwrite +``` + +which is used by `make fix-copies` (note that this fills what it cans, you might have to manually fill information +like argument descriptions). +""" +import argparse +import ast +import enum +import inspect +import operator as op +import re +from pathlib import Path +from typing import Any, Optional, Tuple, Union + +from check_repo import ignore_undocumented + +from transformers.utils import direct_transformers_import + + +PATH_TO_TRANSFORMERS = Path("src").resolve() / "transformers" + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + +OPTIONAL_KEYWORD = "*optional*" +# Re pattern that catches args blocks in docstrings (with all variation around the name supported). +_re_args = re.compile(r"^\s*(Args?|Arguments?|Attributes?|Params?|Parameters?):\s*$") +# Re pattern that parses the start of an arg block: catches () in those lines. +_re_parse_arg = re.compile(r"^(\s*)(\S+)\s+\((.+)\)(?:\:|$)") +# Re pattern that parses the end of a description of an arg (catches the default in *optional*, defaults to xxx). +_re_parse_description = re.compile(r"\*optional\*, defaults to (.*)$") + + +# This is a temporary list of objects to ignore while we progressively fix them. Do not add anything here, fix the +# docstrings instead. If formatting should be ignored for the docstring, you can put a comment # no-format on the +# line before the docstring. +OBJECTS_TO_IGNORE = [ + # Deprecated + "InputExample", + "InputFeatures", + # Signature is *args/**kwargs + # "PretrainedConfig", #ignored but could be fixed + # "GenerationConfig", #ignored but could be fixed + "TFSequenceSummary", + "TFBertTokenizer", + "TFGPT2Tokenizer", + # Missing arguments in the docstring + "ASTFeatureExtractor", + "AlbertModel", + "AlbertTokenizerFast", + "AlignTextModel", + "AlignVisionConfig", + "AudioClassificationPipeline", + "AutoformerConfig", + "AutomaticSpeechRecognitionPipeline", + "AzureOpenAiAgent", + "BarkCoarseConfig", + "BarkConfig", + "BarkFineConfig", + "BarkSemanticConfig", + "BartConfig", + "BartTokenizerFast", + "BarthezTokenizerFast", + "BeitModel", + "BertConfig", + "BertJapaneseTokenizer", + "BertModel", + "BertTokenizerFast", + "BigBirdConfig", + "BigBirdForQuestionAnswering", + "BigBirdModel", + "BigBirdPegasusConfig", + "BigBirdTokenizerFast", + "BitImageProcessor", + "BlenderbotConfig", + "BlenderbotSmallConfig", + "BlenderbotSmallTokenizerFast", + "BlenderbotTokenizerFast", + "Blip2QFormerConfig", + "Blip2VisionConfig", + "BlipTextConfig", + "BlipVisionConfig", + "BloomConfig", + "BloomTokenizerFast", + "BridgeTowerTextConfig", + "BridgeTowerVisionConfig", + "BrosModel", + "CamembertConfig", + "CamembertModel", + "CamembertTokenizerFast", + "CanineModel", + "CanineTokenizer", + "ChineseCLIPTextModel", + "ClapTextConfig", + "ConditionalDetrConfig", + "ConditionalDetrImageProcessor", + "ConvBertConfig", + "ConvBertTokenizerFast", + "ConvNextConfig", + "ConvNextV2Config", + "ConversationalPipeline", + "CpmAntTokenizer", + "CvtConfig", + "CvtModel", + "DeiTImageProcessor", + "DPRReaderTokenizer", + "DPRReaderTokenizerFast", + "DPTModel", + "Data2VecAudioConfig", + "Data2VecTextConfig", + "Data2VecTextModel", + "Data2VecVisionModel", + "DataCollatorForLanguageModeling", + "DebertaConfig", + "DebertaV2Config", + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast", + "DecisionTransformerConfig", + "DeformableDetrConfig", + "DeformableDetrImageProcessor", + "DeiTModel", + "DepthEstimationPipeline", + "DetaConfig", + "DetaImageProcessor", + "DetrConfig", + "DetrImageProcessor", + "DinatModel", + "DistilBertConfig", + "DistilBertTokenizerFast", + "DocumentQuestionAnsweringPipeline", + "DonutSwinModel", + "EarlyStoppingCallback", + "EfficientFormerConfig", + "EfficientFormerImageProcessor", + "EfficientNetConfig", + "ElectraConfig", + "ElectraTokenizerFast", + "EncoderDecoderModel", + "EncoderRepetitionPenaltyLogitsProcessor", + "ErnieConfig", + "ErnieMConfig", + "ErnieMModel", + "ErnieModel", + "ErnieMTokenizer", + "EsmConfig", + "EsmModel", + "FlaxAlbertForMaskedLM", + "FlaxAlbertForMultipleChoice", + "FlaxAlbertForPreTraining", + "FlaxAlbertForQuestionAnswering", + "FlaxAlbertForSequenceClassification", + "FlaxAlbertForTokenClassification", + "FlaxAlbertModel", + "FlaxBartForCausalLM", + "FlaxBartForConditionalGeneration", + "FlaxBartForQuestionAnswering", + "FlaxBartForSequenceClassification", + "FlaxBartModel", + "FlaxBeitForImageClassification", + "FlaxBeitForMaskedImageModeling", + "FlaxBeitModel", + "FlaxBertForCausalLM", + "FlaxBertForMaskedLM", + "FlaxBertForMultipleChoice", + "FlaxBertForNextSentencePrediction", + "FlaxBertForPreTraining", + "FlaxBertForQuestionAnswering", + "FlaxBertForSequenceClassification", + "FlaxBertForTokenClassification", + "FlaxBertModel", + "FlaxBigBirdForCausalLM", + "FlaxBigBirdForMaskedLM", + "FlaxBigBirdForMultipleChoice", + "FlaxBigBirdForPreTraining", + "FlaxBigBirdForQuestionAnswering", + "FlaxBigBirdForSequenceClassification", + "FlaxBigBirdForTokenClassification", + "FlaxBigBirdModel", + "FlaxBlenderbotForConditionalGeneration", + "FlaxBlenderbotModel", + "FlaxBlenderbotSmallForConditionalGeneration", + "FlaxBlenderbotSmallModel", + "FlaxBloomForCausalLM", + "FlaxBloomModel", + "FlaxCLIPModel", + "FlaxDistilBertForMaskedLM", + "FlaxDistilBertForMultipleChoice", + "FlaxDistilBertForQuestionAnswering", + "FlaxDistilBertForSequenceClassification", + "FlaxDistilBertForTokenClassification", + "FlaxDistilBertModel", + "FlaxElectraForCausalLM", + "FlaxElectraForMaskedLM", + "FlaxElectraForMultipleChoice", + "FlaxElectraForPreTraining", + "FlaxElectraForQuestionAnswering", + "FlaxElectraForSequenceClassification", + "FlaxElectraForTokenClassification", + "FlaxElectraModel", + "FlaxEncoderDecoderModel", + "FlaxGPT2LMHeadModel", + "FlaxGPT2Model", + "FlaxGPTJForCausalLM", + "FlaxGPTJModel", + "FlaxGPTNeoForCausalLM", + "FlaxGPTNeoModel", + "FlaxLlamaForCausalLM", + "FlaxLlamaModel", + "FlaxMBartForConditionalGeneration", + "FlaxMBartForQuestionAnswering", + "FlaxMBartForSequenceClassification", + "FlaxMBartModel", + "FlaxMarianMTModel", + "FlaxMarianModel", + "FlaxOPTForCausalLM", + "FlaxPegasusForConditionalGeneration", + "FlaxPegasusModel", + "FlaxRegNetForImageClassification", + "FlaxRegNetModel", + "FlaxResNetForImageClassification", + "FlaxResNetModel", + "FlaxRoFormerForMaskedLM", + "FlaxRoFormerForMultipleChoice", + "FlaxRoFormerForQuestionAnswering", + "FlaxRoFormerForSequenceClassification", + "FlaxRoFormerForTokenClassification", + "FlaxRoFormerModel", + "FlaxRobertaForCausalLM", + "FlaxRobertaForMaskedLM", + "FlaxRobertaForMultipleChoice", + "FlaxRobertaForQuestionAnswering", + "FlaxRobertaForSequenceClassification", + "FlaxRobertaForTokenClassification", + "FlaxRobertaModel", + "FlaxRobertaPreLayerNormForCausalLM", + "FlaxRobertaPreLayerNormForMaskedLM", + "FlaxRobertaPreLayerNormForMultipleChoice", + "FlaxRobertaPreLayerNormForQuestionAnswering", + "FlaxRobertaPreLayerNormForSequenceClassification", + "FlaxRobertaPreLayerNormForTokenClassification", + "FlaxRobertaPreLayerNormModel", + "FlaxSpeechEncoderDecoderModel", + "FlaxViTForImageClassification", + "FlaxViTModel", + "FlaxVisionEncoderDecoderModel", + "FlaxVisionTextDualEncoderModel", + "FlaxWav2Vec2ForCTC", + "FlaxWav2Vec2ForPreTraining", + "FlaxWav2Vec2Model", + "FlaxWhisperForAudioClassification", + "FlaxWhisperForConditionalGeneration", + "FlaxWhisperModel", + "FlaxWhisperTimeStampLogitsProcessor", + "FlaxXGLMForCausalLM", + "FlaxXGLMModel", + "FlaxXLMRobertaForCausalLM", + "FlaxXLMRobertaForMaskedLM", + "FlaxXLMRobertaForMultipleChoice", + "FlaxXLMRobertaForQuestionAnswering", + "FlaxXLMRobertaForSequenceClassification", + "FlaxXLMRobertaForTokenClassification", + "FlaxXLMRobertaModel", + "FNetConfig", + "FNetModel", + "FNetTokenizerFast", + "FSMTConfig", + "FeatureExtractionPipeline", + "FillMaskPipeline", + "FlaubertConfig", + "FlavaConfig", + "FlavaForPreTraining", + "FlavaImageModel", + "FlavaImageProcessor", + "FlavaMultimodalModel", + "FlavaTextConfig", + "FlavaTextModel", + "FocalNetModel", + "FunnelTokenizerFast", + "GPTBigCodeConfig", + "GPTJConfig", + "GPTNeoXConfig", + "GPTNeoXJapaneseConfig", + "GPTNeoXTokenizerFast", + "GPTSanJapaneseConfig", + "GitConfig", + "GitVisionConfig", + "GraphormerConfig", + "GroupViTTextConfig", + "GroupViTVisionConfig", + "HerbertTokenizerFast", + "HubertConfig", + "HubertForCTC", + "IBertConfig", + "IBertModel", + "IdeficsConfig", + "IdeficsProcessor", + "ImageClassificationPipeline", + "ImageGPTConfig", + "ImageSegmentationPipeline", + "ImageToImagePipeline", + "ImageToTextPipeline", + "InformerConfig", + "InstructBlipQFormerConfig", + "JukeboxPriorConfig", + "JukeboxTokenizer", + "LEDConfig", + "LEDTokenizerFast", + "LayoutLMForQuestionAnswering", + "LayoutLMTokenizerFast", + "LayoutLMv2Config", + "LayoutLMv2ForQuestionAnswering", + "LayoutLMv2TokenizerFast", + "LayoutLMv3Config", + "LayoutLMv3ImageProcessor", + "LayoutLMv3TokenizerFast", + "LayoutXLMTokenizerFast", + "LevitConfig", + "LiltConfig", + "LiltModel", + "LongT5Config", + "LongformerConfig", + "LongformerModel", + "LongformerTokenizerFast", + "LukeModel", + "LukeTokenizer", + "LxmertTokenizerFast", + "M2M100Config", + "M2M100Tokenizer", + "MarkupLMProcessor", + "MaskGenerationPipeline", + "MBart50TokenizerFast", + "MBartConfig", + "MCTCTFeatureExtractor", + "MPNetConfig", + "MPNetModel", + "MPNetTokenizerFast", + "MT5Config", + "MT5TokenizerFast", + "MarianConfig", + "MarianTokenizer", + "MarkupLMConfig", + "MarkupLMModel", + "MarkupLMTokenizer", + "MarkupLMTokenizerFast", + "Mask2FormerConfig", + "MaskFormerConfig", + "MaxTimeCriteria", + "MegaConfig", + "MegaModel", + "MegatronBertConfig", + "MegatronBertForPreTraining", + "MegatronBertModel", + "MobileBertConfig", + "MobileBertModel", + "MobileBertTokenizerFast", + "MobileNetV1ImageProcessor", + "MobileNetV1Model", + "MobileNetV2ImageProcessor", + "MobileNetV2Model", + "MobileViTModel", + "MobileViTV2Model", + "MLukeTokenizer", + "MraConfig", + "MusicgenDecoderConfig", + "MusicgenForConditionalGeneration", + "MvpConfig", + "MvpTokenizerFast", + "MT5Tokenizer", + "NatModel", + "NerPipeline", + "NezhaConfig", + "NezhaModel", + "NllbMoeConfig", + "NllbTokenizer", + "NllbTokenizerFast", + "NystromformerConfig", + "OPTConfig", + "ObjectDetectionPipeline", + "OneFormerProcessor", + "OpenAIGPTTokenizerFast", + "OpenLlamaConfig", + "PLBartConfig", + "PegasusConfig", + "PegasusTokenizer", + "PegasusTokenizerFast", + "PegasusXConfig", + "PerceiverImageProcessor", + "PerceiverModel", + "PerceiverTokenizer", + "PersimmonConfig", + "Pipeline", + "Pix2StructConfig", + "Pix2StructTextConfig", + "PLBartTokenizer", + "Pop2PianoConfig", + "PreTrainedTokenizer", + "PreTrainedTokenizerBase", + "PreTrainedTokenizerFast", + "PrefixConstrainedLogitsProcessor", + "ProphetNetConfig", + "QDQBertConfig", + "QDQBertModel", + "QuestionAnsweringPipeline", + "RagConfig", + "RagModel", + "RagRetriever", + "RagSequenceForGeneration", + "RagTokenForGeneration", + "RealmConfig", + "RealmForOpenQA", + "RealmScorer", + "RealmTokenizerFast", + "ReformerConfig", + "ReformerTokenizerFast", + "RegNetConfig", + "RemBertConfig", + "RemBertModel", + "RemBertTokenizer", + "RemBertTokenizerFast", + "RepetitionPenaltyLogitsProcessor", + "RetriBertConfig", + "RetriBertTokenizerFast", + "RoCBertConfig", + "RoCBertModel", + "RoCBertTokenizer", + "RoFormerConfig", + "RobertaConfig", + "RobertaModel", + "RobertaPreLayerNormConfig", + "RobertaPreLayerNormModel", + "RobertaTokenizerFast", + "SEWConfig", + "SEWDConfig", + "SEWDForCTC", + "SEWForCTC", + "SamConfig", + "SamPromptEncoderConfig", + "SeamlessM4TConfig", # use of unconventional markdown + "SeamlessM4Tv2Config", # use of unconventional markdown + "Seq2SeqTrainingArguments", + "SpecialTokensMixin", + "Speech2Text2Config", + "Speech2Text2Tokenizer", + "Speech2TextTokenizer", + "SpeechEncoderDecoderModel", + "SpeechT5Config", + "SpeechT5Model", + "SplinterConfig", + "SplinterTokenizerFast", + "SqueezeBertTokenizerFast", + "SummarizationPipeline", + "Swin2SRImageProcessor", + "Swinv2Model", + "SwitchTransformersConfig", + "T5Config", + "T5Tokenizer", + "T5TokenizerFast", + "TableQuestionAnsweringPipeline", + "TableTransformerConfig", + "TapasConfig", + "TapasModel", + "TapasTokenizer", + "Text2TextGenerationPipeline", + "TextClassificationPipeline", + "TextGenerationPipeline", + "TFAlbertForMaskedLM", + "TFAlbertForMultipleChoice", + "TFAlbertForPreTraining", + "TFAlbertForQuestionAnswering", + "TFAlbertForSequenceClassification", + "TFAlbertForTokenClassification", + "TFAlbertModel", + "TFBartForConditionalGeneration", + "TFBartForSequenceClassification", + "TFBartModel", + "TFBertForMaskedLM", + "TFBertForMultipleChoice", + "TFBertForNextSentencePrediction", + "TFBertForPreTraining", + "TFBertForQuestionAnswering", + "TFBertForSequenceClassification", + "TFBertForTokenClassification", + "TFBertModel", + "TFBlenderbotForConditionalGeneration", + "TFBlenderbotModel", + "TFBlenderbotSmallForConditionalGeneration", + "TFBlenderbotSmallModel", + "TFBlipForConditionalGeneration", + "TFBlipForImageTextRetrieval", + "TFBlipForQuestionAnswering", + "TFCLIPModel", + "TFCTRLForSequenceClassification", + "TFCTRLLMHeadModel", + "TFCTRLModel", + "TFCamembertForCausalLM", + "TFCamembertForMaskedLM", + "TFCamembertForMultipleChoice", + "TFCamembertForQuestionAnswering", + "TFCamembertForSequenceClassification", + "TFCamembertForTokenClassification", + "TFCamembertModel", + "TFConvBertForMaskedLM", + "TFConvBertForMultipleChoice", + "TFConvBertForQuestionAnswering", + "TFConvBertForSequenceClassification", + "TFConvBertForTokenClassification", + "TFConvBertModel", + "TFConvNextForImageClassification", + "TFConvNextModel", + "TFConvNextV2Model", # Parsing issue. Equivalent to PT ConvNextV2Model, see PR #25558 + "TFConvNextV2ForImageClassification", + "TFCvtForImageClassification", + "TFCvtModel", + "TFDPRReader", + "TFData2VecVisionForImageClassification", + "TFData2VecVisionForSemanticSegmentation", + "TFData2VecVisionModel", + "TFDebertaForMaskedLM", + "TFDebertaForQuestionAnswering", + "TFDebertaForSequenceClassification", + "TFDebertaForTokenClassification", + "TFDebertaModel", + "TFDebertaV2ForMaskedLM", + "TFDebertaV2ForMultipleChoice", + "TFDebertaV2ForQuestionAnswering", + "TFDebertaV2ForSequenceClassification", + "TFDebertaV2ForTokenClassification", + "TFDebertaV2Model", + "TFDeiTForImageClassification", + "TFDeiTForImageClassificationWithTeacher", + "TFDeiTForMaskedImageModeling", + "TFDeiTModel", + "TFDistilBertForMaskedLM", + "TFDistilBertForMultipleChoice", + "TFDistilBertForQuestionAnswering", + "TFDistilBertForSequenceClassification", + "TFDistilBertForTokenClassification", + "TFDistilBertModel", + "TFEfficientFormerForImageClassification", + "TFEfficientFormerForImageClassificationWithTeacher", + "TFEfficientFormerModel", + "TFElectraForMaskedLM", + "TFElectraForMultipleChoice", + "TFElectraForPreTraining", + "TFElectraForQuestionAnswering", + "TFElectraForSequenceClassification", + "TFElectraForTokenClassification", + "TFElectraModel", + "TFEncoderDecoderModel", + "TFEsmForMaskedLM", + "TFEsmForSequenceClassification", + "TFEsmForTokenClassification", + "TFEsmModel", + "TFFlaubertForMultipleChoice", + "TFFlaubertForQuestionAnsweringSimple", + "TFFlaubertForSequenceClassification", + "TFFlaubertForTokenClassification", + "TFFlaubertModel", + "TFFlaubertWithLMHeadModel", + "TFFunnelBaseModel", + "TFFunnelForMaskedLM", + "TFFunnelForMultipleChoice", + "TFFunnelForPreTraining", + "TFFunnelForQuestionAnswering", + "TFFunnelForSequenceClassification", + "TFFunnelForTokenClassification", + "TFFunnelModel", + "TFGPT2DoubleHeadsModel", + "TFGPT2ForSequenceClassification", + "TFGPT2LMHeadModel", + "TFGPT2Model", + "TFGPTJForCausalLM", + "TFGPTJForQuestionAnswering", + "TFGPTJForSequenceClassification", + "TFGPTJModel", + "TFGroupViTModel", + "TFHubertForCTC", + "TFHubertModel", + "TFLEDForConditionalGeneration", + "TFLEDModel", + "TFLayoutLMForMaskedLM", + "TFLayoutLMForQuestionAnswering", + "TFLayoutLMForSequenceClassification", + "TFLayoutLMForTokenClassification", + "TFLayoutLMModel", + "TFLayoutLMv3ForQuestionAnswering", + "TFLayoutLMv3ForSequenceClassification", + "TFLayoutLMv3ForTokenClassification", + "TFLayoutLMv3Model", + "TFLongformerForMaskedLM", + "TFLongformerForMultipleChoice", + "TFLongformerForQuestionAnswering", + "TFLongformerForSequenceClassification", + "TFLongformerForTokenClassification", + "TFLongformerModel", + "TFLxmertForPreTraining", + "TFLxmertModel", + "TFMBartForConditionalGeneration", + "TFMBartModel", + "TFMPNetForMaskedLM", + "TFMPNetForMultipleChoice", + "TFMPNetForQuestionAnswering", + "TFMPNetForSequenceClassification", + "TFMPNetForTokenClassification", + "TFMPNetModel", + "TFMarianMTModel", + "TFMarianModel", + "TFMobileBertForMaskedLM", + "TFMobileBertForMultipleChoice", + "TFMobileBertForNextSentencePrediction", + "TFMobileBertForPreTraining", + "TFMobileBertForQuestionAnswering", + "TFMobileBertForSequenceClassification", + "TFMobileBertForTokenClassification", + "TFMobileBertModel", + "TFMobileViTForImageClassification", + "TFMobileViTForSemanticSegmentation", + "TFMobileViTModel", + "TFOPTForCausalLM", + "TFOPTModel", + "TFOpenAIGPTDoubleHeadsModel", + "TFOpenAIGPTForSequenceClassification", + "TFOpenAIGPTLMHeadModel", + "TFOpenAIGPTModel", + "TFPegasusForConditionalGeneration", + "TFPegasusModel", + "TFRagModel", + "TFRagSequenceForGeneration", + "TFRagTokenForGeneration", + "TFRemBertForCausalLM", + "TFRemBertForMaskedLM", + "TFRemBertForMultipleChoice", + "TFRemBertForQuestionAnswering", + "TFRemBertForSequenceClassification", + "TFRemBertForTokenClassification", + "TFRemBertModel", + "TFRepetitionPenaltyLogitsProcessor", + "TFResNetForImageClassification", + "TFResNetModel", + "TFRoFormerForCausalLM", + "TFRoFormerForMaskedLM", + "TFRoFormerForMultipleChoice", + "TFRoFormerForQuestionAnswering", + "TFRoFormerForSequenceClassification", + "TFRoFormerForTokenClassification", + "TFRoFormerModel", + "TFRobertaForMaskedLM", + "TFRobertaForMultipleChoice", + "TFRobertaForQuestionAnswering", + "TFRobertaForSequenceClassification", + "TFRobertaForTokenClassification", + "TFRobertaModel", + "TFRobertaPreLayerNormForMaskedLM", + "TFRobertaPreLayerNormForMultipleChoice", + "TFRobertaPreLayerNormForQuestionAnswering", + "TFRobertaPreLayerNormForSequenceClassification", + "TFRobertaPreLayerNormForTokenClassification", + "TFRobertaPreLayerNormModel", + "TFSamModel", + "TFSegformerForImageClassification", + "TFSegformerForSemanticSegmentation", + "TFSegformerModel", + "TFSpeech2TextForConditionalGeneration", + "TFSpeech2TextModel", + "TFSwinForImageClassification", + "TFSwinForMaskedImageModeling", + "TFSwinModel", + "TFT5EncoderModel", + "TFT5ForConditionalGeneration", + "TFT5Model", + "TFTapasForMaskedLM", + "TFTapasForQuestionAnswering", + "TFTapasForSequenceClassification", + "TFTapasModel", + "TFTransfoXLForSequenceClassification", + "TFTransfoXLLMHeadModel", + "TFTransfoXLModel", + "TFViTForImageClassification", + "TFViTMAEForPreTraining", + "TFViTMAEModel", + "TFViTModel", + "TFVisionEncoderDecoderModel", + "TFVisionTextDualEncoderModel", + "TFWav2Vec2ForCTC", + "TFWav2Vec2Model", + "TFWhisperForConditionalGeneration", + "TFWhisperModel", + "TFXGLMForCausalLM", + "TFXGLMModel", + "TFXLMForMultipleChoice", + "TFXLMForQuestionAnsweringSimple", + "TFXLMForSequenceClassification", + "TFXLMForTokenClassification", + "TFXLMModel", + "TFXLMRobertaForCausalLM", + "TFXLMRobertaForMaskedLM", + "TFXLMRobertaForMultipleChoice", + "TFXLMRobertaForQuestionAnswering", + "TFXLMRobertaForSequenceClassification", + "TFXLMRobertaForTokenClassification", + "TFXLMRobertaModel", + "TFXLMWithLMHeadModel", + "TFXLNetForMultipleChoice", + "TFXLNetForQuestionAnsweringSimple", + "TFXLNetForSequenceClassification", + "TFXLNetForTokenClassification", + "TFXLNetLMHeadModel", + "TFXLNetModel", + "TimeSeriesTransformerConfig", + "TokenClassificationPipeline", + "TrOCRConfig", + "TrainerState", + "TrainingArguments", + "TrajectoryTransformerConfig", + "TranslationPipeline", + "TvltImageProcessor", + "UMT5Config", + "UperNetConfig", + "UperNetForSemanticSegmentation", + "ViTHybridImageProcessor", + "ViTHybridModel", + "ViTMSNModel", + "ViTModel", + "VideoClassificationPipeline", + "ViltConfig", + "ViltForImagesAndTextClassification", + "ViltModel", + "VisionEncoderDecoderModel", + "VisionTextDualEncoderModel", + "VisualBertConfig", + "VisualBertModel", + "VisualQuestionAnsweringPipeline", + "VitMatteForImageMatting", + "VitsTokenizer", + "VivitModel", + "Wav2Vec2CTCTokenizer", + "Wav2Vec2Config", + "Wav2Vec2ConformerConfig", + "Wav2Vec2ConformerForCTC", + "Wav2Vec2FeatureExtractor", + "Wav2Vec2PhonemeCTCTokenizer", + "WavLMConfig", + "WavLMForCTC", + "WhisperConfig", + "WhisperFeatureExtractor", + "WhisperForAudioClassification", + "XCLIPTextConfig", + "XCLIPVisionConfig", + "XGLMConfig", + "XGLMModel", + "XGLMTokenizerFast", + "XLMConfig", + "XLMProphetNetConfig", + "XLMRobertaConfig", + "XLMRobertaModel", + "XLMRobertaTokenizerFast", + "XLMRobertaXLConfig", + "XLMRobertaXLModel", + "XLNetConfig", + "XLNetTokenizerFast", + "XmodConfig", + "XmodModel", + "YolosImageProcessor", + "YolosModel", + "YosoConfig", + "ZeroShotAudioClassificationPipeline", + "ZeroShotClassificationPipeline", + "ZeroShotImageClassificationPipeline", + "ZeroShotObjectDetectionPipeline", +] + +# Supported math operations when interpreting the value of defaults. +MATH_OPERATORS = { + ast.Add: op.add, + ast.Sub: op.sub, + ast.Mult: op.mul, + ast.Div: op.truediv, + ast.Pow: op.pow, + ast.BitXor: op.xor, + ast.USub: op.neg, +} + + +def find_indent(line: str) -> int: + """ + Returns the number of spaces that start a line indent. + """ + search = re.search(r"^(\s*)(?:\S|$)", line) + if search is None: + return 0 + return len(search.groups()[0]) + + +def stringify_default(default: Any) -> str: + """ + Returns the string representation of a default value, as used in docstring: numbers are left as is, all other + objects are in backtiks. + + Args: + default (`Any`): The default value to process + + Returns: + `str`: The string representation of that default. + """ + if isinstance(default, bool): + # We need to test for bool first as a bool passes isinstance(xxx, (int, float)) + return f"`{default}`" + elif isinstance(default, enum.Enum): + # We need to test for enum first as an enum with int values will pass isinstance(xxx, (int, float)) + return f"`{str(default)}`" + elif isinstance(default, int): + return str(default) + elif isinstance(default, float): + result = str(default) + return str(round(default, 2)) if len(result) > 6 else result + elif isinstance(default, str): + return str(default) if default.isnumeric() else f'`"{default}"`' + elif isinstance(default, type): + return f"`{default.__name__}`" + else: + return f"`{default}`" + + +def eval_math_expression(expression: str) -> Optional[Union[float, int]]: + # Mainly taken from the excellent https://stackoverflow.com/a/9558001 + """ + Evaluate (safely) a mathematial expression and returns its value. + + Args: + expression (`str`): The expression to evaluate. + + Returns: + `Optional[Union[float, int]]`: Returns `None` if the evaluation fails in any way and the value computed + otherwise. + + Example: + + ```py + >>> eval_expr('2^6') + 4 + >>> eval_expr('2**6') + 64 + >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)') + -5.0 + ``` + """ + try: + return eval_node(ast.parse(expression, mode="eval").body) + except TypeError: + return + + +def eval_node(node): + if isinstance(node, ast.Num): # + return node.n + elif isinstance(node, ast.BinOp): # + return MATH_OPERATORS[type(node.op)](eval_node(node.left), eval_node(node.right)) + elif isinstance(node, ast.UnaryOp): # e.g., -1 + return MATH_OPERATORS[type(node.op)](eval_node(node.operand)) + else: + raise TypeError(node) + + +def replace_default_in_arg_description(description: str, default: Any) -> str: + """ + Catches the default value in the description of an argument inside a docstring and replaces it by the value passed. + + Args: + description (`str`): The description of an argument in a docstring to process. + default (`Any`): The default value that whould be in the docstring of that argument. + + Returns: + `str`: The description updated with the new default value. + """ + # Lots of docstrings have `optional` or **opational** instead of *optional* so we do this fix here. + description = description.replace("`optional`", OPTIONAL_KEYWORD) + description = description.replace("**optional**", OPTIONAL_KEYWORD) + if default is inspect._empty: + # No default, make sure the description doesn't have any either + idx = description.find(OPTIONAL_KEYWORD) + if idx != -1: + description = description[:idx].rstrip() + if description.endswith(","): + description = description[:-1].rstrip() + elif default is None: + # Default None are not written, we just set `*optional*`. If there is default that is not None specified in the + # description, we do not erase it (as sometimes we set the default to `None` because the default is a mutable + # object). + idx = description.find(OPTIONAL_KEYWORD) + if idx == -1: + description = f"{description}, {OPTIONAL_KEYWORD}" + elif re.search(r"defaults to `?None`?", description) is not None: + len_optional = len(OPTIONAL_KEYWORD) + description = description[: idx + len_optional] + else: + str_default = None + # For numbers we may have a default that is given by a math operation (1/255 is really popular). We don't + # want to replace those by their actual values. + if isinstance(default, (int, float)) and re.search("defaults to `?(.*?)(?:`|$)", description) is not None: + # Grab the default and evaluate it. + current_default = re.search("defaults to `?(.*?)(?:`|$)", description).groups()[0] + if default == eval_math_expression(current_default): + try: + # If it can be directly converted to the type of the default, it's a simple value + str_default = str(type(default)(current_default)) + except Exception: + # Otherwise there is a math operator so we add a code block. + str_default = f"`{current_default}`" + + if str_default is None: + str_default = stringify_default(default) + # Make sure default match + if OPTIONAL_KEYWORD not in description: + description = f"{description}, {OPTIONAL_KEYWORD}, defaults to {str_default}" + elif _re_parse_description.search(description) is None: + idx = description.find(OPTIONAL_KEYWORD) + len_optional = len(OPTIONAL_KEYWORD) + description = f"{description[:idx + len_optional]}, defaults to {str_default}" + else: + description = _re_parse_description.sub(rf"*optional*, defaults to {str_default}", description) + + return description + + +def get_default_description(arg: inspect.Parameter) -> str: + """ + Builds a default description for a parameter that was not documented. + + Args: + arg (`inspect.Parameter`): The argument in the signature to generate a description for. + + Returns: + `str`: The description. + """ + if arg.annotation is inspect._empty: + arg_type = "" + elif hasattr(arg.annotation, "__name__"): + arg_type = arg.annotation.__name__ + else: + arg_type = str(arg.annotation) + + if arg.default is inspect._empty: + return f"`{arg_type}`" + elif arg.default is None: + return f"`{arg_type}`, {OPTIONAL_KEYWORD}" + else: + str_default = stringify_default(arg.default) + return f"`{arg_type}`, {OPTIONAL_KEYWORD}, defaults to {str_default}" + + +def find_source_file(obj: Any) -> Path: + """ + Finds the source file of an object. + + Args: + obj (`Any`): The object whose source file we are looking for. + + Returns: + `Path`: The source file. + """ + module = obj.__module__ + obj_file = PATH_TO_TRANSFORMERS + for part in module.split(".")[1:]: + obj_file = obj_file / part + return obj_file.with_suffix(".py") + + +def match_docstring_with_signature(obj: Any) -> Optional[Tuple[str, str]]: + """ + Matches the docstring of an object with its signature. + + Args: + obj (`Any`): The object to process. + + Returns: + `Optional[Tuple[str, str]]`: Returns `None` if there is no docstring or no parameters documented in the + docstring, otherwise returns a tuple of two strings: the current documentation of the arguments in the + docstring and the one matched with the signature. + """ + if len(getattr(obj, "__doc__", "")) == 0: + # Nothing to do, there is no docstring. + return + + # Read the docstring in the source code to see if there is a special command to ignore this object. + try: + source, _ = inspect.getsourcelines(obj) + except OSError: + source = [] + + idx = 0 + while idx < len(source) and '"""' not in source[idx]: + idx += 1 + + ignore_order = False + if idx < len(source): + line_before_docstring = source[idx - 1] + if re.search(r"^\s*#\s*no-format\s*$", line_before_docstring): + # This object is ignored + return + elif re.search(r"^\s*#\s*ignore-order\s*$", line_before_docstring): + ignore_order = True + + # Read the signature + signature = inspect.signature(obj).parameters + + obj_doc_lines = obj.__doc__.split("\n") + # Get to the line where we start documenting arguments + idx = 0 + while idx < len(obj_doc_lines) and _re_args.search(obj_doc_lines[idx]) is None: + idx += 1 + + if idx == len(obj_doc_lines): + # Nothing to do, no parameters are documented. + return + + indent = find_indent(obj_doc_lines[idx]) + arguments = {} + current_arg = None + idx += 1 + start_idx = idx + # Keep going until the arg section is finished (nonempty line at the same indent level) or the end of the docstring. + while idx < len(obj_doc_lines) and ( + len(obj_doc_lines[idx].strip()) == 0 or find_indent(obj_doc_lines[idx]) > indent + ): + if find_indent(obj_doc_lines[idx]) == indent + 4: + # New argument -> let's generate the proper doc for it + re_search_arg = _re_parse_arg.search(obj_doc_lines[idx]) + if re_search_arg is not None: + _, name, description = re_search_arg.groups() + current_arg = name + if name in signature: + default = signature[name].default + if signature[name].kind is inspect._ParameterKind.VAR_KEYWORD: + default = None + new_description = replace_default_in_arg_description(description, default) + else: + new_description = description + init_doc = _re_parse_arg.sub(rf"\1\2 ({new_description}):", obj_doc_lines[idx]) + arguments[current_arg] = [init_doc] + elif current_arg is not None: + arguments[current_arg].append(obj_doc_lines[idx]) + + idx += 1 + + # We went too far by one (perhaps more if there are a lot of new lines) + idx -= 1 + while len(obj_doc_lines[idx].strip()) == 0: + arguments[current_arg] = arguments[current_arg][:-1] + idx -= 1 + # And we went too far by one again. + idx += 1 + + old_doc_arg = "\n".join(obj_doc_lines[start_idx:idx]) + + old_arguments = list(arguments.keys()) + arguments = {name: "\n".join(doc) for name, doc in arguments.items()} + # Add missing arguments with a template + for name in set(signature.keys()) - set(arguments.keys()): + arg = signature[name] + # We ignore private arguments or *args/**kwargs (unless they are documented by the user) + if name.startswith("_") or arg.kind in [ + inspect._ParameterKind.VAR_KEYWORD, + inspect._ParameterKind.VAR_POSITIONAL, + ]: + arguments[name] = "" + else: + arg_desc = get_default_description(arg) + arguments[name] = " " * (indent + 4) + f"{name} ({arg_desc}): " + + # Arguments are sorted by the order in the signature unless a special comment is put. + if ignore_order: + new_param_docs = [arguments[name] for name in old_arguments if name in signature] + missing = set(signature.keys()) - set(old_arguments) + new_param_docs.extend([arguments[name] for name in missing if len(arguments[name]) > 0]) + else: + new_param_docs = [arguments[name] for name in signature.keys() if len(arguments[name]) > 0] + new_doc_arg = "\n".join(new_param_docs) + + return old_doc_arg, new_doc_arg + + +def fix_docstring(obj: Any, old_doc_args: str, new_doc_args: str): + """ + Fixes the docstring of an object by replacing its arguments documentaiton by the one matched with the signature. + + Args: + obj (`Any`): + The object whose dostring we are fixing. + old_doc_args (`str`): + The current documentation of the parameters of `obj` in the docstring (as returned by + `match_docstring_with_signature`). + new_doc_args (`str`): + The documentation of the parameters of `obj` matched with its signature (as returned by + `match_docstring_with_signature`). + """ + # Read the docstring in the source code and make sure we have the right part of the docstring + source, line_number = inspect.getsourcelines(obj) + + # Get to the line where we start documenting arguments + idx = 0 + while idx < len(source) and _re_args.search(source[idx]) is None: + idx += 1 + + if idx == len(source): + # Args are not defined in the docstring of this object + return + + # Get to the line where we stop documenting arguments + indent = find_indent(source[idx]) + idx += 1 + start_idx = idx + while idx < len(source) and (len(source[idx].strip()) == 0 or find_indent(source[idx]) > indent): + idx += 1 + + idx -= 1 + while len(source[idx].strip()) == 0: + idx -= 1 + idx += 1 + + if "".join(source[start_idx:idx])[:-1] != old_doc_args: + # Args are not fully defined in the docstring of this object + return + + obj_file = find_source_file(obj) + with open(obj_file, "r", encoding="utf-8") as f: + content = f.read() + + # Replace content + lines = content.split("\n") + lines = lines[: line_number + start_idx - 1] + [new_doc_args] + lines[line_number + idx - 1 :] + + print(f"Fixing the docstring of {obj.__name__} in {obj_file}.") + with open(obj_file, "w", encoding="utf-8") as f: + f.write("\n".join(lines)) + + +def check_docstrings(overwrite: bool = False): + """ + Check docstrings of all public objects that are callables and are documented. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether to fix inconsistencies or not. + """ + failures = [] + hard_failures = [] + to_clean = [] + for name in dir(transformers): + # Skip objects that are private or not documented. + if name.startswith("_") or ignore_undocumented(name) or name in OBJECTS_TO_IGNORE: + continue + + obj = getattr(transformers, name) + if not callable(obj) or not isinstance(obj, type) or getattr(obj, "__doc__", None) is None: + continue + + # Check docstring + try: + result = match_docstring_with_signature(obj) + if result is not None: + old_doc, new_doc = result + else: + old_doc, new_doc = None, None + except Exception as e: + print(e) + hard_failures.append(name) + continue + if old_doc != new_doc: + if overwrite: + fix_docstring(obj, old_doc, new_doc) + else: + failures.append(name) + elif not overwrite and new_doc is not None and ("" in new_doc or "" in new_doc): + to_clean.append(name) + + # Deal with errors + error_message = "" + if len(hard_failures) > 0: + error_message += ( + "The argument part of the docstrings of the following objects could not be processed, check they are " + "properly formatted." + ) + error_message += "\n" + "\n".join([f"- {name}" for name in hard_failures]) + if len(failures) > 0: + error_message += ( + "The following objects docstrings do not match their signature. Run `make fix-copies` to fix this." + ) + error_message += "\n" + "\n".join([f"- {name}" for name in failures]) + if len(to_clean) > 0: + error_message += ( + "The following objects docstrings contain templates you need to fix: search for `` or " + "``." + ) + error_message += "\n" + "\n".join([f"- {name}" for name in to_clean]) + + if len(error_message) > 0: + error_message = "There was at least one problem when checking docstrings of public objects.\n" + error_message + raise ValueError(error_message) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + check_docstrings(overwrite=args.fix_and_overwrite) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_doctest_list.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_doctest_list.py new file mode 100644 index 0000000000000000000000000000000000000000..f39895ff52186e7a6c7216b2b9a4815b9ba186da --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_doctest_list.py @@ -0,0 +1,85 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +""" +This script is responsible for cleaning the list of doctests by making sure the entries all exist and are in +alphabetical order. + +Usage (from the root of the repo): + +Check that the doctest list is properly sorted and all files exist (used in `make repo-consistency`): + +```bash +python utils/check_doctest_list.py +``` + +Auto-sort the doctest list if it is not properly sorted (used in `make fix-copies`): + +```bash +python utils/check_doctest_list.py --fix_and_overwrite +``` +""" +import argparse +import os + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_doctest_list.py +REPO_PATH = "." +DOCTEST_FILE_PATHS = ["not_doctested.txt", "slow_documentation_tests.txt"] + + +def clean_doctest_list(doctest_file: str, overwrite: bool = False): + """ + Cleans the doctest in a given file. + + Args: + doctest_file (`str`): + The path to the doctest file to check or clean. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to fix problems. If `False`, will error when the file is not clean. + """ + non_existent_paths = [] + all_paths = [] + with open(doctest_file, "r", encoding="utf-8") as f: + for line in f: + line = line.strip().split(" ")[0] + path = os.path.join(REPO_PATH, line) + if not (os.path.isfile(path) or os.path.isdir(path)): + non_existent_paths.append(line) + all_paths.append(line) + + if len(non_existent_paths) > 0: + non_existent_paths = "\n".join([f"- {f}" for f in non_existent_paths]) + raise ValueError(f"`{doctest_file}` contains non-existent paths:\n{non_existent_paths}") + + sorted_paths = sorted(all_paths) + if all_paths != sorted_paths: + if not overwrite: + raise ValueError( + f"Files in `{doctest_file}` are not in alphabetical order, run `make fix-copies` to fix " + "this automatically." + ) + with open(doctest_file, "w", encoding="utf-8") as f: + f.write("\n".join(sorted_paths) + "\n") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + for doctest_file in DOCTEST_FILE_PATHS: + doctest_file = os.path.join(REPO_PATH, "utils", doctest_file) + clean_doctest_list(doctest_file, args.fix_and_overwrite) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_dummies.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_dummies.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ab6ebfa77b92ed00b17ae8e77b1666a216a9a0 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_dummies.py @@ -0,0 +1,236 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. +""" +This script is responsible for making sure the dummies in utils/dummies_xxx.py are up to date with the main init. + +Why dummies? This is to make sure that a user can always import all objects from `transformers`, even if they don't +have the necessary extra libs installed. Those objects will then raise helpful error message whenever the user tries +to access one of their methods. + +Usage (from the root of the repo): + +Check that the dummy files are up to date (used in `make repo-consistency`): + +```bash +python utils/check_dummies.py +``` + +Update the dummy files if needed (used in `make fix-copies`): + +```bash +python utils/check_dummies.py --fix_and_overwrite +``` +""" +import argparse +import os +import re +from typing import Dict, List, Optional + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_dummies.py +PATH_TO_TRANSFORMERS = "src/transformers" + +# Matches is_xxx_available() +_re_backend = re.compile(r"is\_([a-z_]*)_available()") +# Matches from xxx import bla +_re_single_line_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") +# Matches if not is_xxx_available() +_re_test_backend = re.compile(r"^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)") + + +# Template for the dummy objects. +DUMMY_CONSTANT = """ +{0} = None +""" + + +DUMMY_CLASS = """ +class {0}(metaclass=DummyObject): + _backends = {1} + + def __init__(self, *args, **kwargs): + requires_backends(self, {1}) +""" + + +DUMMY_FUNCTION = """ +def {0}(*args, **kwargs): + requires_backends({0}, {1}) +""" + + +def find_backend(line: str) -> Optional[str]: + """ + Find one (or multiple) backend in a code line of the init. + + Args: + line (`str`): A code line in an init file. + + Returns: + Optional[`str`]: If one (or several) backend is found, returns it. In the case of multiple backends (the line + contains `if is_xxx_available() and `is_yyy_available()`) returns all backends joined on `_and_` (so + `xxx_and_yyy` for instance). + """ + if _re_test_backend.search(line) is None: + return None + backends = [b[0] for b in _re_backend.findall(line)] + backends.sort() + return "_and_".join(backends) + + +def read_init() -> Dict[str, List[str]]: + """ + Read the init and extract backend-specific objects. + + Returns: + Dict[str, List[str]]: A dictionary mapping backend name to the list of object names requiring that backend. + """ + with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Get to the point we do the actual imports for type checking + line_index = 0 + while not lines[line_index].startswith("if TYPE_CHECKING"): + line_index += 1 + + backend_specific_objects = {} + # Go through the end of the file + while line_index < len(lines): + # If the line is an if is_backend_available, we grab all objects associated. + backend = find_backend(lines[line_index]) + if backend is not None: + while not lines[line_index].startswith(" else:"): + line_index += 1 + line_index += 1 + + objects = [] + # Until we unindent, add backend objects to the list + while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8): + line = lines[line_index] + single_line_import_search = _re_single_line_import.search(line) + if single_line_import_search is not None: + # Single-line imports + objects.extend(single_line_import_search.groups()[0].split(", ")) + elif line.startswith(" " * 12): + # Multiple-line imports (with 3 indent level) + objects.append(line[12:-2]) + line_index += 1 + + backend_specific_objects[backend] = objects + else: + line_index += 1 + + return backend_specific_objects + + +def create_dummy_object(name: str, backend_name: str) -> str: + """ + Create the code for a dummy object. + + Args: + name (`str`): The name of the object. + backend_name (`str`): The name of the backend required for that object. + + Returns: + `str`: The code of the dummy object. + """ + if name.isupper(): + return DUMMY_CONSTANT.format(name) + elif name.islower(): + return DUMMY_FUNCTION.format(name, backend_name) + else: + return DUMMY_CLASS.format(name, backend_name) + + +def create_dummy_files(backend_specific_objects: Optional[Dict[str, List[str]]] = None) -> Dict[str, str]: + """ + Create the content of the dummy files. + + Args: + backend_specific_objects (`Dict[str, List[str]]`, *optional*): + The mapping backend name to list of backend-specific objects. If not passed, will be obtained by calling + `read_init()`. + + Returns: + `Dict[str, str]`: A dictionary mapping backend name to code of the corresponding backend file. + """ + if backend_specific_objects is None: + backend_specific_objects = read_init() + + dummy_files = {} + + for backend, objects in backend_specific_objects.items(): + backend_name = "[" + ", ".join(f'"{b}"' for b in backend.split("_and_")) + "]" + dummy_file = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n" + dummy_file += "from ..utils import DummyObject, requires_backends\n\n" + dummy_file += "\n".join([create_dummy_object(o, backend_name) for o in objects]) + dummy_files[backend] = dummy_file + + return dummy_files + + +def check_dummies(overwrite: bool = False): + """ + Check if the dummy files are up to date and maybe `overwrite` with the right content. + + Args: + overwrite (`bool`, *optional*, default to `False`): + Whether or not to overwrite the content of the dummy files. Will raise an error if they are not up to date + when `overwrite=False`. + """ + dummy_files = create_dummy_files() + # For special correspondence backend name to shortcut as used in utils/dummy_xxx_objects.py + short_names = {"torch": "pt"} + + # Locate actual dummy modules and read their content. + path = os.path.join(PATH_TO_TRANSFORMERS, "utils") + dummy_file_paths = { + backend: os.path.join(path, f"dummy_{short_names.get(backend, backend)}_objects.py") + for backend in dummy_files.keys() + } + + actual_dummies = {} + for backend, file_path in dummy_file_paths.items(): + if os.path.isfile(file_path): + with open(file_path, "r", encoding="utf-8", newline="\n") as f: + actual_dummies[backend] = f.read() + else: + actual_dummies[backend] = "" + + # Compare actual with what they should be. + for backend in dummy_files.keys(): + if dummy_files[backend] != actual_dummies[backend]: + if overwrite: + print( + f"Updating transformers.utils.dummy_{short_names.get(backend, backend)}_objects.py as the main " + "__init__ has new objects." + ) + with open(dummy_file_paths[backend], "w", encoding="utf-8", newline="\n") as f: + f.write(dummy_files[backend]) + else: + raise ValueError( + "The main __init__ has objects that are not present in " + f"transformers.utils.dummy_{short_names.get(backend, backend)}_objects.py. Run `make fix-copies` " + "to fix this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + check_dummies(args.fix_and_overwrite) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_inits.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_inits.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a637e6354bba0d2c706f9079ff20c645a10308 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_inits.py @@ -0,0 +1,371 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. +""" +Utility that checks the custom inits of Transformers are well-defined: Transformers uses init files that delay the +import of an object to when it's actually needed. This is to avoid the main init importing all models, which would +make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with +delayed imports have two halves: one definining a dictionary `_import_structure` which maps modules to the name of the +objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. The goal of this +script is to check the objects defined in both halves are the same. + +This also checks the main init properly references all submodules, even if it doesn't import anything from them: every +submodule should be defined as a key of `_import_structure`, with an empty list as value potentially, or the submodule +won't be importable. + +Use from the root of the repo with: + +```bash +python utils/check_inits.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`). + +There is no auto-fix possible here sadly :-( +""" + +import collections +import os +import re +from pathlib import Path +from typing import Dict, List, Optional, Tuple + + +# Path is set with the intent you should run this script from the root of the repo. +PATH_TO_TRANSFORMERS = "src/transformers" + + +# Matches is_xxx_available() +_re_backend = re.compile(r"is\_([a-z_]*)_available()") +# Catches a one-line _import_struct = {xxx} +_re_one_line_import_struct = re.compile(r"^_import_structure\s+=\s+\{([^\}]+)\}") +# Catches a line with a key-values pattern: "bla": ["foo", "bar"] +_re_import_struct_key_value = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') +# Catches a line if not is_foo_available +_re_test_backend = re.compile(r"^\s*if\s+not\s+is\_[a-z_]*\_available\(\)") +# Catches a line _import_struct["bla"].append("foo") +_re_import_struct_add_one = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') +# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] +_re_import_struct_add_many = re.compile(r"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]") +# Catches a line with an object between quotes and a comma: "MyModel", +_re_quote_object = re.compile(r'^\s+"([^"]+)",') +# Catches a line with objects between brackets only: ["foo", "bar"], +_re_between_brackets = re.compile(r"^\s+\[([^\]]+)\]") +# Catches a line with from foo import bar, bla, boo +_re_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") +# Catches a line with try: +_re_try = re.compile(r"^\s*try:") +# Catches a line with else: +_re_else = re.compile(r"^\s*else:") + + +def find_backend(line: str) -> Optional[str]: + """ + Find one (or multiple) backend in a code line of the init. + + Args: + line (`str`): A code line of the main init. + + Returns: + Optional[`str`]: If one (or several) backend is found, returns it. In the case of multiple backends (the line + contains `if is_xxx_available() and `is_yyy_available()`) returns all backends joined on `_and_` (so + `xxx_and_yyy` for instance). + """ + if _re_test_backend.search(line) is None: + return None + backends = [b[0] for b in _re_backend.findall(line)] + backends.sort() + return "_and_".join(backends) + + +def parse_init(init_file) -> Optional[Tuple[Dict[str, List[str]], Dict[str, List[str]]]]: + """ + Read an init_file and parse (per backend) the `_import_structure` objects defined and the `TYPE_CHECKING` objects + defined. + + Args: + init_file (`str`): Path to the init file to inspect. + + Returns: + `Optional[Tuple[Dict[str, List[str]], Dict[str, List[str]]]]`: A tuple of two dictionaries mapping backends to list of + imported objects, one for the `_import_structure` part of the init and one for the `TYPE_CHECKING` part of the + init. Returns `None` if the init is not a custom init. + """ + with open(init_file, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Get the to `_import_structure` definition. + line_index = 0 + while line_index < len(lines) and not lines[line_index].startswith("_import_structure = {"): + line_index += 1 + + # If this is a traditional init, just return. + if line_index >= len(lines): + return None + + # First grab the objects without a specific backend in _import_structure + objects = [] + while not lines[line_index].startswith("if TYPE_CHECKING") and find_backend(lines[line_index]) is None: + line = lines[line_index] + # If we have everything on a single line, let's deal with it. + if _re_one_line_import_struct.search(line): + content = _re_one_line_import_struct.search(line).groups()[0] + imports = re.findall(r"\[([^\]]+)\]", content) + for imp in imports: + objects.extend([obj[1:-1] for obj in imp.split(", ")]) + line_index += 1 + continue + single_line_import_search = _re_import_struct_key_value.search(line) + if single_line_import_search is not None: + imports = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", ") if len(obj) > 0] + objects.extend(imports) + elif line.startswith(" " * 8 + '"'): + objects.append(line[9:-3]) + line_index += 1 + + # Those are stored with the key "none". + import_dict_objects = {"none": objects} + + # Let's continue with backend-specific objects in _import_structure + while not lines[line_index].startswith("if TYPE_CHECKING"): + # If the line is an if not is_backend_available, we grab all objects associated. + backend = find_backend(lines[line_index]) + # Check if the backend declaration is inside a try block: + if _re_try.search(lines[line_index - 1]) is None: + backend = None + + if backend is not None: + line_index += 1 + + # Scroll until we hit the else block of try-except-else + while _re_else.search(lines[line_index]) is None: + line_index += 1 + + line_index += 1 + + objects = [] + # Until we unindent, add backend objects to the list + while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 4): + line = lines[line_index] + if _re_import_struct_add_one.search(line) is not None: + objects.append(_re_import_struct_add_one.search(line).groups()[0]) + elif _re_import_struct_add_many.search(line) is not None: + imports = _re_import_struct_add_many.search(line).groups()[0].split(", ") + imports = [obj[1:-1] for obj in imports if len(obj) > 0] + objects.extend(imports) + elif _re_between_brackets.search(line) is not None: + imports = _re_between_brackets.search(line).groups()[0].split(", ") + imports = [obj[1:-1] for obj in imports if len(obj) > 0] + objects.extend(imports) + elif _re_quote_object.search(line) is not None: + objects.append(_re_quote_object.search(line).groups()[0]) + elif line.startswith(" " * 8 + '"'): + objects.append(line[9:-3]) + elif line.startswith(" " * 12 + '"'): + objects.append(line[13:-3]) + line_index += 1 + + import_dict_objects[backend] = objects + else: + line_index += 1 + + # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend + objects = [] + while ( + line_index < len(lines) + and find_backend(lines[line_index]) is None + and not lines[line_index].startswith("else") + ): + line = lines[line_index] + single_line_import_search = _re_import.search(line) + if single_line_import_search is not None: + objects.extend(single_line_import_search.groups()[0].split(", ")) + elif line.startswith(" " * 8): + objects.append(line[8:-2]) + line_index += 1 + + type_hint_objects = {"none": objects} + + # Let's continue with backend-specific objects + while line_index < len(lines): + # If the line is an if is_backend_available, we grab all objects associated. + backend = find_backend(lines[line_index]) + # Check if the backend declaration is inside a try block: + if _re_try.search(lines[line_index - 1]) is None: + backend = None + + if backend is not None: + line_index += 1 + + # Scroll until we hit the else block of try-except-else + while _re_else.search(lines[line_index]) is None: + line_index += 1 + + line_index += 1 + + objects = [] + # Until we unindent, add backend objects to the list + while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8): + line = lines[line_index] + single_line_import_search = _re_import.search(line) + if single_line_import_search is not None: + objects.extend(single_line_import_search.groups()[0].split(", ")) + elif line.startswith(" " * 12): + objects.append(line[12:-2]) + line_index += 1 + + type_hint_objects[backend] = objects + else: + line_index += 1 + + return import_dict_objects, type_hint_objects + + +def analyze_results(import_dict_objects: Dict[str, List[str]], type_hint_objects: Dict[str, List[str]]) -> List[str]: + """ + Analyze the differences between _import_structure objects and TYPE_CHECKING objects found in an init. + + Args: + import_dict_objects (`Dict[str, List[str]]`): + A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to + list of imported objects. + type_hint_objects (`Dict[str, List[str]]`): + A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to + list of imported objects. + + Returns: + `List[str]`: The list of errors corresponding to mismatches. + """ + + def find_duplicates(seq): + return [k for k, v in collections.Counter(seq).items() if v > 1] + + # If one backend is missing from the other part of the init, error early. + if list(import_dict_objects.keys()) != list(type_hint_objects.keys()): + return ["Both sides of the init do not have the same backends!"] + + errors = [] + # Find all errors. + for key in import_dict_objects.keys(): + # Duplicate imports in any half. + duplicate_imports = find_duplicates(import_dict_objects[key]) + if duplicate_imports: + errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}") + duplicate_type_hints = find_duplicates(type_hint_objects[key]) + if duplicate_type_hints: + errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}") + + # Missing imports in either part of the init. + if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])): + name = "base imports" if key == "none" else f"{key} backend" + errors.append(f"Differences for {name}:") + for a in type_hint_objects[key]: + if a not in import_dict_objects[key]: + errors.append(f" {a} in TYPE_HINT but not in _import_structure.") + for a in import_dict_objects[key]: + if a not in type_hint_objects[key]: + errors.append(f" {a} in _import_structure but not in TYPE_HINT.") + return errors + + +def check_all_inits(): + """ + Check all inits in the transformers repo and raise an error if at least one does not define the same objects in + both halves. + """ + failures = [] + for root, _, files in os.walk(PATH_TO_TRANSFORMERS): + if "__init__.py" in files: + fname = os.path.join(root, "__init__.py") + objects = parse_init(fname) + if objects is not None: + errors = analyze_results(*objects) + if len(errors) > 0: + errors[0] = f"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" + failures.append("\n".join(errors)) + if len(failures) > 0: + raise ValueError("\n\n".join(failures)) + + +def get_transformers_submodules() -> List[str]: + """ + Returns the list of Transformers submodules. + """ + submodules = [] + for path, directories, files in os.walk(PATH_TO_TRANSFORMERS): + for folder in directories: + # Ignore private modules + if folder.startswith("_"): + directories.remove(folder) + continue + # Ignore leftovers from branches (empty folders apart from pycache) + if len(list((Path(path) / folder).glob("*.py"))) == 0: + continue + short_path = str((Path(path) / folder).relative_to(PATH_TO_TRANSFORMERS)) + submodule = short_path.replace(os.path.sep, ".") + submodules.append(submodule) + for fname in files: + if fname == "__init__.py": + continue + short_path = str((Path(path) / fname).relative_to(PATH_TO_TRANSFORMERS)) + submodule = short_path.replace(".py", "").replace(os.path.sep, ".") + if len(submodule.split(".")) == 1: + submodules.append(submodule) + return submodules + + +IGNORE_SUBMODULES = [ + "convert_pytorch_checkpoint_to_tf2", + "modeling_flax_pytorch_utils", + "models.esm.openfold_utils", + "modeling_attn_mask_utils", + "safetensors_conversion", +] + + +def check_submodules(): + """ + Check all submodules of Transformers are properly registered in the main init. Error otherwise. + """ + # This is to make sure the transformers module imported is the one in the repo. + from transformers.utils import direct_transformers_import + + transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + + import_structure_keys = set(transformers._import_structure.keys()) + # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing + # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and + # (potentiall re-) add them. + with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r") as f: + init_content = f.read() + import_structure_keys.update(set(re.findall(r"import_structure\[\"([^\"]*)\"\]", init_content))) + + module_not_registered = [ + module + for module in get_transformers_submodules() + if module not in IGNORE_SUBMODULES and module not in import_structure_keys + ] + + if len(module_not_registered) > 0: + list_of_modules = "\n".join(f"- {module}" for module in module_not_registered) + raise ValueError( + "The following submodules are not properly registed in the main init of Transformers:\n" + f"{list_of_modules}\n" + "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." + ) + + +if __name__ == "__main__": + check_all_inits() + check_submodules() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_model_tester.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_model_tester.py new file mode 100644 index 0000000000000000000000000000000000000000..8ace411b1a4e7db68fcc1a0ed874dfc3005721a1 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_model_tester.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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 glob +import os + +from get_test_info import get_tester_classes + + +if __name__ == "__main__": + failures = [] + + pattern = os.path.join("tests", "models", "**", "test_modeling_*.py") + test_files = glob.glob(pattern) + # TODO: deal with TF/Flax too + test_files = [ + x for x in test_files if not (x.startswith("test_modeling_tf_") or x.startswith("test_modeling_flax_")) + ] + + for test_file in test_files: + tester_classes = get_tester_classes(test_file) + for tester_class in tester_classes: + # A few tester classes don't have `parent` parameter in `__init__`. + # TODO: deal this better + try: + tester = tester_class(parent=None) + except Exception: + continue + if hasattr(tester, "get_config"): + config = tester.get_config() + for k, v in config.to_dict().items(): + if isinstance(v, int): + target = None + if k in ["vocab_size"]: + target = 100 + elif k in ["max_position_embeddings"]: + target = 128 + elif k in ["hidden_size", "d_model"]: + target = 40 + elif k == ["num_layers", "num_hidden_layers", "num_encoder_layers", "num_decoder_layers"]: + target = 5 + if target is not None and v > target: + failures.append( + f"{tester_class.__name__} will produce a `config` of type `{config.__class__.__name__}`" + f' with config["{k}"] = {v} which is too large for testing! Set its value to be smaller' + f" than {target}." + ) + + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_repo.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_repo.py new file mode 100644 index 0000000000000000000000000000000000000000..aac06276234632e5f20f7fbc1dcb36b2ccc27c31 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_repo.py @@ -0,0 +1,1175 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. +""" +Utility that performs several consistency checks on the repo. This includes: +- checking all models are properly defined in the __init__ of models/ +- checking all models are in the main __init__ +- checking all models are properly tested +- checking all object in the main __init__ are documented +- checking all models are in at least one auto class +- checking all the auto mapping are properly defined (no typos, importable) +- checking the list of deprecated models is up to date + +Use from the root of the repo with (as used in `make repo-consistency`): + +```bash +python utils/check_repo.py +``` + +It has no auto-fix mode. +""" +import inspect +import os +import re +import sys +import types +import warnings +from collections import OrderedDict +from difflib import get_close_matches +from pathlib import Path +from typing import List, Tuple + +from transformers import is_flax_available, is_tf_available, is_torch_available +from transformers.models.auto import get_values +from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES +from transformers.models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING_NAMES +from transformers.models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING_NAMES +from transformers.models.auto.processing_auto import PROCESSOR_MAPPING_NAMES +from transformers.models.auto.tokenization_auto import TOKENIZER_MAPPING_NAMES +from transformers.utils import ENV_VARS_TRUE_VALUES, direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_repo.py +PATH_TO_TRANSFORMERS = "src/transformers" +PATH_TO_TESTS = "tests" +PATH_TO_DOC = "docs/source/en" + +# Update this list with models that are supposed to be private. +PRIVATE_MODELS = [ + "AltRobertaModel", + "DPRSpanPredictor", + "LongT5Stack", + "RealmBertModel", + "T5Stack", + "MT5Stack", + "UMT5Stack", + "Pop2PianoStack", + "SwitchTransformersStack", + "TFDPRSpanPredictor", + "MaskFormerSwinModel", + "MaskFormerSwinPreTrainedModel", + "BridgeTowerTextModel", + "BridgeTowerVisionModel", + "Kosmos2TextModel", + "Kosmos2TextForCausalLM", + "Kosmos2VisionModel", + "SeamlessM4Tv2TextToUnitModel", + "SeamlessM4Tv2CodeHifiGan", + "SeamlessM4Tv2TextToUnitForConditionalGeneration", +] + +# Update this list for models that are not tested with a comment explaining the reason it should not be. +# Being in this list is an exception and should **not** be the rule. +IGNORE_NON_TESTED = PRIVATE_MODELS.copy() + [ + # models to ignore for not tested + "FuyuForCausalLM", # Not tested fort now + "InstructBlipQFormerModel", # Building part of bigger (tested) model. + "UMT5EncoderModel", # Building part of bigger (tested) model. + "Blip2QFormerModel", # Building part of bigger (tested) model. + "ErnieMForInformationExtraction", + "GraphormerDecoderHead", # Building part of bigger (tested) model. + "JukeboxVQVAE", # Building part of bigger (tested) model. + "JukeboxPrior", # Building part of bigger (tested) model. + "DecisionTransformerGPT2Model", # Building part of bigger (tested) model. + "SegformerDecodeHead", # Building part of bigger (tested) model. + "MgpstrModel", # Building part of bigger (tested) model. + "BertLMHeadModel", # Needs to be setup as decoder. + "MegatronBertLMHeadModel", # Building part of bigger (tested) model. + "RealmBertModel", # Building part of bigger (tested) model. + "RealmReader", # Not regular model. + "RealmScorer", # Not regular model. + "RealmForOpenQA", # Not regular model. + "ReformerForMaskedLM", # Needs to be setup as decoder. + "TFElectraMainLayer", # Building part of bigger (tested) model (should it be a TFPreTrainedModel ?) + "TFRobertaForMultipleChoice", # TODO: fix + "TFRobertaPreLayerNormForMultipleChoice", # TODO: fix + "SeparableConv1D", # Building part of bigger (tested) model. + "FlaxBartForCausalLM", # Building part of bigger (tested) model. + "FlaxBertForCausalLM", # Building part of bigger (tested) model. Tested implicitly through FlaxRobertaForCausalLM. + "OPTDecoderWrapper", + "TFSegformerDecodeHead", # Not a regular model. + "AltRobertaModel", # Building part of bigger (tested) model. + "BlipTextLMHeadModel", # No need to test it as it is tested by BlipTextVision models + "TFBlipTextLMHeadModel", # No need to test it as it is tested by BlipTextVision models + "BridgeTowerTextModel", # No need to test it as it is tested by BridgeTowerModel model. + "BridgeTowerVisionModel", # No need to test it as it is tested by BridgeTowerModel model. + "BarkCausalModel", # Building part of bigger (tested) model. + "BarkModel", # Does not have a forward signature - generation tested with integration tests. + "SeamlessM4TTextToUnitModel", # Building part of bigger (tested) model. + "SeamlessM4TCodeHifiGan", # Building part of bigger (tested) model. + "SeamlessM4TTextToUnitForConditionalGeneration", # Building part of bigger (tested) model. +] + +# Update this list with test files that don't have a tester with a `all_model_classes` variable and which don't +# trigger the common tests. +TEST_FILES_WITH_NO_COMMON_TESTS = [ + "models/decision_transformer/test_modeling_decision_transformer.py", + "models/camembert/test_modeling_camembert.py", + "models/mt5/test_modeling_flax_mt5.py", + "models/mbart/test_modeling_mbart.py", + "models/mt5/test_modeling_mt5.py", + "models/pegasus/test_modeling_pegasus.py", + "models/camembert/test_modeling_tf_camembert.py", + "models/mt5/test_modeling_tf_mt5.py", + "models/xlm_roberta/test_modeling_tf_xlm_roberta.py", + "models/xlm_roberta/test_modeling_flax_xlm_roberta.py", + "models/xlm_prophetnet/test_modeling_xlm_prophetnet.py", + "models/xlm_roberta/test_modeling_xlm_roberta.py", + "models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py", + "models/vision_text_dual_encoder/test_modeling_tf_vision_text_dual_encoder.py", + "models/vision_text_dual_encoder/test_modeling_flax_vision_text_dual_encoder.py", + "models/decision_transformer/test_modeling_decision_transformer.py", + "models/bark/test_modeling_bark.py", +] + +# Update this list for models that are not in any of the auto MODEL_XXX_MAPPING. Being in this list is an exception and +# should **not** be the rule. +IGNORE_NON_AUTO_CONFIGURED = PRIVATE_MODELS.copy() + [ + # models to ignore for model xxx mapping + "AlignTextModel", + "AlignVisionModel", + "ClapTextModel", + "ClapTextModelWithProjection", + "ClapAudioModel", + "ClapAudioModelWithProjection", + "Blip2ForConditionalGeneration", + "Blip2QFormerModel", + "Blip2VisionModel", + "ErnieMForInformationExtraction", + "GitVisionModel", + "GraphormerModel", + "GraphormerForGraphClassification", + "BlipForConditionalGeneration", + "BlipForImageTextRetrieval", + "BlipForQuestionAnswering", + "BlipVisionModel", + "BlipTextLMHeadModel", + "BlipTextModel", + "BrosSpadeEEForTokenClassification", + "BrosSpadeELForTokenClassification", + "TFBlipForConditionalGeneration", + "TFBlipForImageTextRetrieval", + "TFBlipForQuestionAnswering", + "TFBlipVisionModel", + "TFBlipTextLMHeadModel", + "TFBlipTextModel", + "Swin2SRForImageSuperResolution", + "BridgeTowerForImageAndTextRetrieval", + "BridgeTowerForMaskedLM", + "BridgeTowerForContrastiveLearning", + "CLIPSegForImageSegmentation", + "CLIPSegVisionModel", + "CLIPSegTextModel", + "EsmForProteinFolding", + "GPTSanJapaneseModel", + "TimeSeriesTransformerForPrediction", + "InformerForPrediction", + "AutoformerForPrediction", + "PatchTSTForPretraining", + "PatchTSTForPrediction", + "JukeboxVQVAE", + "JukeboxPrior", + "SamModel", + "DPTForDepthEstimation", + "DecisionTransformerGPT2Model", + "GLPNForDepthEstimation", + "ViltForImagesAndTextClassification", + "ViltForImageAndTextRetrieval", + "ViltForTokenClassification", + "ViltForMaskedLM", + "PerceiverForMultimodalAutoencoding", + "PerceiverForOpticalFlow", + "SegformerDecodeHead", + "TFSegformerDecodeHead", + "FlaxBeitForMaskedImageModeling", + "BeitForMaskedImageModeling", + "ChineseCLIPTextModel", + "ChineseCLIPVisionModel", + "CLIPTextModel", + "CLIPTextModelWithProjection", + "CLIPVisionModel", + "CLIPVisionModelWithProjection", + "ClvpForCausalLM", + "ClvpModel", + "GroupViTTextModel", + "GroupViTVisionModel", + "TFCLIPTextModel", + "TFCLIPVisionModel", + "TFGroupViTTextModel", + "TFGroupViTVisionModel", + "FlaxCLIPTextModel", + "FlaxCLIPTextModelWithProjection", + "FlaxCLIPVisionModel", + "FlaxWav2Vec2ForCTC", + "DetrForSegmentation", + "Pix2StructVisionModel", + "Pix2StructTextModel", + "Pix2StructForConditionalGeneration", + "ConditionalDetrForSegmentation", + "DPRReader", + "FlaubertForQuestionAnswering", + "FlavaImageCodebook", + "FlavaTextModel", + "FlavaImageModel", + "FlavaMultimodalModel", + "GPT2DoubleHeadsModel", + "GPTSw3DoubleHeadsModel", + "InstructBlipVisionModel", + "InstructBlipQFormerModel", + "LayoutLMForQuestionAnswering", + "LukeForMaskedLM", + "LukeForEntityClassification", + "LukeForEntityPairClassification", + "LukeForEntitySpanClassification", + "MgpstrModel", + "OpenAIGPTDoubleHeadsModel", + "OwlViTTextModel", + "OwlViTVisionModel", + "Owlv2TextModel", + "Owlv2VisionModel", + "OwlViTForObjectDetection", + "PatchTSMixerForPrediction", + "PatchTSMixerForPretraining", + "RagModel", + "RagSequenceForGeneration", + "RagTokenForGeneration", + "RealmEmbedder", + "RealmForOpenQA", + "RealmScorer", + "RealmReader", + "TFDPRReader", + "TFGPT2DoubleHeadsModel", + "TFLayoutLMForQuestionAnswering", + "TFOpenAIGPTDoubleHeadsModel", + "TFRagModel", + "TFRagSequenceForGeneration", + "TFRagTokenForGeneration", + "Wav2Vec2ForCTC", + "HubertForCTC", + "SEWForCTC", + "SEWDForCTC", + "XLMForQuestionAnswering", + "XLNetForQuestionAnswering", + "SeparableConv1D", + "VisualBertForRegionToPhraseAlignment", + "VisualBertForVisualReasoning", + "VisualBertForQuestionAnswering", + "VisualBertForMultipleChoice", + "TFWav2Vec2ForCTC", + "TFHubertForCTC", + "XCLIPVisionModel", + "XCLIPTextModel", + "AltCLIPTextModel", + "AltCLIPVisionModel", + "AltRobertaModel", + "TvltForAudioVisualClassification", + "BarkCausalModel", + "BarkCoarseModel", + "BarkFineModel", + "BarkSemanticModel", + "MusicgenModel", + "MusicgenForConditionalGeneration", + "SpeechT5ForSpeechToSpeech", + "SpeechT5ForTextToSpeech", + "SpeechT5HifiGan", + "VitMatteForImageMatting", + "SeamlessM4TTextToUnitModel", + "SeamlessM4TTextToUnitForConditionalGeneration", + "SeamlessM4TCodeHifiGan", + "SeamlessM4TForSpeechToSpeech", # no auto class for speech-to-speech + "TvpForVideoGrounding", + "SeamlessM4Tv2NARTextToUnitModel", + "SeamlessM4Tv2NARTextToUnitForConditionalGeneration", + "SeamlessM4Tv2CodeHifiGan", + "SeamlessM4Tv2ForSpeechToSpeech", # no auto class for speech-to-speech +] + +# DO NOT edit this list! +# (The corresponding pytorch objects should never have been in the main `__init__`, but it's too late to remove) +OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK = [ + "FlaxBertLayer", + "FlaxBigBirdLayer", + "FlaxRoFormerLayer", + "TFBertLayer", + "TFLxmertEncoder", + "TFLxmertXLayer", + "TFMPNetLayer", + "TFMobileBertLayer", + "TFSegformerLayer", + "TFViTMAELayer", +] + +# Update this list for models that have multiple model types for the same model doc. +MODEL_TYPE_TO_DOC_MAPPING = OrderedDict( + [ + ("data2vec-text", "data2vec"), + ("data2vec-audio", "data2vec"), + ("data2vec-vision", "data2vec"), + ("donut-swin", "donut"), + ] +) + + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + + +def check_missing_backends(): + """ + Checks if all backends are installed (otherwise the check of this script is incomplete). Will error in the CI if + that's not the case but only throw a warning for users running this. + """ + missing_backends = [] + if not is_torch_available(): + missing_backends.append("PyTorch") + if not is_tf_available(): + missing_backends.append("TensorFlow") + if not is_flax_available(): + missing_backends.append("Flax") + if len(missing_backends) > 0: + missing = ", ".join(missing_backends) + if os.getenv("TRANSFORMERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES: + raise Exception( + "Full repo consistency checks require all backends to be installed (with `pip install -e .[dev]` in the " + f"Transformers repo, the following are missing: {missing}." + ) + else: + warnings.warn( + "Full repo consistency checks require all backends to be installed (with `pip install -e .[dev]` in the " + f"Transformers repo, the following are missing: {missing}. While it's probably fine as long as you " + "didn't make any change in one of those backends modeling files, you should probably execute the " + "command above to be on the safe side." + ) + + +def check_model_list(): + """ + Checks the model listed as subfolders of `models` match the models available in `transformers.models`. + """ + # Get the models from the directory structure of `src/transformers/models/` + models_dir = os.path.join(PATH_TO_TRANSFORMERS, "models") + _models = [] + for model in os.listdir(models_dir): + if model == "deprecated": + continue + model_dir = os.path.join(models_dir, model) + if os.path.isdir(model_dir) and "__init__.py" in os.listdir(model_dir): + _models.append(model) + + # Get the models in the submodule `transformers.models` + models = [model for model in dir(transformers.models) if not model.startswith("__")] + + missing_models = sorted(set(_models).difference(models)) + if missing_models: + raise Exception( + f"The following models should be included in {models_dir}/__init__.py: {','.join(missing_models)}." + ) + + +# If some modeling modules should be ignored for all checks, they should be added in the nested list +# _ignore_modules of this function. +def get_model_modules() -> List[str]: + """Get all the model modules inside the transformers library (except deprecated models).""" + _ignore_modules = [ + "modeling_auto", + "modeling_encoder_decoder", + "modeling_marian", + "modeling_mmbt", + "modeling_outputs", + "modeling_retribert", + "modeling_utils", + "modeling_flax_auto", + "modeling_flax_encoder_decoder", + "modeling_flax_utils", + "modeling_speech_encoder_decoder", + "modeling_flax_speech_encoder_decoder", + "modeling_flax_vision_encoder_decoder", + "modeling_timm_backbone", + "modeling_tf_auto", + "modeling_tf_encoder_decoder", + "modeling_tf_outputs", + "modeling_tf_pytorch_utils", + "modeling_tf_utils", + "modeling_tf_vision_encoder_decoder", + "modeling_vision_encoder_decoder", + ] + modules = [] + for model in dir(transformers.models): + # There are some magic dunder attributes in the dir, we ignore them + if model == "deprecated" or model.startswith("__"): + continue + + model_module = getattr(transformers.models, model) + for submodule in dir(model_module): + if submodule.startswith("modeling") and submodule not in _ignore_modules: + modeling_module = getattr(model_module, submodule) + if inspect.ismodule(modeling_module): + modules.append(modeling_module) + return modules + + +def get_models(module: types.ModuleType, include_pretrained: bool = False) -> List[Tuple[str, type]]: + """ + Get the objects in a module that are models. + + Args: + module (`types.ModuleType`): + The module from which we are extracting models. + include_pretrained (`bool`, *optional*, defaults to `False`): + Whether or not to include the `PreTrainedModel` subclass (like `BertPreTrainedModel`) or not. + + Returns: + List[Tuple[str, type]]: List of models as tuples (class name, actual class). + """ + models = [] + model_classes = (transformers.PreTrainedModel, transformers.TFPreTrainedModel, transformers.FlaxPreTrainedModel) + for attr_name in dir(module): + if not include_pretrained and ("Pretrained" in attr_name or "PreTrained" in attr_name): + continue + attr = getattr(module, attr_name) + if isinstance(attr, type) and issubclass(attr, model_classes) and attr.__module__ == module.__name__: + models.append((attr_name, attr)) + return models + + +def is_building_block(model: str) -> bool: + """ + Returns `True` if a model is a building block part of a bigger model. + """ + if model.endswith("Wrapper"): + return True + if model.endswith("Encoder"): + return True + if model.endswith("Decoder"): + return True + if model.endswith("Prenet"): + return True + + +def is_a_private_model(model: str) -> bool: + """Returns `True` if the model should not be in the main init.""" + if model in PRIVATE_MODELS: + return True + return is_building_block(model) + + +def check_models_are_in_init(): + """Checks all models defined in the library are in the main init.""" + models_not_in_init = [] + dir_transformers = dir(transformers) + for module in get_model_modules(): + models_not_in_init += [ + model[0] for model in get_models(module, include_pretrained=True) if model[0] not in dir_transformers + ] + + # Remove private models + models_not_in_init = [model for model in models_not_in_init if not is_a_private_model(model)] + if len(models_not_in_init) > 0: + raise Exception(f"The following models should be in the main init: {','.join(models_not_in_init)}.") + + +# If some test_modeling files should be ignored when checking models are all tested, they should be added in the +# nested list _ignore_files of this function. +def get_model_test_files() -> List[str]: + """ + Get the model test files. + + Returns: + `List[str]`: The list of test files. The returned files will NOT contain the `tests` (i.e. `PATH_TO_TESTS` + defined in this script). They will be considered as paths relative to `tests`. A caller has to use + `os.path.join(PATH_TO_TESTS, ...)` to access the files. + """ + + _ignore_files = [ + "test_modeling_common", + "test_modeling_encoder_decoder", + "test_modeling_flax_encoder_decoder", + "test_modeling_flax_speech_encoder_decoder", + "test_modeling_marian", + "test_modeling_tf_common", + "test_modeling_tf_encoder_decoder", + ] + test_files = [] + model_test_root = os.path.join(PATH_TO_TESTS, "models") + model_test_dirs = [] + for x in os.listdir(model_test_root): + x = os.path.join(model_test_root, x) + if os.path.isdir(x): + model_test_dirs.append(x) + + for target_dir in [PATH_TO_TESTS] + model_test_dirs: + for file_or_dir in os.listdir(target_dir): + path = os.path.join(target_dir, file_or_dir) + if os.path.isfile(path): + filename = os.path.split(path)[-1] + if "test_modeling" in filename and os.path.splitext(filename)[0] not in _ignore_files: + file = os.path.join(*path.split(os.sep)[1:]) + test_files.append(file) + + return test_files + + +# This is a bit hacky but I didn't find a way to import the test_file as a module and read inside the tester class +# for the all_model_classes variable. +def find_tested_models(test_file: str) -> List[str]: + """ + Parse the content of test_file to detect what's in `all_model_classes`. This detects the models that inherit from + the common test class. + + Args: + test_file (`str`): The path to the test file to check + + Returns: + `List[str]`: The list of models tested in that file. + """ + with open(os.path.join(PATH_TO_TESTS, test_file), "r", encoding="utf-8", newline="\n") as f: + content = f.read() + all_models = re.findall(r"all_model_classes\s+=\s+\(\s*\(([^\)]*)\)", content) + # Check with one less parenthesis as well + all_models += re.findall(r"all_model_classes\s+=\s+\(([^\)]*)\)", content) + if len(all_models) > 0: + model_tested = [] + for entry in all_models: + for line in entry.split(","): + name = line.strip() + if len(name) > 0: + model_tested.append(name) + return model_tested + + +def should_be_tested(model_name: str) -> bool: + """ + Whether or not a model should be tested. + """ + if model_name in IGNORE_NON_TESTED: + return False + return not is_building_block(model_name) + + +def check_models_are_tested(module: types.ModuleType, test_file: str) -> List[str]: + """Check models defined in a module are all tested in a given file. + + Args: + module (`types.ModuleType`): The module in which we get the models. + test_file (`str`): The path to the file where the module is tested. + + Returns: + `List[str]`: The list of error messages corresponding to models not tested. + """ + # XxxPreTrainedModel are not tested + defined_models = get_models(module) + tested_models = find_tested_models(test_file) + if tested_models is None: + if test_file.replace(os.path.sep, "/") in TEST_FILES_WITH_NO_COMMON_TESTS: + return + return [ + f"{test_file} should define `all_model_classes` to apply common tests to the models it tests. " + + "If this intentional, add the test filename to `TEST_FILES_WITH_NO_COMMON_TESTS` in the file " + + "`utils/check_repo.py`." + ] + failures = [] + for model_name, _ in defined_models: + if model_name not in tested_models and should_be_tested(model_name): + failures.append( + f"{model_name} is defined in {module.__name__} but is not tested in " + + f"{os.path.join(PATH_TO_TESTS, test_file)}. Add it to the all_model_classes in that file." + + "If common tests should not applied to that model, add its name to `IGNORE_NON_TESTED`" + + "in the file `utils/check_repo.py`." + ) + return failures + + +def check_all_models_are_tested(): + """Check all models are properly tested.""" + modules = get_model_modules() + test_files = get_model_test_files() + failures = [] + for module in modules: + # Matches a module to its test file. + test_file = [file for file in test_files if f"test_{module.__name__.split('.')[-1]}.py" in file] + if len(test_file) == 0: + failures.append(f"{module.__name__} does not have its corresponding test file {test_file}.") + elif len(test_file) > 1: + failures.append(f"{module.__name__} has several test files: {test_file}.") + else: + test_file = test_file[0] + new_failures = check_models_are_tested(module, test_file) + if new_failures is not None: + failures += new_failures + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def get_all_auto_configured_models() -> List[str]: + """Return the list of all models in at least one auto class.""" + result = set() # To avoid duplicates we concatenate all model classes in a set. + if is_torch_available(): + for attr_name in dir(transformers.models.auto.modeling_auto): + if attr_name.startswith("MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_auto, attr_name))) + if is_tf_available(): + for attr_name in dir(transformers.models.auto.modeling_tf_auto): + if attr_name.startswith("TF_MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_tf_auto, attr_name))) + if is_flax_available(): + for attr_name in dir(transformers.models.auto.modeling_flax_auto): + if attr_name.startswith("FLAX_MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_flax_auto, attr_name))) + return list(result) + + +def ignore_unautoclassed(model_name: str) -> bool: + """Rules to determine if a model should be in an auto class.""" + # Special white list + if model_name in IGNORE_NON_AUTO_CONFIGURED: + return True + # Encoder and Decoder should be ignored + if "Encoder" in model_name or "Decoder" in model_name: + return True + return False + + +def check_models_are_auto_configured(module: types.ModuleType, all_auto_models: List[str]) -> List[str]: + """ + Check models defined in module are each in an auto class. + + Args: + module (`types.ModuleType`): + The module in which we get the models. + all_auto_models (`List[str]`): + The list of all models in an auto class (as obtained with `get_all_auto_configured_models()`). + + Returns: + `List[str]`: The list of error messages corresponding to models not tested. + """ + defined_models = get_models(module) + failures = [] + for model_name, _ in defined_models: + if model_name not in all_auto_models and not ignore_unautoclassed(model_name): + failures.append( + f"{model_name} is defined in {module.__name__} but is not present in any of the auto mapping. " + "If that is intended behavior, add its name to `IGNORE_NON_AUTO_CONFIGURED` in the file " + "`utils/check_repo.py`." + ) + return failures + + +def check_all_models_are_auto_configured(): + """Check all models are each in an auto class.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + modules = get_model_modules() + all_auto_models = get_all_auto_configured_models() + failures = [] + for module in modules: + new_failures = check_models_are_auto_configured(module, all_auto_models) + if new_failures is not None: + failures += new_failures + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_object_names_being_defined(): + """Check all names defined in auto (name) mappings exist in the library.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + mappings_to_check = { + "TOKENIZER_MAPPING_NAMES": TOKENIZER_MAPPING_NAMES, + "IMAGE_PROCESSOR_MAPPING_NAMES": IMAGE_PROCESSOR_MAPPING_NAMES, + "FEATURE_EXTRACTOR_MAPPING_NAMES": FEATURE_EXTRACTOR_MAPPING_NAMES, + "PROCESSOR_MAPPING_NAMES": PROCESSOR_MAPPING_NAMES, + } + + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name, mapping in mappings_to_check.items(): + for _, class_names in mapping.items(): + if not isinstance(class_names, tuple): + class_names = (class_names,) + for class_name in class_names: + if class_name is None: + continue + # dummy object is accepted + if not hasattr(transformers, class_name): + # If the class name is in a model name mapping, let's not check if there is a definition in any modeling + # module, if it's a private model defined in this file. + if name.endswith("MODEL_MAPPING_NAMES") and is_a_private_model(class_name): + continue + failures.append( + f"`{class_name}` appears in the mapping `{name}` but it is not defined in the library." + ) + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_mapping_names_in_config_mapping_names(): + """Check all keys defined in auto mappings (mappings of names) appear in `CONFIG_MAPPING_NAMES`.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + # `TOKENIZER_PROCESSOR_MAPPING_NAMES` and `AutoTokenizer` is special, and don't need to follow the rule. + mappings_to_check = { + "IMAGE_PROCESSOR_MAPPING_NAMES": IMAGE_PROCESSOR_MAPPING_NAMES, + "FEATURE_EXTRACTOR_MAPPING_NAMES": FEATURE_EXTRACTOR_MAPPING_NAMES, + "PROCESSOR_MAPPING_NAMES": PROCESSOR_MAPPING_NAMES, + } + + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name, mapping in mappings_to_check.items(): + for model_type in mapping: + if model_type not in CONFIG_MAPPING_NAMES: + failures.append( + f"`{model_type}` appears in the mapping `{name}` but it is not defined in the keys of " + "`CONFIG_MAPPING_NAMES`." + ) + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_mappings_importable(): + """Check all auto mappings can be imported.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + mappings_to_check = {} + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name in mappings_to_check: + name = name.replace("_MAPPING_NAMES", "_MAPPING") + if not hasattr(transformers, name): + failures.append(f"`{name}`") + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_objects_being_equally_in_main_init(): + """ + Check if a (TensorFlow or Flax) object is in the main __init__ iif its counterpart in PyTorch is. + """ + attrs = dir(transformers) + + failures = [] + for attr in attrs: + obj = getattr(transformers, attr) + if not hasattr(obj, "__module__") or "models.deprecated" in obj.__module__: + continue + + module_path = obj.__module__ + module_name = module_path.split(".")[-1] + module_dir = ".".join(module_path.split(".")[:-1]) + if ( + module_name.startswith("modeling_") + and not module_name.startswith("modeling_tf_") + and not module_name.startswith("modeling_flax_") + ): + parent_module = sys.modules[module_dir] + + frameworks = [] + if is_tf_available(): + frameworks.append("TF") + if is_flax_available(): + frameworks.append("Flax") + + for framework in frameworks: + other_module_path = module_path.replace("modeling_", f"modeling_{framework.lower()}_") + if os.path.isfile("src/" + other_module_path.replace(".", "/") + ".py"): + other_module_name = module_name.replace("modeling_", f"modeling_{framework.lower()}_") + other_module = getattr(parent_module, other_module_name) + if hasattr(other_module, f"{framework}{attr}"): + if not hasattr(transformers, f"{framework}{attr}"): + if f"{framework}{attr}" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK: + failures.append(f"{framework}{attr}") + if hasattr(other_module, f"{framework}_{attr}"): + if not hasattr(transformers, f"{framework}_{attr}"): + if f"{framework}_{attr}" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK: + failures.append(f"{framework}_{attr}") + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +_re_decorator = re.compile(r"^\s*@(\S+)\s+$") + + +def check_decorator_order(filename: str) -> List[int]: + """ + Check that in a given test file, the slow decorator is always last. + + Args: + filename (`str`): The path to a test file to check. + + Returns: + `List[int]`: The list of failures as a list of indices where there are problems. + """ + with open(filename, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + decorator_before = None + errors = [] + for i, line in enumerate(lines): + search = _re_decorator.search(line) + if search is not None: + decorator_name = search.groups()[0] + if decorator_before is not None and decorator_name.startswith("parameterized"): + errors.append(i) + decorator_before = decorator_name + elif decorator_before is not None: + decorator_before = None + return errors + + +def check_all_decorator_order(): + """Check that in all test files, the slow decorator is always last.""" + errors = [] + for fname in os.listdir(PATH_TO_TESTS): + if fname.endswith(".py"): + filename = os.path.join(PATH_TO_TESTS, fname) + new_errors = check_decorator_order(filename) + errors += [f"- {filename}, line {i}" for i in new_errors] + if len(errors) > 0: + msg = "\n".join(errors) + raise ValueError( + "The parameterized decorator (and its variants) should always be first, but this is not the case in the" + f" following files:\n{msg}" + ) + + +def find_all_documented_objects() -> List[str]: + """ + Parse the content of all doc files to detect which classes and functions it documents. + + Returns: + `List[str]`: The list of all object names being documented. + """ + documented_obj = [] + for doc_file in Path(PATH_TO_DOC).glob("**/*.rst"): + with open(doc_file, "r", encoding="utf-8", newline="\n") as f: + content = f.read() + raw_doc_objs = re.findall(r"(?:autoclass|autofunction):: transformers.(\S+)\s+", content) + documented_obj += [obj.split(".")[-1] for obj in raw_doc_objs] + for doc_file in Path(PATH_TO_DOC).glob("**/*.md"): + with open(doc_file, "r", encoding="utf-8", newline="\n") as f: + content = f.read() + raw_doc_objs = re.findall(r"\[\[autodoc\]\]\s+(\S+)\s+", content) + documented_obj += [obj.split(".")[-1] for obj in raw_doc_objs] + return documented_obj + + +# One good reason for not being documented is to be deprecated. Put in this list deprecated objects. +DEPRECATED_OBJECTS = [ + "AutoModelWithLMHead", + "BartPretrainedModel", + "DataCollator", + "DataCollatorForSOP", + "GlueDataset", + "GlueDataTrainingArguments", + "LineByLineTextDataset", + "LineByLineWithRefDataset", + "LineByLineWithSOPTextDataset", + "PretrainedBartModel", + "PretrainedFSMTModel", + "SingleSentenceClassificationProcessor", + "SquadDataTrainingArguments", + "SquadDataset", + "SquadExample", + "SquadFeatures", + "SquadV1Processor", + "SquadV2Processor", + "TFAutoModelWithLMHead", + "TFBartPretrainedModel", + "TextDataset", + "TextDatasetForNextSentencePrediction", + "Wav2Vec2ForMaskedLM", + "Wav2Vec2Tokenizer", + "glue_compute_metrics", + "glue_convert_examples_to_features", + "glue_output_modes", + "glue_processors", + "glue_tasks_num_labels", + "squad_convert_examples_to_features", + "xnli_compute_metrics", + "xnli_output_modes", + "xnli_processors", + "xnli_tasks_num_labels", + "TFTrainer", + "TFTrainingArguments", +] + +# Exceptionally, some objects should not be documented after all rules passed. +# ONLY PUT SOMETHING IN THIS LIST AS A LAST RESORT! +UNDOCUMENTED_OBJECTS = [ + "AddedToken", # This is a tokenizers class. + "BasicTokenizer", # Internal, should never have been in the main init. + "CharacterTokenizer", # Internal, should never have been in the main init. + "DPRPretrainedReader", # Like an Encoder. + "DummyObject", # Just picked by mistake sometimes. + "MecabTokenizer", # Internal, should never have been in the main init. + "ModelCard", # Internal type. + "SqueezeBertModule", # Internal building block (should have been called SqueezeBertLayer) + "TFDPRPretrainedReader", # Like an Encoder. + "TransfoXLCorpus", # Internal type. + "WordpieceTokenizer", # Internal, should never have been in the main init. + "absl", # External module + "add_end_docstrings", # Internal, should never have been in the main init. + "add_start_docstrings", # Internal, should never have been in the main init. + "convert_tf_weight_name_to_pt_weight_name", # Internal used to convert model weights + "logger", # Internal logger + "logging", # External module + "requires_backends", # Internal function + "AltRobertaModel", # Internal module +] + +# This list should be empty. Objects in it should get their own doc page. +SHOULD_HAVE_THEIR_OWN_PAGE = [ + # Benchmarks + "PyTorchBenchmark", + "PyTorchBenchmarkArguments", + "TensorFlowBenchmark", + "TensorFlowBenchmarkArguments", + "AutoBackbone", + "BeitBackbone", + "BitBackbone", + "ConvNextBackbone", + "ConvNextV2Backbone", + "DinatBackbone", + "Dinov2Backbone", + "FocalNetBackbone", + "MaskFormerSwinBackbone", + "MaskFormerSwinConfig", + "MaskFormerSwinModel", + "NatBackbone", + "ResNetBackbone", + "SwinBackbone", + "TimmBackbone", + "TimmBackboneConfig", + "VitDetBackbone", +] + + +def ignore_undocumented(name: str) -> bool: + """Rules to determine if `name` should be undocumented (returns `True` if it should not be documented).""" + # NOT DOCUMENTED ON PURPOSE. + # Constants uppercase are not documented. + if name.isupper(): + return True + # PreTrainedModels / Encoders / Decoders / Layers / Embeddings / Attention are not documented. + if ( + name.endswith("PreTrainedModel") + or name.endswith("Decoder") + or name.endswith("Encoder") + or name.endswith("Layer") + or name.endswith("Embeddings") + or name.endswith("Attention") + ): + return True + # Submodules are not documented. + if os.path.isdir(os.path.join(PATH_TO_TRANSFORMERS, name)) or os.path.isfile( + os.path.join(PATH_TO_TRANSFORMERS, f"{name}.py") + ): + return True + # All load functions are not documented. + if name.startswith("load_tf") or name.startswith("load_pytorch"): + return True + # is_xxx_available functions are not documented. + if name.startswith("is_") and name.endswith("_available"): + return True + # Deprecated objects are not documented. + if name in DEPRECATED_OBJECTS or name in UNDOCUMENTED_OBJECTS: + return True + # MMBT model does not really work. + if name.startswith("MMBT"): + return True + if name in SHOULD_HAVE_THEIR_OWN_PAGE: + return True + return False + + +def check_all_objects_are_documented(): + """Check all models are properly documented.""" + documented_objs = find_all_documented_objects() + modules = transformers._modules + objects = [c for c in dir(transformers) if c not in modules and not c.startswith("_")] + undocumented_objs = [c for c in objects if c not in documented_objs and not ignore_undocumented(c)] + if len(undocumented_objs) > 0: + raise Exception( + "The following objects are in the public init so should be documented:\n - " + + "\n - ".join(undocumented_objs) + ) + check_docstrings_are_in_md() + check_model_type_doc_match() + + +def check_model_type_doc_match(): + """Check all doc pages have a corresponding model type.""" + model_doc_folder = Path(PATH_TO_DOC) / "model_doc" + model_docs = [m.stem for m in model_doc_folder.glob("*.md")] + + model_types = list(transformers.models.auto.configuration_auto.MODEL_NAMES_MAPPING.keys()) + model_types = [MODEL_TYPE_TO_DOC_MAPPING[m] if m in MODEL_TYPE_TO_DOC_MAPPING else m for m in model_types] + + errors = [] + for m in model_docs: + if m not in model_types and m != "auto": + close_matches = get_close_matches(m, model_types) + error_message = f"{m} is not a proper model identifier." + if len(close_matches) > 0: + close_matches = "/".join(close_matches) + error_message += f" Did you mean {close_matches}?" + errors.append(error_message) + + if len(errors) > 0: + raise ValueError( + "Some model doc pages do not match any existing model type:\n" + + "\n".join(errors) + + "\nYou can add any missing model type to the `MODEL_NAMES_MAPPING` constant in " + "models/auto/configuration_auto.py." + ) + + +# Re pattern to catch :obj:`xx`, :class:`xx`, :func:`xx` or :meth:`xx`. +_re_rst_special_words = re.compile(r":(?:obj|func|class|meth):`([^`]+)`") +# Re pattern to catch things between double backquotes. +_re_double_backquotes = re.compile(r"(^|[^`])``([^`]+)``([^`]|$)") +# Re pattern to catch example introduction. +_re_rst_example = re.compile(r"^\s*Example.*::\s*$", flags=re.MULTILINE) + + +def is_rst_docstring(docstring: str) -> True: + """ + Returns `True` if `docstring` is written in rst. + """ + if _re_rst_special_words.search(docstring) is not None: + return True + if _re_double_backquotes.search(docstring) is not None: + return True + if _re_rst_example.search(docstring) is not None: + return True + return False + + +def check_docstrings_are_in_md(): + """Check all docstrings are written in md and nor rst.""" + files_with_rst = [] + for file in Path(PATH_TO_TRANSFORMERS).glob("**/*.py"): + with open(file, encoding="utf-8") as f: + code = f.read() + docstrings = code.split('"""') + + for idx, docstring in enumerate(docstrings): + if idx % 2 == 0 or not is_rst_docstring(docstring): + continue + files_with_rst.append(file) + break + + if len(files_with_rst) > 0: + raise ValueError( + "The following files have docstrings written in rst:\n" + + "\n".join([f"- {f}" for f in files_with_rst]) + + "\nTo fix this run `doc-builder convert path_to_py_file` after installing `doc-builder`\n" + "(`pip install git+https://github.com/huggingface/doc-builder`)" + ) + + +def check_deprecated_constant_is_up_to_date(): + """ + Check if the constant `DEPRECATED_MODELS` in `models/auto/configuration_auto.py` is up to date. + """ + deprecated_folder = os.path.join(PATH_TO_TRANSFORMERS, "models", "deprecated") + deprecated_models = [m for m in os.listdir(deprecated_folder) if not m.startswith("_")] + + constant_to_check = transformers.models.auto.configuration_auto.DEPRECATED_MODELS + message = [] + missing_models = sorted(set(deprecated_models) - set(constant_to_check)) + if len(missing_models) != 0: + missing_models = ", ".join(missing_models) + message.append( + "The following models are in the deprecated folder, make sure to add them to `DEPRECATED_MODELS` in " + f"`models/auto/configuration_auto.py`: {missing_models}." + ) + + extra_models = sorted(set(constant_to_check) - set(deprecated_models)) + if len(extra_models) != 0: + extra_models = ", ".join(extra_models) + message.append( + "The following models are in the `DEPRECATED_MODELS` constant but not in the deprecated folder. Either " + f"remove them from the constant or move to the deprecated folder: {extra_models}." + ) + + if len(message) > 0: + raise Exception("\n".join(message)) + + +def check_repo_quality(): + """Check all models are properly tested and documented.""" + print("Checking all models are included.") + check_model_list() + print("Checking all models are public.") + check_models_are_in_init() + print("Checking all models are properly tested.") + check_all_decorator_order() + check_all_models_are_tested() + print("Checking all objects are properly documented.") + check_all_objects_are_documented() + print("Checking all models are in at least one auto class.") + check_all_models_are_auto_configured() + print("Checking all names in auto name mappings are defined.") + check_all_auto_object_names_being_defined() + print("Checking all keys in auto name mappings are defined in `CONFIG_MAPPING_NAMES`.") + check_all_auto_mapping_names_in_config_mapping_names() + print("Checking all auto mappings could be imported.") + check_all_auto_mappings_importable() + print("Checking all objects are equally (across frameworks) in the main __init__.") + check_objects_being_equally_in_main_init() + print("Checking the DEPRECATED_MODELS constant is up to date.") + check_deprecated_constant_is_up_to_date() + + +if __name__ == "__main__": + check_repo_quality() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_self_hosted_runner.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_self_hosted_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..7439bd270effcc206d79e9a7bcf97fe8ad939b63 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_self_hosted_runner.py @@ -0,0 +1,52 @@ +import argparse +import json +import subprocess + + +def get_runner_status(target_runners, token): + offline_runners = [] + + cmd = ( + f'curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"' + " https://api.github.com/repos/huggingface/transformers/actions/runners" + ) + output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE) + o = output.stdout.decode("utf-8") + status = json.loads(o) + + runners = status["runners"] + for runner in runners: + if runner["name"] in target_runners: + if runner["status"] == "offline": + offline_runners.append(runner) + + # save the result so we can report them on Slack + with open("offline_runners.txt", "w") as fp: + fp.write(json.dumps(offline_runners)) + + if len(offline_runners) > 0: + failed = "\n".join([x["name"] for x in offline_runners]) + raise ValueError(f"The following runners are offline:\n{failed}") + + +if __name__ == "__main__": + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument( + "--target_runners", + default=None, + type=list_str, + required=True, + help="Comma-separated list of runners to check status.", + ) + + parser.add_argument( + "--token", default=None, type=str, required=True, help="A token that has actions:read permission." + ) + args = parser.parse_args() + + get_runner_status(args.target_runners, args.token) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_table.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_table.py new file mode 100644 index 0000000000000000000000000000000000000000..6eec4754032e8eb23cf5bec4ad1ed0ce0c422711 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_table.py @@ -0,0 +1,293 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. +""" +Utility that checks the big table in the file docs/source/en/index.md and potentially updates it. + +Use from the root of the repo with: + +```bash +python utils/check_inits.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`). + +To auto-fix issues run: + +```bash +python utils/check_inits.py --fix_and_overwrite +``` + +which is used by `make fix-copies`. +""" +import argparse +import collections +import os +import re +from typing import List + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_table.py +TRANSFORMERS_PATH = "src/transformers" +PATH_TO_DOCS = "docs/source/en" +REPO_PATH = "." + + +def _find_text_in_file(filename: str, start_prompt: str, end_prompt: str) -> str: + """ + Find the text in filename between two prompts. + + Args: + filename (`str`): The file to search into. + start_prompt (`str`): A string to look for at the start of the content searched. + end_prompt (`str`): A string that will mark the end of the content to look for. + + Returns: + `str`: The content between the prompts. + """ + with open(filename, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Find the start prompt. + start_index = 0 + while not lines[start_index].startswith(start_prompt): + start_index += 1 + start_index += 1 + + # Now go until the end prompt. + end_index = start_index + while not lines[end_index].startswith(end_prompt): + end_index += 1 + end_index -= 1 + + while len(lines[start_index]) <= 1: + start_index += 1 + while len(lines[end_index]) <= 1: + end_index -= 1 + end_index += 1 + return "".join(lines[start_index:end_index]), start_index, end_index, lines + + +# Regexes that match TF/Flax/PT model names. Add here suffixes that are used to identify models, separated by | +_re_tf_models = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") +_re_flax_models = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") +# Will match any TF or Flax model too so need to be in an else branch after the two previous regexes. +_re_pt_models = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") + + +# This is to make sure the transformers module imported is the one in the repo. +transformers_module = direct_transformers_import(TRANSFORMERS_PATH) + + +def camel_case_split(identifier: str) -> List[str]: + """ + Split a camel-cased name into words. + + Args: + identifier (`str`): The camel-cased name to parse. + + Returns: + `List[str]`: The list of words in the identifier (as seprated by capital letters). + + Example: + + ```py + >>> camel_case_split("CamelCasedClass") + ["Camel", "Cased", "Class"] + ``` + """ + # Regex thanks to https://stackoverflow.com/questions/29916065/how-to-do-camelcase-split-in-python + matches = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier) + return [m.group(0) for m in matches] + + +def _center_text(text: str, width: int) -> str: + """ + Utility that will add spaces on the left and right of a text to make it centered for a given width. + + Args: + text (`str`): The text to center. + width (`int`): The desired length of the result. + + Returns: + `str`: A text of length `width` with the original `text` in the middle. + """ + text_length = 2 if text == "✅" or text == "❌" else len(text) + left_indent = (width - text_length) // 2 + right_indent = width - text_length - left_indent + return " " * left_indent + text + " " * right_indent + + +SPECIAL_MODEL_NAME_LINK_MAPPING = { + "Data2VecAudio": "[Data2VecAudio](model_doc/data2vec)", + "Data2VecText": "[Data2VecText](model_doc/data2vec)", + "Data2VecVision": "[Data2VecVision](model_doc/data2vec)", + "DonutSwin": "[DonutSwin](model_doc/donut)", +} + +MODEL_NAMES_WITH_SAME_CONFIG = { + "BARThez": "BART", + "BARTpho": "BART", + "BertJapanese": "BERT", + "BERTweet": "BERT", + "BORT": "BERT", + "ByT5": "T5", + "CPM": "OpenAI GPT-2", + "DePlot": "Pix2Struct", + "DialoGPT": "OpenAI GPT-2", + "DiT": "BEiT", + "FLAN-T5": "T5", + "FLAN-UL2": "T5", + "HerBERT": "BERT", + "LayoutXLM": "LayoutLMv2", + "Llama2": "LLaMA", + "MADLAD-400": "T5", + "MatCha": "Pix2Struct", + "mBART-50": "mBART", + "Megatron-GPT2": "OpenAI GPT-2", + "mLUKE": "LUKE", + "MMS": "Wav2Vec2", + "NLLB": "M2M100", + "PhoBERT": "BERT", + "T5v1.1": "T5", + "TAPEX": "BART", + "UL2": "T5", + "Wav2Vec2Phoneme": "Wav2Vec2", + "XLM-V": "XLM-RoBERTa", + "XLS-R": "Wav2Vec2", + "XLSR-Wav2Vec2": "Wav2Vec2", +} +MODEL_NAMES_TO_IGNORE = ["CLIPVisionModel"] + + +def get_model_table_from_auto_modules() -> str: + """ + Generates an up-to-date model table from the content of the auto modules. + """ + # Dictionary model names to config. + config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES + model_name_to_config = { + name: config_maping_names[code] + for code, name in transformers_module.MODEL_NAMES_MAPPING.items() + if code in config_maping_names + } + model_name_to_prefix = {name: config.replace("Config", "") for name, config in model_name_to_config.items()} + + # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. + pt_models = collections.defaultdict(bool) + tf_models = collections.defaultdict(bool) + flax_models = collections.defaultdict(bool) + + # Let's lookup through all transformers object (once). + for attr_name in dir(transformers_module): + lookup_dict = None + if _re_tf_models.match(attr_name) is not None: + lookup_dict = tf_models + attr_name = _re_tf_models.match(attr_name).groups()[0] + elif _re_flax_models.match(attr_name) is not None: + lookup_dict = flax_models + attr_name = _re_flax_models.match(attr_name).groups()[0] + elif _re_pt_models.match(attr_name) is not None: + lookup_dict = pt_models + attr_name = _re_pt_models.match(attr_name).groups()[0] + + if lookup_dict is not None: + while len(attr_name) > 0: + if attr_name in model_name_to_prefix.values(): + lookup_dict[attr_name] = True + break + # Try again after removing the last word in the name + attr_name = "".join(camel_case_split(attr_name)[:-1]) + + # Let's build that table! + model_names = list(model_name_to_config.keys()) + list(MODEL_NAMES_WITH_SAME_CONFIG.keys()) + + # model name to doc link mapping + model_names_mapping = transformers_module.models.auto.configuration_auto.MODEL_NAMES_MAPPING + model_name_to_link_mapping = {value: f"[{value}](model_doc/{key})" for key, value in model_names_mapping.items()} + # update mapping with special model names + model_name_to_link_mapping = { + k: SPECIAL_MODEL_NAME_LINK_MAPPING[k] if k in SPECIAL_MODEL_NAME_LINK_MAPPING else v + for k, v in model_name_to_link_mapping.items() + } + + # MaskFormerSwin and TimmBackbone are backbones and so not meant to be loaded and used on their own. Instead, they define architectures which can be loaded using the AutoBackbone API. + names_to_exclude = ["MaskFormerSwin", "TimmBackbone", "Speech2Text2"] + model_names = [name for name in model_names if name not in names_to_exclude] + model_names.sort(key=str.lower) + + columns = ["Model", "PyTorch support", "TensorFlow support", "Flax Support"] + # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). + + widths = [len(c) + 2 for c in columns] + widths[0] = max([len(doc_link) for doc_link in model_name_to_link_mapping.values()]) + 2 + + # Build the table per se + table = "|" + "|".join([_center_text(c, w) for c, w in zip(columns, widths)]) + "|\n" + # Use ":-----:" format to center-aligned table cell texts + table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths]) + "|\n" + + check = {True: "✅", False: "❌"} + + for name in model_names: + if name in MODEL_NAMES_TO_IGNORE: + continue + if name in MODEL_NAMES_WITH_SAME_CONFIG.keys(): + prefix = model_name_to_prefix[MODEL_NAMES_WITH_SAME_CONFIG[name]] + else: + prefix = model_name_to_prefix[name] + line = [ + model_name_to_link_mapping[name], + check[pt_models[prefix]], + check[tf_models[prefix]], + check[flax_models[prefix]], + ] + table += "|" + "|".join([_center_text(l, w) for l, w in zip(line, widths)]) + "|\n" + return table + + +def check_model_table(overwrite=False): + """ + Check the model table in the index.md is consistent with the state of the lib and potentially fix it. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the table when it's not up to date. + """ + current_table, start_index, end_index, lines = _find_text_in_file( + filename=os.path.join(PATH_TO_DOCS, "index.md"), + start_prompt="", + ) + new_table = get_model_table_from_auto_modules() + + if current_table != new_table: + if overwrite: + with open(os.path.join(PATH_TO_DOCS, "index.md"), "w", encoding="utf-8", newline="\n") as f: + f.writelines(lines[:start_index] + [new_table] + lines[end_index:]) + else: + raise ValueError( + "The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + check_model_table(args.fix_and_overwrite) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_task_guides.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_task_guides.py new file mode 100644 index 0000000000000000000000000000000000000000..b00ff1dc1a5a0894fde3b921973e89e5e02e1389 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_task_guides.py @@ -0,0 +1,168 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +""" +Utility that checks the list of models in the tips in the task-specific pages of the doc is up to date and potentially +fixes it. + +Use from the root of the repo with: + +```bash +python utils/check_task_guides.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`). + +To auto-fix issues run: + +```bash +python utils/check_task_guides.py --fix_and_overwrite +``` + +which is used by `make fix-copies`. +""" +import argparse +import os + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_task_guides.py +TRANSFORMERS_PATH = "src/transformers" +PATH_TO_TASK_GUIDES = "docs/source/en/tasks" + + +def _find_text_in_file(filename: str, start_prompt: str, end_prompt: str) -> str: + """ + Find the text in filename between two prompts. + + Args: + filename (`str`): The file to search into. + start_prompt (`str`): A string to look for at the start of the content searched. + end_prompt (`str`): A string that will mark the end of the content to look for. + + Returns: + `str`: The content between the prompts. + """ + with open(filename, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + # Find the start prompt. + start_index = 0 + while not lines[start_index].startswith(start_prompt): + start_index += 1 + start_index += 1 + + # Now go until the end prompt. + end_index = start_index + while not lines[end_index].startswith(end_prompt): + end_index += 1 + end_index -= 1 + + while len(lines[start_index]) <= 1: + start_index += 1 + while len(lines[end_index]) <= 1: + end_index -= 1 + end_index += 1 + return "".join(lines[start_index:end_index]), start_index, end_index, lines + + +# This is to make sure the transformers module imported is the one in the repo. +transformers_module = direct_transformers_import(TRANSFORMERS_PATH) + +# Map between a task guide and the corresponding auto class. +TASK_GUIDE_TO_MODELS = { + "asr.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, + "audio_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, + "language_modeling.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, + "image_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, + "masked_language_modeling.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, + "multiple_choice.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, + "object_detection.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, + "question_answering.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, + "semantic_segmentation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, + "sequence_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, + "summarization.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + "token_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, + "translation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + "video_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, + "document_question_answering.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, + "monocular_depth_estimation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, +} + +# This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any +# `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). +SPECIAL_TASK_GUIDE_TO_MODEL_TYPES = { + "summarization.md": ("nllb",), + "translation.md": ("nllb",), +} + + +def get_model_list_for_task(task_guide: str) -> str: + """ + Return the list of models supporting a given task. + + Args: + task_guide (`str`): The name of the task guide to check. + + Returns: + `str`: The list of models supporting this task, as links to their respective doc pages separated by commas. + """ + model_maping_names = TASK_GUIDE_TO_MODELS[task_guide] + special_model_types = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(task_guide, set()) + model_names = { + code: name + for code, name in transformers_module.MODEL_NAMES_MAPPING.items() + if (code in model_maping_names or code in special_model_types) + } + return ", ".join([f"[{name}](../model_doc/{code})" for code, name in model_names.items()]) + "\n" + + +def check_model_list_for_task(task_guide: str, overwrite: bool = False): + """ + For a given task guide, checks the model list in the generated tip for consistency with the state of the lib and + updates it if needed. + + Args: + task_guide (`str`): + The name of the task guide to check. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the table when it's not up to date. + """ + current_list, start_index, end_index, lines = _find_text_in_file( + filename=os.path.join(PATH_TO_TASK_GUIDES, task_guide), + start_prompt="", + end_prompt="", + ) + + new_list = get_model_list_for_task(task_guide) + + if current_list != new_list: + if overwrite: + with open(os.path.join(PATH_TO_TASK_GUIDES, task_guide), "w", encoding="utf-8", newline="\n") as f: + f.writelines(lines[:start_index] + [new_list] + lines[end_index:]) + else: + raise ValueError( + f"The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`" + " to fix this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + for task_guide in TASK_GUIDE_TO_MODELS.keys(): + check_model_list_for_task(task_guide, args.fix_and_overwrite) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_tf_ops.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_tf_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c2b8bae4e26b74e38728fc1440a58cf4837c1b --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/check_tf_ops.py @@ -0,0 +1,101 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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 argparse +import json +import os + +from tensorflow.core.protobuf.saved_model_pb2 import SavedModel + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_copies.py +REPO_PATH = "." + +# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) +INTERNAL_OPS = [ + "Assert", + "AssignVariableOp", + "EmptyTensorList", + "MergeV2Checkpoints", + "ReadVariableOp", + "ResourceGather", + "RestoreV2", + "SaveV2", + "ShardedFilename", + "StatefulPartitionedCall", + "StaticRegexFullMatch", + "VarHandleOp", +] + + +def onnx_compliancy(saved_model_path, strict, opset): + saved_model = SavedModel() + onnx_ops = [] + + with open(os.path.join(REPO_PATH, "utils", "tf_ops", "onnx.json")) as f: + onnx_opsets = json.load(f)["opsets"] + + for i in range(1, opset + 1): + onnx_ops.extend(onnx_opsets[str(i)]) + + with open(saved_model_path, "rb") as f: + saved_model.ParseFromString(f.read()) + + model_op_names = set() + + # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) + for meta_graph in saved_model.meta_graphs: + # Add operations in the graph definition + model_op_names.update(node.op for node in meta_graph.graph_def.node) + + # Go through the functions in the graph definition + for func in meta_graph.graph_def.library.function: + # Add operations in each function + model_op_names.update(node.op for node in func.node_def) + + # Convert to list, sorted if you want + model_op_names = sorted(model_op_names) + incompatible_ops = [] + + for op in model_op_names: + if op not in onnx_ops and op not in INTERNAL_OPS: + incompatible_ops.append(op) + + if strict and len(incompatible_ops) > 0: + raise Exception(f"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops) + elif len(incompatible_ops) > 0: + print(f"Found the following incompatible ops for the opset {opset}:") + print(*incompatible_ops, sep="\n") + else: + print(f"The saved model {saved_model_path} can properly be converted with ONNX.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).") + parser.add_argument( + "--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested." + ) + parser.add_argument( + "--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model." + ) + parser.add_argument( + "--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)" + ) + args = parser.parse_args() + + if args.framework == "onnx": + onnx_compliancy(args.saved_model_path, args.strict, args.opset) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/create_dummy_models.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/create_dummy_models.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2c39de4c8f930c7b470dbd1472bd0c8e8b59db --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/create_dummy_models.py @@ -0,0 +1,1556 @@ +# coding=utf-8 +# Copyright 2022 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 argparse +import collections.abc +import copy +import inspect +import json +import multiprocessing +import os +import shutil +import tempfile +import traceback +from pathlib import Path + +from check_config_docstrings import get_checkpoint_from_config_class +from datasets import load_dataset +from get_test_info import get_model_to_tester_mapping, get_tester_classes_for_model +from huggingface_hub import Repository, create_repo, hf_api, upload_folder + +from transformers import ( + CONFIG_MAPPING, + FEATURE_EXTRACTOR_MAPPING, + IMAGE_PROCESSOR_MAPPING, + PROCESSOR_MAPPING, + TOKENIZER_MAPPING, + AutoTokenizer, + LayoutLMv3TokenizerFast, + PreTrainedTokenizer, + PreTrainedTokenizerFast, + logging, +) +from transformers.feature_extraction_utils import FeatureExtractionMixin +from transformers.file_utils import is_tf_available, is_torch_available +from transformers.image_processing_utils import BaseImageProcessor +from transformers.models.auto.configuration_auto import AutoConfig, model_type_to_module_name +from transformers.models.fsmt import configuration_fsmt +from transformers.processing_utils import ProcessorMixin, transformers_module +from transformers.tokenization_utils_base import PreTrainedTokenizerBase + + +# make sure tokenizer plays nice with multiprocessing +os.environ["TOKENIZERS_PARALLELISM"] = "false" + +logging.set_verbosity_error() +logging.disable_progress_bar() +logger = logging.get_logger(__name__) + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + +if not is_torch_available(): + raise ValueError("Please install PyTorch.") + +if not is_tf_available(): + raise ValueError("Please install TensorFlow.") + + +FRAMEWORKS = ["pytorch", "tensorflow"] +INVALID_ARCH = [] +TARGET_VOCAB_SIZE = 1024 + +data = {"training_ds": None, "testing_ds": None} + +COMPOSITE_MODELS = { + "EncoderDecoderModel": "EncoderDecoderModel-bert-bert", + "SpeechEncoderDecoderModel": "SpeechEncoderDecoderModel-wav2vec2-bert", + "VisionEncoderDecoderModel": "VisionEncoderDecoderModel-vit-gpt2", + "VisionTextDualEncoderModel": "VisionTextDualEncoderModel-vit-bert", +} + +# This list contains the model architectures for which a tiny version could not be created. +# Avoid to add new architectures here - unless we have verified carefully that it's (almost) impossible to create them. +# One such case is: no model tester class is implemented for a model type (like `MT5`) because its architecture is +# identical to another one (`MT5` is based on `T5`), but trained on different datasets or with different techniques. +UNCONVERTIBLE_MODEL_ARCHITECTURES = { + "BertGenerationEncoder", + "BertGenerationDecoder", + "CamembertForSequenceClassification", + "CamembertForMultipleChoice", + "CamembertForMaskedLM", + "CamembertForCausalLM", + "CamembertForTokenClassification", + "CamembertForQuestionAnswering", + "CamembertModel", + "TFCamembertForMultipleChoice", + "TFCamembertForTokenClassification", + "TFCamembertForQuestionAnswering", + "TFCamembertForSequenceClassification", + "TFCamembertForMaskedLM", + "TFCamembertModel", + "TFCamembertForCausalLM", + "DecisionTransformerModel", + "GraphormerModel", + "InformerModel", + "JukeboxModel", + "MarianForCausalLM", + "MaskFormerSwinModel", + "MaskFormerSwinBackbone", + "MT5Model", + "MT5ForConditionalGeneration", + "UMT5ForConditionalGeneration", + "TFMT5ForConditionalGeneration", + "TFMT5Model", + "QDQBertForSequenceClassification", + "QDQBertForMaskedLM", + "QDQBertModel", + "QDQBertForTokenClassification", + "QDQBertLMHeadModel", + "QDQBertForMultipleChoice", + "QDQBertForQuestionAnswering", + "QDQBertForNextSentencePrediction", + "ReformerModelWithLMHead", + "RetriBertModel", + "Speech2Text2ForCausalLM", + "TimeSeriesTransformerModel", + "TrajectoryTransformerModel", + "TrOCRForCausalLM", + "XLMProphetNetForConditionalGeneration", + "XLMProphetNetForCausalLM", + "XLMProphetNetModel", + "XLMRobertaModel", + "XLMRobertaForTokenClassification", + "XLMRobertaForMultipleChoice", + "XLMRobertaForMaskedLM", + "XLMRobertaForCausalLM", + "XLMRobertaForSequenceClassification", + "XLMRobertaForQuestionAnswering", + "TFXLMRobertaForSequenceClassification", + "TFXLMRobertaForMaskedLM", + "TFXLMRobertaForCausalLM", + "TFXLMRobertaForQuestionAnswering", + "TFXLMRobertaModel", + "TFXLMRobertaForMultipleChoice", + "TFXLMRobertaForTokenClassification", +} + + +def get_processor_types_from_config_class(config_class, allowed_mappings=None): + """Return a tuple of processors for `config_class`. + + We use `tuple` here to include (potentially) both slow & fast tokenizers. + """ + + # To make a uniform return type + def _to_tuple(x): + if not isinstance(x, collections.abc.Sequence): + x = (x,) + else: + x = tuple(x) + return x + + if allowed_mappings is None: + allowed_mappings = ["processor", "tokenizer", "image_processor", "feature_extractor"] + + processor_types = () + + # Check first if a model has `ProcessorMixin`. Otherwise, check if it has tokenizers, and/or an image processor or + # a feature extractor + if config_class in PROCESSOR_MAPPING and "processor" in allowed_mappings: + processor_types = _to_tuple(PROCESSOR_MAPPING[config_class]) + else: + if config_class in TOKENIZER_MAPPING and "tokenizer" in allowed_mappings: + processor_types = TOKENIZER_MAPPING[config_class] + + if config_class in IMAGE_PROCESSOR_MAPPING and "image_processor" in allowed_mappings: + processor_types += _to_tuple(IMAGE_PROCESSOR_MAPPING[config_class]) + elif config_class in FEATURE_EXTRACTOR_MAPPING and "feature_extractor" in allowed_mappings: + processor_types += _to_tuple(FEATURE_EXTRACTOR_MAPPING[config_class]) + + # Remark: some configurations have no processor at all. For example, generic composite models like + # `EncoderDecoderModel` is used for any (compatible) text models. Also, `DecisionTransformer` doesn't + # require any processor. + + # We might get `None` for some tokenizers - remove them here. + processor_types = tuple(p for p in processor_types if p is not None) + + return processor_types + + +def get_architectures_from_config_class(config_class, arch_mappings, models_to_skip=None): + """Return a tuple of all possible architectures attributed to a configuration class `config_class`. + + For example, BertConfig -> [BertModel, BertForMaskedLM, ..., BertForQuestionAnswering]. + """ + # A model architecture could appear in several mappings. For example, `BartForConditionalGeneration` is in + # - MODEL_FOR_PRETRAINING_MAPPING_NAMES + # - MODEL_WITH_LM_HEAD_MAPPING_NAMES + # - MODEL_FOR_MASKED_LM_MAPPING_NAMES + # - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES + # We avoid the duplication. + architectures = set() + + if models_to_skip is None: + models_to_skip = [] + models_to_skip = UNCONVERTIBLE_MODEL_ARCHITECTURES.union(models_to_skip) + + for mapping in arch_mappings: + if config_class in mapping: + models = mapping[config_class] + models = tuple(models) if isinstance(models, collections.abc.Sequence) else (models,) + for model in models: + if model.__name__ not in models_to_skip: + architectures.add(model) + + architectures = tuple(architectures) + + return architectures + + +def get_config_class_from_processor_class(processor_class): + """Get the config class from a processor class. + + Some config/model classes use tokenizers/feature_extractors from other models. For example, `GPT-J` uses + `GPT2Tokenizer`. If no checkpoint is found for a config class, or a checkpoint is found without necessary file(s) to + create the processor for `processor_class`, we get the config class that corresponds to `processor_class` and use it + to find a checkpoint in order to create the processor. + """ + + processor_prefix = processor_class.__name__ + for postfix in ["TokenizerFast", "Tokenizer", "ImageProcessor", "FeatureExtractor", "Processor"]: + processor_prefix = processor_prefix.replace(postfix, "") + + # `Wav2Vec2CTCTokenizer` -> `Wav2Vec2Config` + if processor_prefix == "Wav2Vec2CTC": + processor_prefix = "Wav2Vec2" + + # Find the new configuration class + new_config_name = f"{processor_prefix}Config" + new_config_class = getattr(transformers_module, new_config_name) + + return new_config_class + + +def build_processor(config_class, processor_class, allow_no_checkpoint=False): + """Create a processor for `processor_class`. + + If a processor is not able to be built with the original arguments, this method tries to change the arguments and + call itself recursively, by inferring a new `config_class` or a new `processor_class` from another one, in order to + find a checkpoint containing the necessary files to build a processor. + + The processor is not saved here. Instead, it will be saved in `convert_processors` after further changes in + `convert_processors`. For each model architecture`, a copy will be created and saved along the built model. + """ + # Currently, this solely uses the docstring in the source file of `config_class` to find a checkpoint. + checkpoint = get_checkpoint_from_config_class(config_class) + + if checkpoint is None: + # try to get the checkpoint from the config class for `processor_class`. + # This helps cases like `XCLIPConfig` and `VideoMAEFeatureExtractor` to find a checkpoint from `VideoMAEConfig`. + config_class_from_processor_class = get_config_class_from_processor_class(processor_class) + checkpoint = get_checkpoint_from_config_class(config_class_from_processor_class) + + processor = None + try: + processor = processor_class.from_pretrained(checkpoint) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + + # Try to get a new processor class from checkpoint. This is helpful for a checkpoint without necessary file to load + # processor while `processor_class` is an Auto class. For example, `sew` has `Wav2Vec2Processor` in + # `PROCESSOR_MAPPING_NAMES`, its `tokenizer_class` is `AutoTokenizer`, and the checkpoint + # `https://huggingface.co/asapp/sew-tiny-100k` has no tokenizer file, but we can get + # `tokenizer_class: Wav2Vec2CTCTokenizer` from the config file. (The new processor class won't be able to load from + # `checkpoint`, but it helps this recursive method to find a way to build a processor). + if ( + processor is None + and checkpoint is not None + and issubclass(processor_class, (PreTrainedTokenizerBase, AutoTokenizer)) + ): + try: + config = AutoConfig.from_pretrained(checkpoint) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + config = None + if config is not None: + if not isinstance(config, config_class): + raise ValueError( + f"`config` (which is of type {config.__class__.__name__}) should be an instance of `config_class`" + f" ({config_class.__name__})!" + ) + tokenizer_class = config.tokenizer_class + new_processor_class = None + if tokenizer_class is not None: + new_processor_class = getattr(transformers_module, tokenizer_class) + if new_processor_class != processor_class: + processor = build_processor(config_class, new_processor_class) + # If `tokenizer_class` is not specified in `config`, let's use `config` to get the process class via auto + # mappings, but only allow the tokenizer mapping being used. This is to make `Wav2Vec2Conformer` build + if processor is None: + new_processor_classes = get_processor_types_from_config_class( + config.__class__, allowed_mappings=["tokenizer"] + ) + # Used to avoid infinite recursion between a pair of fast/slow tokenizer types + names = [ + x.__name__.replace("Fast", "") for x in [processor_class, new_processor_class] if x is not None + ] + new_processor_classes = [ + x for x in new_processor_classes if x is not None and x.__name__.replace("Fast", "") not in names + ] + if len(new_processor_classes) > 0: + new_processor_class = new_processor_classes[0] + # Let's use fast tokenizer if there is any + for x in new_processor_classes: + if x.__name__.endswith("Fast"): + new_processor_class = x + break + processor = build_processor(config_class, new_processor_class) + + if processor is None: + # Try to build each component (tokenizer & feature extractor) of a `ProcessorMixin`. + if issubclass(processor_class, ProcessorMixin): + attrs = {} + for attr_name in processor_class.attributes: + attrs[attr_name] = [] + # This could be a tuple (for tokenizers). For example, `CLIPProcessor` has + # - feature_extractor_class = "CLIPFeatureExtractor" + # - tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast") + attr_class_names = getattr(processor_class, f"{attr_name}_class") + if not isinstance(attr_class_names, tuple): + attr_class_names = (attr_class_names,) + + for name in attr_class_names: + attr_class = getattr(transformers_module, name) + attr = build_processor(config_class, attr_class) + if attr is not None: + attrs[attr_name].append(attr) + + # try to build a `ProcessorMixin`, so we can return a single value + if all(len(v) > 0 for v in attrs.values()): + try: + processor = processor_class(**{k: v[0] for k, v in attrs.items()}) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + else: + # `checkpoint` might lack some file(s) to load a processor. For example, `facebook/hubert-base-ls960` + # has no tokenizer file to load `Wav2Vec2CTCTokenizer`. In this case, we try to build a processor + # with the configuration class (for example, `Wav2Vec2Config`) corresponding to `processor_class`. + config_class_from_processor_class = get_config_class_from_processor_class(processor_class) + if config_class_from_processor_class != config_class: + processor = build_processor(config_class_from_processor_class, processor_class) + + # Try to create an image processor or a feature extractor without any checkpoint + if ( + processor is None + and allow_no_checkpoint + and (issubclass(processor_class, BaseImageProcessor) or issubclass(processor_class, FeatureExtractionMixin)) + ): + try: + processor = processor_class() + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + + # validation + if processor is not None: + if not (isinstance(processor, processor_class) or processor_class.__name__.startswith("Auto")): + raise ValueError( + f"`processor` (which is of type {processor.__class__.__name__}) should be an instance of" + f" {processor_class.__name__} or an Auto class!" + ) + + return processor + + +def get_tiny_config(config_class, model_class=None, **model_tester_kwargs): + """Retrieve a tiny configuration from `config_class` using each model's `ModelTester`. + + Args: + config_class: Subclass of `PreTrainedConfig`. + + Returns: + An instance of `config_class` with tiny hyperparameters + """ + model_type = config_class.model_type + + # For model type like `data2vec-vision` and `donut-swin`, we can't get the config/model file name directly via + # `model_type` as it would be sth. like `configuration_data2vec_vision.py`. + # A simple way is to use `inspect.getsourcefile(config_class)`. + config_source_file = inspect.getsourcefile(config_class) + # The modeling file name without prefix (`modeling_`) and postfix (`.py`) + modeling_name = config_source_file.split(os.path.sep)[-1].replace("configuration_", "").replace(".py", "") + + try: + print("Importing", model_type_to_module_name(model_type)) + module_name = model_type_to_module_name(model_type) + if not modeling_name.startswith(module_name): + raise ValueError(f"{modeling_name} doesn't start with {module_name}!") + test_file = os.path.join("tests", "models", module_name, f"test_modeling_{modeling_name}.py") + models_to_model_testers = get_model_to_tester_mapping(test_file) + # Find the model tester class + model_tester_class = None + tester_classes = [] + if model_class is not None: + tester_classes = get_tester_classes_for_model(test_file, model_class) + else: + for _tester_classes in models_to_model_testers.values(): + tester_classes.extend(_tester_classes) + if len(tester_classes) > 0: + # sort with the length of the class names first, then the alphabetical order + # This is to avoid `T5EncoderOnlyModelTest` is used instead of `T5ModelTest`, which has + # `is_encoder_decoder=False` and causes some pipeline tests failing (also failures in `Optimum` CI). + # TODO: More fine grained control of the desired tester class. + model_tester_class = sorted(tester_classes, key=lambda x: (len(x.__name__), x.__name__))[0] + except ModuleNotFoundError: + error = f"Tiny config not created for {model_type} - cannot find the testing module from the model name." + raise ValueError(error) + + if model_tester_class is None: + error = f"Tiny config not created for {model_type} - no model tester is found in the testing module." + raise ValueError(error) + + # CLIP-like models have `text_model_tester` and `vision_model_tester`, and we need to pass `vocab_size` to + # `text_model_tester` via `text_kwargs`. The same trick is also necessary for `Flava`. + + if "vocab_size" in model_tester_kwargs: + if "text_kwargs" in inspect.signature(model_tester_class.__init__).parameters.keys(): + vocab_size = model_tester_kwargs.pop("vocab_size") + model_tester_kwargs["text_kwargs"] = {"vocab_size": vocab_size} + + # `parent` is an instance of `unittest.TestCase`, but we don't need it here. + model_tester = model_tester_class(parent=None, **model_tester_kwargs) + + if hasattr(model_tester, "get_pipeline_config"): + config = model_tester.get_pipeline_config() + elif hasattr(model_tester, "prepare_config_and_inputs"): + # `PoolFormer` has no `get_config` defined. Furthermore, it's better to use `prepare_config_and_inputs` even if + # `get_config` is defined, since there might be some extra changes in `prepare_config_and_inputs`. + config = model_tester.prepare_config_and_inputs()[0] + elif hasattr(model_tester, "get_config"): + config = model_tester.get_config() + else: + error = ( + f"Tiny config not created for {model_type} - the model tester {model_tester_class.__name__} lacks" + " necessary method to create config." + ) + raise ValueError(error) + + # make sure this is long enough (some model tester has `20` for this attr.) to pass `text-generation` + # pipeline tests. + max_positions = [] + for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]: + if getattr(config, key, 0) > 0: + max_positions.append(getattr(config, key)) + if getattr(config, "text_config", None) is not None: + if getattr(config.text_config, key, None) is not None: + max_positions.append(getattr(config.text_config, key)) + if len(max_positions) > 0: + max_position = max(200, min(max_positions)) + for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]: + if getattr(config, key, 0) > 0: + setattr(config, key, max_position) + if getattr(config, "text_config", None) is not None: + if getattr(config.text_config, key, None) is not None: + setattr(config.text_config, key, max_position) + + return config + + +def convert_tokenizer(tokenizer_fast: PreTrainedTokenizerFast): + new_tokenizer = tokenizer_fast.train_new_from_iterator( + data["training_ds"]["text"], TARGET_VOCAB_SIZE, show_progress=False + ) + + # Make sure it at least runs + if not isinstance(new_tokenizer, LayoutLMv3TokenizerFast): + new_tokenizer(data["testing_ds"]["text"]) + + return new_tokenizer + + +def convert_feature_extractor(feature_extractor, tiny_config): + to_convert = False + kwargs = {} + if hasattr(tiny_config, "image_size"): + kwargs["size"] = tiny_config.image_size + kwargs["crop_size"] = tiny_config.image_size + to_convert = True + elif ( + hasattr(tiny_config, "vision_config") + and tiny_config.vision_config is not None + and hasattr(tiny_config.vision_config, "image_size") + ): + kwargs["size"] = tiny_config.vision_config.image_size + kwargs["crop_size"] = tiny_config.vision_config.image_size + to_convert = True + + # Speech2TextModel specific. + if hasattr(tiny_config, "input_feat_per_channel"): + kwargs["feature_size"] = tiny_config.input_feat_per_channel + kwargs["num_mel_bins"] = tiny_config.input_feat_per_channel + to_convert = True + + if to_convert: + feature_extractor = feature_extractor.__class__(**kwargs) + + return feature_extractor + + +def convert_processors(processors, tiny_config, output_folder, result): + """Change a processor to work with smaller inputs. + + For tokenizers, we try to reduce their vocabulary size. + + For feature extractor, we use smaller image size or change + other attributes using the values from `tiny_config`. See `convert_feature_extractor`. + + This method should not fail: we catch the errors and put them in `result["warnings"]` with descriptive messages. + """ + + def _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False): + """Set tokenizer(s) to `None` if the fast/slow tokenizers have different values for `vocab_size` or `length`. + + If `keep_fast_tokenizer=True`, the fast tokenizer will be kept. + """ + # sanity check 1: fast and slow tokenizers should be compatible (vocab_size) + if fast_tokenizer is not None and slow_tokenizer is not None: + if fast_tokenizer.vocab_size != slow_tokenizer.vocab_size: + warning_messagae = ( + "The fast/slow tokenizers " + f"({fast_tokenizer.__class__.__name__}/{slow_tokenizer.__class__.__name__}) have different " + "vocabulary size: " + f"fast_tokenizer.vocab_size = {fast_tokenizer.vocab_size} and " + f"slow_tokenizer.vocab_size = {slow_tokenizer.vocab_size}." + ) + result["warnings"].append(warning_messagae) + if not keep_fast_tokenizer: + fast_tokenizer = None + slow_tokenizer = None + + # sanity check 2: fast and slow tokenizers should be compatible (length) + if fast_tokenizer is not None and slow_tokenizer is not None: + if len(fast_tokenizer) != len(slow_tokenizer): + warning_messagae = ( + f"The fast/slow tokenizers () have different length: " + f"len(fast_tokenizer) = {len(fast_tokenizer)} and " + f"len(slow_tokenizer) = {len(slow_tokenizer)}." + ) + result["warnings"].append(warning_messagae) + if not keep_fast_tokenizer: + fast_tokenizer = None + slow_tokenizer = None + + return fast_tokenizer, slow_tokenizer + + tokenizers = [] + feature_extractors = [] + for processor in processors: + if isinstance(processor, PreTrainedTokenizerBase): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}: + tokenizers.append(processor) + elif isinstance(processor, BaseImageProcessor): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}: + feature_extractors.append(processor) + elif isinstance(processor, FeatureExtractionMixin): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}: + feature_extractors.append(processor) + elif isinstance(processor, ProcessorMixin): + if hasattr(processor, "tokenizer"): + if processor.tokenizer.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}: + tokenizers.append(processor.tokenizer) + # Currently, we only have these 2 possibilities + if hasattr(processor, "image_processor"): + if processor.image_processor.__class__.__name__ not in { + x.__class__.__name__ for x in feature_extractors + }: + feature_extractors.append(processor.image_processor) + elif hasattr(processor, "feature_extractor"): + if processor.feature_extractor.__class__.__name__ not in { + x.__class__.__name__ for x in feature_extractors + }: + feature_extractors.append(processor.feature_extractor) + + # check the built processors have the unique type + num_types = len({x.__class__.__name__ for x in feature_extractors}) + if num_types >= 2: + raise ValueError(f"`feature_extractors` should contain at most 1 type, but it contains {num_types} types!") + num_types = len({x.__class__.__name__.replace("Fast", "") for x in tokenizers}) + if num_types >= 2: + raise ValueError(f"`tokenizers` should contain at most 1 tokenizer type, but it contains {num_types} types!") + + fast_tokenizer = None + slow_tokenizer = None + + for tokenizer in tokenizers: + if isinstance(tokenizer, PreTrainedTokenizerFast): + fast_tokenizer = tokenizer + else: + slow_tokenizer = tokenizer + + # If the (original) fast/slow tokenizers don't correspond, keep only the fast tokenizer. + # This doesn't necessarily imply the fast/slow tokenizers in a single Hub repo. has issues. + # It's more of an issue in `build_processor` which tries to get a checkpoint with as much effort as possible. + # For `YosoModel` (which uses `AlbertTokenizer(Fast)`), its real (Hub) checkpoint doesn't contain valid files to + # load the slower tokenizer (`AlbertTokenizer`), and it ends up finding the (canonical) checkpoint of `AlbertModel`, + # which has different vocabulary. + # TODO: Try to improve `build_processor`'s definition and/or usage to avoid the above situation in the first place. + fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=True) + original_fast_tokenizer, original_slow_tokenizer = fast_tokenizer, slow_tokenizer + + if fast_tokenizer: + try: + # Wav2Vec2ForCTC , ByT5Tokenizer etc. all are already small enough and have no fast version that can + # be retrained + if fast_tokenizer.vocab_size > TARGET_VOCAB_SIZE: + fast_tokenizer = convert_tokenizer(fast_tokenizer) + except Exception: + result["warnings"].append( + ( + f"Failed to convert the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + + # If `fast_tokenizer` exists, `slow_tokenizer` should correspond to it. + if fast_tokenizer: + # Make sure the fast tokenizer can be saved + try: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + fast_tokenizer.save_pretrained(tmpdir) + try: + slow_tokenizer = AutoTokenizer.from_pretrained(tmpdir, use_fast=False) + except Exception: + result["warnings"].append( + ( + f"Failed to load the slow tokenizer saved from {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + # Let's just keep the fast version + slow_tokenizer = None + except Exception: + result["warnings"].append( + ( + f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + fast_tokenizer = None + + # If the (possibly converted) fast/slow tokenizers don't correspond, set them to `None`, and use the original + # tokenizers. + fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False) + + # If there is any conversion failed, we keep the original tokenizers. + if (original_fast_tokenizer is not None and fast_tokenizer is None) or ( + original_slow_tokenizer is not None and slow_tokenizer is None + ): + warning_messagae = ( + "There are some issues when converting the fast/slow tokenizers. The original tokenizers from the Hub " + " will be used instead." + ) + result["warnings"].append(warning_messagae) + # Let's use the original version at the end (`original_fast_tokenizer` and `original_slow_tokenizer`) + fast_tokenizer = original_fast_tokenizer + slow_tokenizer = original_slow_tokenizer + + # Make sure the fast tokenizer can be saved + if fast_tokenizer: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + try: + fast_tokenizer.save_pretrained(tmpdir) + except Exception: + result["warnings"].append( + ( + f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + fast_tokenizer = None + # Make sure the slow tokenizer can be saved + if slow_tokenizer: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + try: + slow_tokenizer.save_pretrained(tmpdir) + except Exception: + result["warnings"].append( + ( + f"Failed to save the slow tokenizer for {slow_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + slow_tokenizer = None + + # update feature extractors using the tiny config + try: + feature_extractors = [convert_feature_extractor(p, tiny_config) for p in feature_extractors] + except Exception: + result["warnings"].append( + ( + "Failed to convert feature extractors.", + traceback.format_exc(), + ) + ) + feature_extractors = [] + + if hasattr(tiny_config, "max_position_embeddings") and tiny_config.max_position_embeddings > 0: + if fast_tokenizer is not None: + if fast_tokenizer.__class__.__name__ in [ + "RobertaTokenizerFast", + "XLMRobertaTokenizerFast", + "LongformerTokenizerFast", + "MPNetTokenizerFast", + ]: + fast_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2 + else: + fast_tokenizer.model_max_length = tiny_config.max_position_embeddings + if slow_tokenizer is not None: + if slow_tokenizer.__class__.__name__ in [ + "RobertaTokenizer", + "XLMRobertaTokenizer", + "LongformerTokenizer", + "MPNetTokenizer", + ]: + slow_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2 + else: + slow_tokenizer.model_max_length = tiny_config.max_position_embeddings + + processors = [fast_tokenizer, slow_tokenizer] + feature_extractors + processors = [p for p in processors if p is not None] + for p in processors: + p.save_pretrained(output_folder) + + return processors + + +def get_checkpoint_dir(output_dir, model_arch): + """Get framework-agnostic architecture name. Used to save all PT/TF/Flax models into the same directory.""" + + arch_name = model_arch.__name__ + if arch_name.startswith("TF"): + arch_name = arch_name[2:] + elif arch_name.startswith("Flax"): + arch_name = arch_name[4:] + + return os.path.join(output_dir, arch_name) + + +def build_model(model_arch, tiny_config, output_dir): + """Create and save a model for `model_arch`. + + Also copy the set of processors to each model (under the same model type) output folder. + """ + + checkpoint_dir = get_checkpoint_dir(output_dir, model_arch) + + processor_output_dir = os.path.join(output_dir, "processors") + # copy the (same set of) processors (for a model type) to the model arch. specific folder + if os.path.isdir(processor_output_dir): + shutil.copytree(processor_output_dir, checkpoint_dir, dirs_exist_ok=True) + + tiny_config = copy.deepcopy(tiny_config) + + if any(model_arch.__name__.endswith(x) for x in ["ForCausalLM", "LMHeadModel"]): + tiny_config.is_encoder_decoder = False + tiny_config.is_decoder = True + + model = model_arch(config=tiny_config) + model.save_pretrained(checkpoint_dir) + model.from_pretrained(checkpoint_dir) + + return model + + +def fill_result_with_error(result, error, trace, models_to_create): + """Fill `result` with errors for all target model arch if we can't build processor""" + error = (error, trace) + result["error"] = error + for framework in FRAMEWORKS: + if framework in models_to_create: + result[framework] = {} + for model_arch in models_to_create[framework]: + result[framework][model_arch.__name__] = {"model": None, "checkpoint": None, "error": error} + + result["processor"] = {p.__class__.__name__: p.__class__.__name__ for p in result["processor"].values()} + + +def upload_model(model_dir, organization, token): + """Upload the tiny models""" + + arch_name = model_dir.split(os.path.sep)[-1] + repo_name = f"tiny-random-{arch_name}" + repo_id = f"{organization}/{repo_name}" + + repo_exist = False + error = None + try: + create_repo(repo_id=repo_id, exist_ok=False, repo_type="model", token=token) + except Exception as e: + error = e + if "You already created" in str(e): + error = None + logger.warning("Remote repository exists and will be cloned.") + repo_exist = True + try: + create_repo(repo_id=repo_id, exist_ok=True, repo_type="model", token=token) + except Exception as e: + error = e + if error is not None: + raise error + + with tempfile.TemporaryDirectory() as tmpdir: + repo = Repository(local_dir=tmpdir, clone_from=repo_id, token=token) + repo.git_pull() + shutil.copytree(model_dir, tmpdir, dirs_exist_ok=True) + + if repo_exist: + # Open a PR on the existing Hub repo. + hub_pr_url = upload_folder( + folder_path=model_dir, + repo_id=repo_id, + repo_type="model", + commit_message=f"Update tiny models for {arch_name}", + commit_description=f"Upload tiny models for {arch_name}", + create_pr=True, + token=token, + ) + logger.warning(f"PR open in {hub_pr_url}.") + # TODO: We need this information? + else: + # Push to Hub repo directly + repo.git_add(auto_lfs_track=True) + repo.git_commit(f"Upload tiny models for {arch_name}") + repo.git_push(blocking=True) # this prints a progress bar with the upload + logger.warning(f"Tiny models {arch_name} pushed to {repo_id}.") + + +def build_composite_models(config_class, output_dir): + import tempfile + + from transformers import ( + BertConfig, + BertLMHeadModel, + BertModel, + BertTokenizer, + BertTokenizerFast, + EncoderDecoderModel, + GPT2Config, + GPT2LMHeadModel, + GPT2Tokenizer, + GPT2TokenizerFast, + SpeechEncoderDecoderModel, + TFEncoderDecoderModel, + TFVisionEncoderDecoderModel, + TFVisionTextDualEncoderModel, + VisionEncoderDecoderModel, + VisionTextDualEncoderModel, + ViTConfig, + ViTFeatureExtractor, + ViTModel, + Wav2Vec2Config, + Wav2Vec2Model, + Wav2Vec2Processor, + ) + + # These will be removed at the end if they are empty + result = {"error": None, "warnings": []} + + if config_class.model_type == "encoder-decoder": + encoder_config_class = BertConfig + decoder_config_class = BertConfig + encoder_processor = (BertTokenizerFast, BertTokenizer) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = BertModel + decoder_class = BertLMHeadModel + model_class = EncoderDecoderModel + tf_model_class = TFEncoderDecoderModel + elif config_class.model_type == "vision-encoder-decoder": + encoder_config_class = ViTConfig + decoder_config_class = GPT2Config + encoder_processor = (ViTFeatureExtractor,) + decoder_processor = (GPT2TokenizerFast, GPT2Tokenizer) + encoder_class = ViTModel + decoder_class = GPT2LMHeadModel + model_class = VisionEncoderDecoderModel + tf_model_class = TFVisionEncoderDecoderModel + elif config_class.model_type == "speech-encoder-decoder": + encoder_config_class = Wav2Vec2Config + decoder_config_class = BertConfig + encoder_processor = (Wav2Vec2Processor,) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = Wav2Vec2Model + decoder_class = BertLMHeadModel + model_class = SpeechEncoderDecoderModel + tf_model_class = None + elif config_class.model_type == "vision-text-dual-encoder": + # Not encoder-decoder, but encoder-encoder. We just keep the same name as above to make code easier + encoder_config_class = ViTConfig + decoder_config_class = BertConfig + encoder_processor = (ViTFeatureExtractor,) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = ViTModel + decoder_class = BertModel + model_class = VisionTextDualEncoderModel + tf_model_class = TFVisionTextDualEncoderModel + + with tempfile.TemporaryDirectory() as tmpdir: + try: + # build encoder + models_to_create = {"processor": encoder_processor, "pytorch": (encoder_class,), "tensorflow": []} + encoder_output_dir = os.path.join(tmpdir, "encoder") + build(encoder_config_class, models_to_create, encoder_output_dir) + + # build decoder + models_to_create = {"processor": decoder_processor, "pytorch": (decoder_class,), "tensorflow": []} + decoder_output_dir = os.path.join(tmpdir, "decoder") + build(decoder_config_class, models_to_create, decoder_output_dir) + + # build encoder-decoder + encoder_path = os.path.join(encoder_output_dir, encoder_class.__name__) + decoder_path = os.path.join(decoder_output_dir, decoder_class.__name__) + + if config_class.model_type != "vision-text-dual-encoder": + # Specify these explicitly for encoder-decoder like models, but not for `vision-text-dual-encoder` as it + # has no decoder. + decoder_config = decoder_config_class.from_pretrained(decoder_path) + decoder_config.is_decoder = True + decoder_config.add_cross_attention = True + model = model_class.from_encoder_decoder_pretrained( + encoder_path, + decoder_path, + decoder_config=decoder_config, + ) + elif config_class.model_type == "vision-text-dual-encoder": + model = model_class.from_vision_text_pretrained(encoder_path, decoder_path) + + model_path = os.path.join( + output_dir, + f"{model_class.__name__}-{encoder_config_class.model_type}-{decoder_config_class.model_type}", + ) + model.save_pretrained(model_path) + + if tf_model_class is not None: + model = tf_model_class.from_pretrained(model_path) + model.save_pretrained(model_path) + + # copy the processors + encoder_processor_path = os.path.join(encoder_output_dir, "processors") + decoder_processor_path = os.path.join(decoder_output_dir, "processors") + if os.path.isdir(encoder_processor_path): + shutil.copytree(encoder_processor_path, model_path, dirs_exist_ok=True) + if os.path.isdir(decoder_processor_path): + shutil.copytree(decoder_processor_path, model_path, dirs_exist_ok=True) + + # fill `result` + result["processor"] = {x.__name__: x.__name__ for x in encoder_processor + decoder_processor} + + result["pytorch"] = {model_class.__name__: {"model": model_class.__name__, "checkpoint": model_path}} + + result["tensorflow"] = {} + if tf_model_class is not None: + result["tensorflow"] = { + tf_model_class.__name__: {"model": tf_model_class.__name__, "checkpoint": model_path} + } + except Exception: + result["error"] = ( + f"Failed to build models for {config_class.__name__}.", + traceback.format_exc(), + ) + + if not result["error"]: + del result["error"] + if not result["warnings"]: + del result["warnings"] + + return result + + +def get_token_id_from_tokenizer(token_id_name, tokenizer, original_token_id): + """Use `tokenizer` to get the values of `bos_token_id`, `eos_token_ids`, etc. + + The argument `token_id_name` should be a string ending with `_token_id`, and `original_token_id` should be an + integer that will be return if `tokenizer` has no token corresponding to `token_id_name`. + """ + + token_id = original_token_id + + if not token_id_name.endswith("_token_id"): + raise ValueError(f"`token_id_name` is {token_id_name}, which doesn't end with `_token_id`!") + + token = getattr(tokenizer, token_id_name.replace("_token_id", "_token"), None) + if token is not None: + if isinstance(tokenizer, PreTrainedTokenizerFast): + token_id = tokenizer._convert_token_to_id_with_added_voc(token) + else: + token_id = tokenizer._convert_token_to_id(token) + + return token_id + + +def get_config_overrides(config_class, processors): + # `Bark` configuration is too special. Let's just not handle this for now. + if config_class.__name__ == "BarkConfig": + return {} + + config_overrides = {} + + # Check if there is any tokenizer (prefer fast version if any) + tokenizer = None + for processor in processors: + if isinstance(processor, PreTrainedTokenizerFast): + tokenizer = processor + break + elif isinstance(processor, PreTrainedTokenizer): + tokenizer = processor + + if tokenizer is None: + return config_overrides + + # Get some properties of the (already converted) tokenizer (smaller vocab size, special token ids, etc.) + # We use `len(tokenizer)` instead of `tokenizer.vocab_size` to avoid potential issues for tokenizers with non-empty + # `added_tokens_encoder`. One example is the `DebertaV2Tokenizer` where the mask token is the extra token. + vocab_size = len(tokenizer) + + # The original checkpoint has length `35998`, but it doesn't have ids `30400` and `30514` but instead `35998` and + # `35999`. + if config_class.__name__ == "GPTSanJapaneseConfig": + vocab_size += 2 + + config_overrides["vocab_size"] = vocab_size + + # Used to create a new model tester with `tokenizer.vocab_size` in order to get the (updated) special token ids. + model_tester_kwargs = {"vocab_size": vocab_size} + # `FSMTModelTester` accepts `src_vocab_size` and `tgt_vocab_size` but not `vocab_size`. + if config_class.__name__ == "FSMTConfig": + del model_tester_kwargs["vocab_size"] + model_tester_kwargs["src_vocab_size"] = tokenizer.src_vocab_size + model_tester_kwargs["tgt_vocab_size"] = tokenizer.tgt_vocab_size + + _tiny_config = get_tiny_config(config_class, **model_tester_kwargs) + + # handle the possibility of `text_config` inside `_tiny_config` for clip-like models (`owlvit`, `groupvit`, etc.) + if hasattr(_tiny_config, "text_config"): + _tiny_config = _tiny_config.text_config + + # Collect values of some special token ids + for attr in dir(_tiny_config): + if attr.endswith("_token_id"): + token_id = getattr(_tiny_config, attr) + if token_id is not None: + # Using the token id values from `tokenizer` instead of from `_tiny_config`. + token_id = get_token_id_from_tokenizer(attr, tokenizer, original_token_id=token_id) + config_overrides[attr] = token_id + + if config_class.__name__ == "FSMTConfig": + config_overrides["src_vocab_size"] = tokenizer.src_vocab_size + config_overrides["tgt_vocab_size"] = tokenizer.tgt_vocab_size + # `FSMTConfig` has `DecoderConfig` as `decoder` attribute. + config_overrides["decoder"] = configuration_fsmt.DecoderConfig( + vocab_size=tokenizer.tgt_vocab_size, bos_token_id=config_overrides["eos_token_id"] + ) + + return config_overrides + + +def build(config_class, models_to_create, output_dir): + """Create all models for a certain model type. + + Args: + config_class (`PretrainedConfig`): + A subclass of `PretrainedConfig` that is used to determine `models_to_create`. + models_to_create (`dict`): + A dictionary containing the processor/model classes that we want to create the instances. These models are + of the same model type which is associated to `config_class`. + output_dir (`str`): + The directory to save all the checkpoints. Each model architecture will be saved in a subdirectory under + it. Models in different frameworks with the same architecture will be saved in the same subdirectory. + """ + if data["training_ds"] is None or data["testing_ds"] is None: + ds = load_dataset("wikitext", "wikitext-2-raw-v1") + data["training_ds"] = ds["train"] + data["testing_ds"] = ds["test"] + + if config_class.model_type in [ + "encoder-decoder", + "vision-encoder-decoder", + "speech-encoder-decoder", + "vision-text-dual-encoder", + ]: + return build_composite_models(config_class, output_dir) + + result = {k: {} for k in models_to_create} + + # These will be removed at the end if they are empty + result["error"] = None + result["warnings"] = [] + + # Build processors + processor_classes = models_to_create["processor"] + + if len(processor_classes) == 0: + error = f"No processor class could be found in {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + for processor_class in processor_classes: + try: + processor = build_processor(config_class, processor_class, allow_no_checkpoint=True) + if processor is not None: + result["processor"][processor_class] = processor + except Exception: + error = f"Failed to build processor for {processor_class.__name__}." + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + if len(result["processor"]) == 0: + error = f"No processor could be built for {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + try: + tiny_config = get_tiny_config(config_class) + except Exception as e: + error = f"Failed to get tiny config for {config_class.__name__}: {e}" + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + # Convert the processors (reduce vocabulary size, smaller image size, etc.) + processors = list(result["processor"].values()) + processor_output_folder = os.path.join(output_dir, "processors") + try: + processors = convert_processors(processors, tiny_config, processor_output_folder, result) + except Exception: + error = "Failed to convert the processors." + trace = traceback.format_exc() + result["warnings"].append((error, trace)) + + if len(processors) == 0: + error = f"No processor is returned by `convert_processors` for {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + try: + config_overrides = get_config_overrides(config_class, processors) + except Exception as e: + error = f"Failure occurs while calling `get_config_overrides`: {e}" + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + # Just for us to see this easily in the report + if "vocab_size" in config_overrides: + result["vocab_size"] = config_overrides["vocab_size"] + + # Update attributes that `vocab_size` involves + for k, v in config_overrides.items(): + if hasattr(tiny_config, k): + setattr(tiny_config, k, v) + # So far, we only have to deal with `text_config`, as `config_overrides` contains text-related attributes only. + # `FuyuConfig` saves data under both FuyuConfig and its `text_config`. This is not good, but let's just update + # every involved fields to avoid potential failure. + if ( + hasattr(tiny_config, "text_config") + and tiny_config.text_config is not None + and hasattr(tiny_config.text_config, k) + ): + setattr(tiny_config.text_config, k, v) + # If `text_config_dict` exists, we need to update its value here too in order to # make + # `save_pretrained -> from_pretrained` work. + if hasattr(tiny_config, "text_config_dict"): + tiny_config.text_config_dict[k] = v + + if result["warnings"]: + logger.warning(result["warnings"][0][0]) + + # update `result["processor"]` + result["processor"] = {type(p).__name__: p.__class__.__name__ for p in processors} + + for pytorch_arch in models_to_create["pytorch"]: + result["pytorch"][pytorch_arch.__name__] = {} + error = None + try: + model = build_model(pytorch_arch, tiny_config, output_dir=output_dir) + except Exception as e: + model = None + error = f"Failed to create the pytorch model for {pytorch_arch}: {e}" + trace = traceback.format_exc() + + result["pytorch"][pytorch_arch.__name__]["model"] = model.__class__.__name__ if model is not None else None + result["pytorch"][pytorch_arch.__name__]["checkpoint"] = ( + get_checkpoint_dir(output_dir, pytorch_arch) if model is not None else None + ) + if error is not None: + result["pytorch"][pytorch_arch.__name__]["error"] = (error, trace) + logger.error(f"{pytorch_arch.__name__}: {error}") + + for tensorflow_arch in models_to_create["tensorflow"]: + # Make PT/TF weights compatible + pt_arch_name = tensorflow_arch.__name__[2:] # Remove `TF` + pt_arch = getattr(transformers_module, pt_arch_name) + + result["tensorflow"][tensorflow_arch.__name__] = {} + error = None + if pt_arch.__name__ in result["pytorch"] and result["pytorch"][pt_arch.__name__]["checkpoint"] is not None: + ckpt = get_checkpoint_dir(output_dir, pt_arch) + # Use the same weights from PyTorch. + try: + model = tensorflow_arch.from_pretrained(ckpt) + model.save_pretrained(ckpt) + except Exception as e: + # Conversion may fail. Let's not create a model with different weights to avoid confusion (for now). + model = None + error = f"Failed to convert the pytorch model to the tensorflow model for {pt_arch}: {e}" + trace = traceback.format_exc() + else: + try: + model = build_model(tensorflow_arch, tiny_config, output_dir=output_dir) + except Exception as e: + model = None + error = f"Failed to create the tensorflow model for {tensorflow_arch}: {e}" + trace = traceback.format_exc() + + result["tensorflow"][tensorflow_arch.__name__]["model"] = ( + model.__class__.__name__ if model is not None else None + ) + result["tensorflow"][tensorflow_arch.__name__]["checkpoint"] = ( + get_checkpoint_dir(output_dir, tensorflow_arch) if model is not None else None + ) + if error is not None: + result["tensorflow"][tensorflow_arch.__name__]["error"] = (error, trace) + logger.error(f"{tensorflow_arch.__name__}: {error}") + + if not result["error"]: + del result["error"] + if not result["warnings"]: + del result["warnings"] + + return result + + +def build_tiny_model_summary(results, organization=None, token=None): + """Build a summary: a dictionary of the form + { + model architecture name: + { + "tokenizer_classes": [...], + "processor_classes": [...], + "model_classes": [...], + } + .. + } + """ + tiny_model_summary = {} + for config_name in results: + processors = [key for key, value in results[config_name]["processor"].items()] + tokenizer_classes = sorted([x for x in processors if x.endswith("TokenizerFast") or x.endswith("Tokenizer")]) + processor_classes = sorted([x for x in processors if x not in tokenizer_classes]) + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + model_classes = [arch_name] + base_arch_name = arch_name[2:] if arch_name.startswith("TF") else arch_name + # tiny model is not created for `arch_name` + if results[config_name][framework][arch_name]["model"] is None: + model_classes = [] + if base_arch_name not in tiny_model_summary: + tiny_model_summary[base_arch_name] = {} + tiny_model_summary[base_arch_name].update( + { + "tokenizer_classes": tokenizer_classes, + "processor_classes": processor_classes, + } + ) + tiny_model_summary[base_arch_name]["model_classes"] = sorted( + tiny_model_summary[base_arch_name].get("model_classes", []) + model_classes + ) + if organization is not None: + repo_name = f"tiny-random-{base_arch_name}" + # composite models' checkpoints have more precise repo. names on the Hub. + if base_arch_name in COMPOSITE_MODELS: + repo_name = f"tiny-random-{COMPOSITE_MODELS[base_arch_name]}" + repo_id = f"{organization}/{repo_name}" + try: + commit_hash = hf_api.repo_info(repo_id, token=token).sha + except Exception: + # The directory is not created, but processor(s) is/are included in `results`. + logger.warning(f"Failed to get information for {repo_id}.\n{traceback.format_exc()}") + del tiny_model_summary[base_arch_name] + continue + tiny_model_summary[base_arch_name]["sha"] = commit_hash + + return tiny_model_summary + + +def build_failed_report(results, include_warning=True): + failed_results = {} + for config_name in results: + if "error" in results[config_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + failed_results[config_name] = {"error": results[config_name]["error"]} + + if include_warning and "warnings" in results[config_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + failed_results[config_name]["warnings"] = results[config_name]["warnings"] + + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + if "error" in results[config_name][framework][arch_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + if framework not in failed_results[config_name]: + failed_results[config_name][framework] = {} + if arch_name not in failed_results[config_name][framework]: + failed_results[config_name][framework][arch_name] = {} + error = results[config_name][framework][arch_name]["error"] + failed_results[config_name][framework][arch_name]["error"] = error + + return failed_results + + +def build_simple_report(results): + text = "" + failed_text = "" + for config_name in results: + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + if "error" in results[config_name][framework][arch_name]: + result = results[config_name][framework][arch_name]["error"] + failed_text += f"{arch_name}: {result[0]}\n" + else: + result = ("OK",) + text += f"{arch_name}: {result[0]}\n" + + return text, failed_text + + +def update_tiny_model_summary_file(report_path): + with open(os.path.join(report_path, "tiny_model_summary.json")) as fp: + new_data = json.load(fp) + with open("tests/utils/tiny_model_summary.json") as fp: + data = json.load(fp) + for key, value in new_data.items(): + if key not in data: + data[key] = value + else: + for attr in ["tokenizer_classes", "processor_classes", "model_classes"]: + # we might get duplication here. We will remove them below when creating `updated_data`. + data[key][attr].extend(value[attr]) + new_sha = value.get("sha", None) + if new_sha is not None: + data[key]["sha"] = new_sha + + updated_data = {} + for key in sorted(data.keys()): + updated_data[key] = {} + for attr, value in data[key].items(): + # deduplication and sort + updated_data[key][attr] = sorted(set(value)) if attr != "sha" else value + + with open(os.path.join(report_path, "updated_tiny_model_summary.json"), "w") as fp: + json.dump(updated_data, fp, indent=4, ensure_ascii=False) + + +def create_tiny_models( + output_path, + all, + model_types, + models_to_skip, + no_check, + upload, + organization, + token, + num_workers=1, +): + clone_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + if os.getcwd() != clone_path: + raise ValueError(f"This script should be run from the root of the clone of `transformers` {clone_path}") + + report_path = os.path.join(output_path, "reports") + os.makedirs(report_path) + + _pytorch_arch_mappings = [ + x + for x in dir(transformers_module) + if x.startswith("MODEL_") and x.endswith("_MAPPING") and x != "MODEL_NAMES_MAPPING" + ] + _tensorflow_arch_mappings = [ + x for x in dir(transformers_module) if x.startswith("TF_MODEL_") and x.endswith("_MAPPING") + ] + + pytorch_arch_mappings = [getattr(transformers_module, x) for x in _pytorch_arch_mappings] + tensorflow_arch_mappings = [getattr(transformers_module, x) for x in _tensorflow_arch_mappings] + + config_classes = CONFIG_MAPPING.values() + if not all: + config_classes = [CONFIG_MAPPING[model_type] for model_type in model_types] + + # A map from config classes to tuples of processors (tokenizer, feature extractor, processor) classes + processor_type_map = {c: get_processor_types_from_config_class(c) for c in config_classes} + + to_create = {} + for c in config_classes: + processors = processor_type_map[c] + models = get_architectures_from_config_class(c, pytorch_arch_mappings, models_to_skip) + tf_models = get_architectures_from_config_class(c, tensorflow_arch_mappings, models_to_skip) + if len(models) + len(tf_models) > 0: + to_create[c] = {"processor": processors, "pytorch": models, "tensorflow": tf_models} + + results = {} + if num_workers <= 1: + for c, models_to_create in list(to_create.items()): + print(f"Create models for {c.__name__} ...") + result = build(c, models_to_create, output_dir=os.path.join(output_path, c.model_type)) + results[c.__name__] = result + print("=" * 40) + else: + all_build_args = [] + for c, models_to_create in list(to_create.items()): + all_build_args.append((c, models_to_create, os.path.join(output_path, c.model_type))) + with multiprocessing.Pool() as pool: + results = pool.starmap(build, all_build_args) + results = {buid_args[0].__name__: result for buid_args, result in zip(all_build_args, results)} + + if upload: + if organization is None: + raise ValueError("The argument `organization` could not be `None`. No model is uploaded") + + to_upload = [] + for model_type in os.listdir(output_path): + # This is the directory containing the reports + if model_type == "reports": + continue + for arch in os.listdir(os.path.join(output_path, model_type)): + if arch == "processors": + continue + to_upload.append(os.path.join(output_path, model_type, arch)) + to_upload = sorted(to_upload) + + upload_results = {} + if len(to_upload) > 0: + for model_dir in to_upload: + try: + upload_model(model_dir, organization, token) + except Exception as e: + error = f"Failed to upload {model_dir}. {e.__class__.__name__}: {e}" + logger.error(error) + upload_results[model_dir] = error + + with open(os.path.join(report_path, "failed_uploads.json"), "w") as fp: + json.dump(upload_results, fp, indent=4) + + # Build the tiny model summary file. The `tokenizer_classes` and `processor_classes` could be both empty lists. + # When using the items in this file to update the file `tests/utils/tiny_model_summary.json`, the model + # architectures with `tokenizer_classes` and `processor_classes` being both empty should **NOT** be added to + # `tests/utils/tiny_model_summary.json`. + tiny_model_summary = build_tiny_model_summary(results, organization=organization, token=token) + with open(os.path.join(report_path, "tiny_model_summary.json"), "w") as fp: + json.dump(tiny_model_summary, fp, indent=4) + + with open(os.path.join(report_path, "tiny_model_creation_report.json"), "w") as fp: + json.dump(results, fp, indent=4) + + # Build the warning/failure report (json format): same format as the complete `results` except this contains only + # warnings or errors. + failed_results = build_failed_report(results) + with open(os.path.join(report_path, "failed_report.json"), "w") as fp: + json.dump(failed_results, fp, indent=4) + + simple_report, failed_report = build_simple_report(results) + # The simplified report: a .txt file with each line of format: + # {model architecture name}: {OK or error message} + with open(os.path.join(report_path, "simple_report.txt"), "w") as fp: + fp.write(simple_report) + + # The simplified failure report: same above except this only contains line with errors + with open(os.path.join(report_path, "simple_failed_report.txt"), "w") as fp: + fp.write(failed_report) + + update_tiny_model_summary_file(report_path=os.path.join(output_path, "reports")) + + +if __name__ == "__main__": + # This has to be `spawn` to avoid hanging forever! + multiprocessing.set_start_method("spawn") + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + parser.add_argument("--all", action="store_true", help="Will create all tiny models.") + parser.add_argument( + "--no_check", + action="store_true", + help="If set, will not check the validity of architectures. Use with caution.", + ) + parser.add_argument( + "-m", + "--model_types", + type=list_str, + help="Comma-separated list of model type(s) from which the tiny models will be created.", + ) + parser.add_argument( + "--models_to_skip", + type=list_str, + help=( + "Comma-separated list of model class names(s) from which the tiny models won't be created.\nThis is usually " + "the list of model classes that have their tiny versions already uploaded to the Hub." + ), + ) + parser.add_argument("--upload", action="store_true", help="If to upload the created tiny models to the Hub.") + parser.add_argument( + "--organization", + default=None, + type=str, + help="The organization on the Hub to which the tiny models will be uploaded.", + ) + parser.add_argument( + "--token", default=None, type=str, help="A valid authentication token for HuggingFace Hub with write access." + ) + parser.add_argument("output_path", type=Path, help="Path indicating where to store generated model.") + parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.") + + args = parser.parse_args() + + if not args.all and not args.model_types: + raise ValueError("Please provide at least one model type or pass `--all` to export all architectures.") + + create_tiny_models( + args.output_path, + args.all, + args.model_types, + args.models_to_skip, + args.no_check, + args.upload, + args.organization, + args.token, + args.num_workers, + ) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/custom_init_isort.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/custom_init_isort.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf2aaffdf4be054c889d74a43484e6e482d1002 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/custom_init_isort.py @@ -0,0 +1,329 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# 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. +""" +Utility that sorts the imports in the custom inits of Transformers. Transformers uses init files that delay the +import of an object to when it's actually needed. This is to avoid the main init importing all models, which would +make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with +delayed imports have two halves: one definining a dictionary `_import_structure` which maps modules to the name of the +objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. `isort` or `ruff` +properly sort the second half which looks like traditionl imports, the goal of this script is to sort the first half. + +Use from the root of the repo with: + +```bash +python utils/custom_init_isort.py +``` + +which will auto-sort the imports (used in `make style`). + +For a check only (as used in `make quality`) run: + +```bash +python utils/custom_init_isort.py --check_only +``` +""" +import argparse +import os +import re +from typing import Any, Callable, List, Optional + + +# Path is defined with the intent you should run this script from the root of the repo. +PATH_TO_TRANSFORMERS = "src/transformers" + +# Pattern that looks at the indentation in a line. +_re_indent = re.compile(r"^(\s*)\S") +# Pattern that matches `"key":" and puts `key` in group 0. +_re_direct_key = re.compile(r'^\s*"([^"]+)":') +# Pattern that matches `_import_structure["key"]` and puts `key` in group 0. +_re_indirect_key = re.compile(r'^\s*_import_structure\["([^"]+)"\]') +# Pattern that matches `"key",` and puts `key` in group 0. +_re_strip_line = re.compile(r'^\s*"([^"]+)",\s*$') +# Pattern that matches any `[stuff]` and puts `stuff` in group 0. +_re_bracket_content = re.compile(r"\[([^\]]+)\]") + + +def get_indent(line: str) -> str: + """Returns the indent in given line (as string).""" + search = _re_indent.search(line) + return "" if search is None else search.groups()[0] + + +def split_code_in_indented_blocks( + code: str, indent_level: str = "", start_prompt: Optional[str] = None, end_prompt: Optional[str] = None +) -> List[str]: + """ + Split some code into its indented blocks, starting at a given level. + + Args: + code (`str`): The code to split. + indent_level (`str`): The indent level (as string) to use for identifying the blocks to split. + start_prompt (`str`, *optional*): If provided, only starts splitting at the line where this text is. + end_prompt (`str`, *optional*): If provided, stops splitting at a line where this text is. + + Warning: + The text before `start_prompt` or after `end_prompt` (if provided) is not ignored, just not split. The input `code` + can thus be retrieved by joining the result. + + Returns: + `List[str]`: The list of blocks. + """ + # Let's split the code into lines and move to start_index. + index = 0 + lines = code.split("\n") + if start_prompt is not None: + while not lines[index].startswith(start_prompt): + index += 1 + blocks = ["\n".join(lines[:index])] + else: + blocks = [] + + # This variable contains the block treated at a given time. + current_block = [lines[index]] + index += 1 + # We split into blocks until we get to the `end_prompt` (or the end of the file). + while index < len(lines) and (end_prompt is None or not lines[index].startswith(end_prompt)): + # We have a non-empty line with the proper indent -> start of a new block + if len(lines[index]) > 0 and get_indent(lines[index]) == indent_level: + # Store the current block in the result and rest. There are two cases: the line is part of the block (like + # a closing parenthesis) or not. + if len(current_block) > 0 and get_indent(current_block[-1]).startswith(indent_level + " "): + # Line is part of the current block + current_block.append(lines[index]) + blocks.append("\n".join(current_block)) + if index < len(lines) - 1: + current_block = [lines[index + 1]] + index += 1 + else: + current_block = [] + else: + # Line is not part of the current block + blocks.append("\n".join(current_block)) + current_block = [lines[index]] + else: + # Just add the line to the current block + current_block.append(lines[index]) + index += 1 + + # Adds current block if it's nonempty. + if len(current_block) > 0: + blocks.append("\n".join(current_block)) + + # Add final block after end_prompt if provided. + if end_prompt is not None and index < len(lines): + blocks.append("\n".join(lines[index:])) + + return blocks + + +def ignore_underscore_and_lowercase(key: Callable[[Any], str]) -> Callable[[Any], str]: + """ + Wraps a key function (as used in a sort) to lowercase and ignore underscores. + """ + + def _inner(x): + return key(x).lower().replace("_", "") + + return _inner + + +def sort_objects(objects: List[Any], key: Optional[Callable[[Any], str]] = None) -> List[Any]: + """ + Sort a list of objects following the rules of isort (all uppercased first, camel-cased second and lower-cased + last). + + Args: + objects (`List[Any]`): + The list of objects to sort. + key (`Callable[[Any], str]`, *optional*): + A function taking an object as input and returning a string, used to sort them by alphabetical order. + If not provided, will default to noop (so a `key` must be provided if the `objects` are not of type string). + + Returns: + `List[Any]`: The sorted list with the same elements as in the inputs + """ + + # If no key is provided, we use a noop. + def noop(x): + return x + + if key is None: + key = noop + # Constants are all uppercase, they go first. + constants = [obj for obj in objects if key(obj).isupper()] + # Classes are not all uppercase but start with a capital, they go second. + classes = [obj for obj in objects if key(obj)[0].isupper() and not key(obj).isupper()] + # Functions begin with a lowercase, they go last. + functions = [obj for obj in objects if not key(obj)[0].isupper()] + + # Then we sort each group. + key1 = ignore_underscore_and_lowercase(key) + return sorted(constants, key=key1) + sorted(classes, key=key1) + sorted(functions, key=key1) + + +def sort_objects_in_import(import_statement: str) -> str: + """ + Sorts the imports in a single import statement. + + Args: + import_statement (`str`): The import statement in which to sort the imports. + + Returns: + `str`: The same as the input, but with objects properly sorted. + """ + + # This inner function sort imports between [ ]. + def _replace(match): + imports = match.groups()[0] + # If there is one import only, nothing to do. + if "," not in imports: + return f"[{imports}]" + keys = [part.strip().replace('"', "") for part in imports.split(",")] + # We will have a final empty element if the line finished with a comma. + if len(keys[-1]) == 0: + keys = keys[:-1] + return "[" + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + "]" + + lines = import_statement.split("\n") + if len(lines) > 3: + # Here we have to sort internal imports that are on several lines (one per name): + # key: [ + # "object1", + # "object2", + # ... + # ] + + # We may have to ignore one or two lines on each side. + idx = 2 if lines[1].strip() == "[" else 1 + keys_to_sort = [(i, _re_strip_line.search(line).groups()[0]) for i, line in enumerate(lines[idx:-idx])] + sorted_indices = sort_objects(keys_to_sort, key=lambda x: x[1]) + sorted_lines = [lines[x[0] + idx] for x in sorted_indices] + return "\n".join(lines[:idx] + sorted_lines + lines[-idx:]) + elif len(lines) == 3: + # Here we have to sort internal imports that are on one separate line: + # key: [ + # "object1", "object2", ... + # ] + if _re_bracket_content.search(lines[1]) is not None: + lines[1] = _re_bracket_content.sub(_replace, lines[1]) + else: + keys = [part.strip().replace('"', "") for part in lines[1].split(",")] + # We will have a final empty element if the line finished with a comma. + if len(keys[-1]) == 0: + keys = keys[:-1] + lines[1] = get_indent(lines[1]) + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + return "\n".join(lines) + else: + # Finally we have to deal with imports fitting on one line + import_statement = _re_bracket_content.sub(_replace, import_statement) + return import_statement + + +def sort_imports(file: str, check_only: bool = True): + """ + Sort the imports defined in the `_import_structure` of a given init. + + Args: + file (`str`): The path to the init to check/fix. + check_only (`bool`, *optional*, defaults to `True`): Whether or not to just check (and not auto-fix) the init. + """ + with open(file, encoding="utf-8") as f: + code = f.read() + + # If the file is not a custom init, there is nothing to do. + if "_import_structure" not in code: + return + + # Blocks of indent level 0 + main_blocks = split_code_in_indented_blocks( + code, start_prompt="_import_structure = {", end_prompt="if TYPE_CHECKING:" + ) + + # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). + for block_idx in range(1, len(main_blocks) - 1): + # Check if the block contains some `_import_structure`s thingy to sort. + block = main_blocks[block_idx] + block_lines = block.split("\n") + + # Get to the start of the imports. + line_idx = 0 + while line_idx < len(block_lines) and "_import_structure" not in block_lines[line_idx]: + # Skip dummy import blocks + if "import dummy" in block_lines[line_idx]: + line_idx = len(block_lines) + else: + line_idx += 1 + if line_idx >= len(block_lines): + continue + + # Ignore beginning and last line: they don't contain anything. + internal_block_code = "\n".join(block_lines[line_idx:-1]) + indent = get_indent(block_lines[1]) + # Slit the internal block into blocks of indent level 1. + internal_blocks = split_code_in_indented_blocks(internal_block_code, indent_level=indent) + # We have two categories of import key: list or _import_structure[key].append/extend + pattern = _re_direct_key if "_import_structure = {" in block_lines[0] else _re_indirect_key + # Grab the keys, but there is a trap: some lines are empty or just comments. + keys = [(pattern.search(b).groups()[0] if pattern.search(b) is not None else None) for b in internal_blocks] + # We only sort the lines with a key. + keys_to_sort = [(i, key) for i, key in enumerate(keys) if key is not None] + sorted_indices = [x[0] for x in sorted(keys_to_sort, key=lambda x: x[1])] + + # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. + count = 0 + reorderded_blocks = [] + for i in range(len(internal_blocks)): + if keys[i] is None: + reorderded_blocks.append(internal_blocks[i]) + else: + block = sort_objects_in_import(internal_blocks[sorted_indices[count]]) + reorderded_blocks.append(block) + count += 1 + + # And we put our main block back together with its first and last line. + main_blocks[block_idx] = "\n".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]]) + + if code != "\n".join(main_blocks): + if check_only: + return True + else: + print(f"Overwriting {file}.") + with open(file, "w", encoding="utf-8") as f: + f.write("\n".join(main_blocks)) + + +def sort_imports_in_all_inits(check_only=True): + """ + Sort the imports defined in the `_import_structure` of all inits in the repo. + + Args: + check_only (`bool`, *optional*, defaults to `True`): Whether or not to just check (and not auto-fix) the init. + """ + failures = [] + for root, _, files in os.walk(PATH_TO_TRANSFORMERS): + if "__init__.py" in files: + result = sort_imports(os.path.join(root, "__init__.py"), check_only=check_only) + if result: + failures = [os.path.join(root, "__init__.py")] + if len(failures) > 0: + raise ValueError(f"Would overwrite {len(failures)} files, run `make style`.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") + args = parser.parse_args() + + sort_imports_in_all_inits(check_only=args.check_only) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/download_glue_data.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/download_glue_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ef482d47de9595816cb9a544e9186ec96c83d549 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/download_glue_data.py @@ -0,0 +1,157 @@ +""" Script for downloading all GLUE data. +Original source: https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e + +Note: for legal reasons, we are unable to host MRPC. +You can either use the version hosted by the SentEval team, which is already tokenized, +or you can download the original data from (https://download.microsoft.com/download/D/4/6/D46FF87A-F6B9-4252-AA8B-3604ED519838/MSRParaphraseCorpus.msi) and extract the data from it manually. +For Windows users, you can run the .msi file. For Mac and Linux users, consider an external library such as 'cabextract' (see below for an example). +You should then rename and place specific files in a folder (see below for an example). + +mkdir MRPC +cabextract MSRParaphraseCorpus.msi -d MRPC +cat MRPC/_2DEC3DBE877E4DB192D17C0256E90F1D | tr -d $'\r' > MRPC/msr_paraphrase_train.txt +cat MRPC/_D7B391F9EAFF4B1B8BCE8F21B20B1B61 | tr -d $'\r' > MRPC/msr_paraphrase_test.txt +rm MRPC/_* +rm MSRParaphraseCorpus.msi + +1/30/19: It looks like SentEval is no longer hosting their extracted and tokenized MRPC data, so you'll need to download the data from the original source for now. +2/11/19: It looks like SentEval actually *is* hosting the extracted data. Hooray! +""" + +import argparse +import os +import sys +import urllib.request +import zipfile + + +TASKS = ["CoLA", "SST", "MRPC", "QQP", "STS", "MNLI", "SNLI", "QNLI", "RTE", "WNLI", "diagnostic"] +TASK2PATH = { + "CoLA": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FCoLA.zip?alt=media&token=46d5e637-3411-4188-bc44-5809b5bfb5f4", + "SST": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSST-2.zip?alt=media&token=aabc5f6b-e466-44a2-b9b4-cf6337f84ac8", + "MRPC": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2Fmrpc_dev_ids.tsv?alt=media&token=ec5c0836-31d5-48f4-b431-7480817f1adc", + "QQP": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQQP.zip?alt=media&token=700c6acf-160d-4d89-81d1-de4191d02cb5", + "STS": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSTS-B.zip?alt=media&token=bddb94a7-8706-4e0d-a694-1109e12273b5", + "MNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FMNLI.zip?alt=media&token=50329ea1-e339-40e2-809c-10c40afff3ce", + "SNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSNLI.zip?alt=media&token=4afcfbb2-ff0c-4b2d-a09a-dbf07926f4df", + "QNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQNLIv2.zip?alt=media&token=6fdcf570-0fc5-4631-8456-9505272d1601", + "RTE": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FRTE.zip?alt=media&token=5efa7e85-a0bb-4f19-8ea2-9e1840f077fb", + "WNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FWNLI.zip?alt=media&token=068ad0a0-ded7-4bd7-99a5-5e00222e0faf", + "diagnostic": "https://storage.googleapis.com/mtl-sentence-representations.appspot.com/tsvsWithoutLabels%2FAX.tsv?GoogleAccessId=firebase-adminsdk-0khhl@mtl-sentence-representations.iam.gserviceaccount.com&Expires=2498860800&Signature=DuQ2CSPt2Yfre0C%2BiISrVYrIFaZH1Lc7hBVZDD4ZyR7fZYOMNOUGpi8QxBmTNOrNPjR3z1cggo7WXFfrgECP6FBJSsURv8Ybrue8Ypt%2FTPxbuJ0Xc2FhDi%2BarnecCBFO77RSbfuz%2Bs95hRrYhTnByqu3U%2FYZPaj3tZt5QdfpH2IUROY8LiBXoXS46LE%2FgOQc%2FKN%2BA9SoscRDYsnxHfG0IjXGwHN%2Bf88q6hOmAxeNPx6moDulUF6XMUAaXCSFU%2BnRO2RDL9CapWxj%2BDl7syNyHhB7987hZ80B%2FwFkQ3MEs8auvt5XW1%2Bd4aCU7ytgM69r8JDCwibfhZxpaa4gd50QXQ%3D%3D", +} + +MRPC_TRAIN = "https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_train.txt" +MRPC_TEST = "https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_test.txt" + + +def download_and_extract(task, data_dir): + print(f"Downloading and extracting {task}...") + data_file = f"{task}.zip" + urllib.request.urlretrieve(TASK2PATH[task], data_file) + with zipfile.ZipFile(data_file) as zip_ref: + zip_ref.extractall(data_dir) + os.remove(data_file) + print("\tCompleted!") + + +def format_mrpc(data_dir, path_to_data): + print("Processing MRPC...") + mrpc_dir = os.path.join(data_dir, "MRPC") + if not os.path.isdir(mrpc_dir): + os.mkdir(mrpc_dir) + if path_to_data: + mrpc_train_file = os.path.join(path_to_data, "msr_paraphrase_train.txt") + mrpc_test_file = os.path.join(path_to_data, "msr_paraphrase_test.txt") + else: + print("Local MRPC data not specified, downloading data from %s" % MRPC_TRAIN) + mrpc_train_file = os.path.join(mrpc_dir, "msr_paraphrase_train.txt") + mrpc_test_file = os.path.join(mrpc_dir, "msr_paraphrase_test.txt") + urllib.request.urlretrieve(MRPC_TRAIN, mrpc_train_file) + urllib.request.urlretrieve(MRPC_TEST, mrpc_test_file) + if not os.path.isfile(mrpc_train_file): + raise ValueError(f"Train data not found at {mrpc_train_file}") + if not os.path.isfile(mrpc_test_file): + raise ValueError(f"Test data not found at {mrpc_test_file}") + urllib.request.urlretrieve(TASK2PATH["MRPC"], os.path.join(mrpc_dir, "dev_ids.tsv")) + + dev_ids = [] + with open(os.path.join(mrpc_dir, "dev_ids.tsv"), encoding="utf8") as ids_fh: + for row in ids_fh: + dev_ids.append(row.strip().split("\t")) + + with open(mrpc_train_file, encoding="utf8") as data_fh, open( + os.path.join(mrpc_dir, "train.tsv"), "w", encoding="utf8" + ) as train_fh, open(os.path.join(mrpc_dir, "dev.tsv"), "w", encoding="utf8") as dev_fh: + header = data_fh.readline() + train_fh.write(header) + dev_fh.write(header) + for row in data_fh: + label, id1, id2, s1, s2 = row.strip().split("\t") + if [id1, id2] in dev_ids: + dev_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2)) + else: + train_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2)) + + with open(mrpc_test_file, encoding="utf8") as data_fh, open( + os.path.join(mrpc_dir, "test.tsv"), "w", encoding="utf8" + ) as test_fh: + header = data_fh.readline() + test_fh.write("index\t#1 ID\t#2 ID\t#1 String\t#2 String\n") + for idx, row in enumerate(data_fh): + label, id1, id2, s1, s2 = row.strip().split("\t") + test_fh.write("%d\t%s\t%s\t%s\t%s\n" % (idx, id1, id2, s1, s2)) + print("\tCompleted!") + + +def download_diagnostic(data_dir): + print("Downloading and extracting diagnostic...") + if not os.path.isdir(os.path.join(data_dir, "diagnostic")): + os.mkdir(os.path.join(data_dir, "diagnostic")) + data_file = os.path.join(data_dir, "diagnostic", "diagnostic.tsv") + urllib.request.urlretrieve(TASK2PATH["diagnostic"], data_file) + print("\tCompleted!") + return + + +def get_tasks(task_names): + task_names = task_names.split(",") + if "all" in task_names: + tasks = TASKS + else: + tasks = [] + for task_name in task_names: + if task_name not in TASKS: + raise ValueError(f"Task {task_name} not found!") + tasks.append(task_name) + return tasks + + +def main(arguments): + parser = argparse.ArgumentParser() + parser.add_argument("--data_dir", help="directory to save data to", type=str, default="glue_data") + parser.add_argument( + "--tasks", help="tasks to download data for as a comma separated string", type=str, default="all" + ) + parser.add_argument( + "--path_to_mrpc", + help="path to directory containing extracted MRPC data, msr_paraphrase_train.txt and msr_paraphrase_text.txt", + type=str, + default="", + ) + args = parser.parse_args(arguments) + + if not os.path.isdir(args.data_dir): + os.mkdir(args.data_dir) + tasks = get_tasks(args.tasks) + + for task in tasks: + if task == "MRPC": + format_mrpc(args.data_dir, args.path_to_mrpc) + elif task == "diagnostic": + download_diagnostic(args.data_dir) + else: + download_and_extract(task, args.data_dir) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/extract_warnings.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/extract_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..38c6ac5ecb9fb3da951905c3e962f5cfea9b500a --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/extract_warnings.py @@ -0,0 +1,134 @@ +import argparse +import json +import os +import time +import zipfile + +from get_ci_error_statistics import download_artifact, get_artifacts_links + +from transformers import logging + + +logger = logging.get_logger(__name__) + + +def extract_warnings_from_single_artifact(artifact_path, targets): + """Extract warnings from a downloaded artifact (in .zip format)""" + selected_warnings = set() + buffer = [] + + def parse_line(fp): + for line in fp: + if isinstance(line, bytes): + line = line.decode("UTF-8") + if "warnings summary (final)" in line: + continue + # This means we are outside the body of a warning + elif not line.startswith(" "): + # process a single warning and move it to `selected_warnings`. + if len(buffer) > 0: + warning = "\n".join(buffer) + # Only keep the warnings specified in `targets` + if any(f": {x}: " in warning for x in targets): + selected_warnings.add(warning) + buffer.clear() + continue + else: + line = line.strip() + buffer.append(line) + + if from_gh: + for filename in os.listdir(artifact_path): + file_path = os.path.join(artifact_path, filename) + if not os.path.isdir(file_path): + # read the file + if filename != "warnings.txt": + continue + with open(file_path) as fp: + parse_line(fp) + else: + try: + with zipfile.ZipFile(artifact_path) as z: + for filename in z.namelist(): + if not os.path.isdir(filename): + # read the file + if filename != "warnings.txt": + continue + with z.open(filename) as fp: + parse_line(fp) + except Exception: + logger.warning( + f"{artifact_path} is either an invalid zip file or something else wrong. This file is skipped." + ) + + return selected_warnings + + +def extract_warnings(artifact_dir, targets): + """Extract warnings from all artifact files""" + + selected_warnings = set() + + paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if (p.endswith(".zip") or from_gh)] + for p in paths: + selected_warnings.update(extract_warnings_from_single_artifact(p, targets)) + + return selected_warnings + + +if __name__ == "__main__": + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + parser.add_argument( + "--output_dir", + type=str, + required=True, + help="Where to store the downloaded artifacts and other result files.", + ) + parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") + # optional parameters + parser.add_argument( + "--targets", + default="DeprecationWarning,UserWarning,FutureWarning", + type=list_str, + help="Comma-separated list of target warning(s) which we want to extract.", + ) + parser.add_argument( + "--from_gh", + action="store_true", + help="If running from a GitHub action workflow and collecting warnings from its artifacts.", + ) + + args = parser.parse_args() + + from_gh = args.from_gh + if from_gh: + # The artifacts have to be downloaded using `actions/download-artifact@v3` + pass + else: + os.makedirs(args.output_dir, exist_ok=True) + + # get download links + artifacts = get_artifacts_links(args.workflow_run_id, token=args.token) + with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: + json.dump(artifacts, fp, ensure_ascii=False, indent=4) + + # download artifacts + for idx, (name, url) in enumerate(artifacts.items()): + print(name) + print(url) + print("=" * 80) + download_artifact(name, url, args.output_dir, args.token) + # Be gentle to GitHub + time.sleep(1) + + # extract warnings from artifacts + selected_warnings = extract_warnings(args.output_dir, args.targets) + selected_warnings = sorted(selected_warnings) + with open(os.path.join(args.output_dir, "selected_warnings.json"), "w", encoding="UTF-8") as fp: + json.dump(selected_warnings, fp, ensure_ascii=False, indent=4) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_ci_error_statistics.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_ci_error_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..93884dda1df6303154e9975eff0ef2b884a8159d --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_ci_error_statistics.py @@ -0,0 +1,277 @@ +import argparse +import json +import math +import os +import time +import traceback +import zipfile +from collections import Counter + +import requests + + +def get_job_links(workflow_run_id, token=None): + """Extract job names and their job links in a GitHub Actions workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" + result = requests.get(url, headers=headers).json() + job_links = {} + + try: + job_links.update({job["name"]: job["html_url"] for job in result["jobs"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + job_links.update({job["name"]: job["html_url"] for job in result["jobs"]}) + + return job_links + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +def get_artifacts_links(worflow_run_id, token=None): + """Get all artifact links from a workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" + result = requests.get(url, headers=headers).json() + artifacts = {} + + try: + artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]}) + + return artifacts + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +def download_artifact(artifact_name, artifact_url, output_dir, token): + """Download a GitHub Action artifact from a URL. + + The URL is of the form `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`, + but it can't be used to download directly. We need to get a redirect URL first. + See https://docs.github.com/en/rest/actions/artifacts#download-an-artifact + """ + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + result = requests.get(artifact_url, headers=headers, allow_redirects=False) + download_url = result.headers["Location"] + response = requests.get(download_url, allow_redirects=True) + file_path = os.path.join(output_dir, f"{artifact_name}.zip") + with open(file_path, "wb") as fp: + fp.write(response.content) + + +def get_errors_from_single_artifact(artifact_zip_path, job_links=None): + """Extract errors from a downloaded artifact (in .zip format)""" + errors = [] + failed_tests = [] + job_name = None + + with zipfile.ZipFile(artifact_zip_path) as z: + for filename in z.namelist(): + if not os.path.isdir(filename): + # read the file + if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: + with z.open(filename) as f: + for line in f: + line = line.decode("UTF-8").strip() + if filename == "failures_line.txt": + try: + # `error_line` is the place where `error` occurs + error_line = line[: line.index(": ")] + error = line[line.index(": ") + len(": ") :] + errors.append([error_line, error]) + except Exception: + # skip un-related lines + pass + elif filename == "summary_short.txt" and line.startswith("FAILED "): + # `test` is the test method that failed + test = line[len("FAILED ") :] + failed_tests.append(test) + elif filename == "job_name.txt": + job_name = line + + if len(errors) != len(failed_tests): + raise ValueError( + f"`errors` and `failed_tests` should have the same number of elements. Got {len(errors)} for `errors` " + f"and {len(failed_tests)} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" + " problem." + ) + + job_link = None + if job_name and job_links: + job_link = job_links.get(job_name, None) + + # A list with elements of the form (line of error, error, failed test) + result = [x + [y] + [job_link] for x, y in zip(errors, failed_tests)] + + return result + + +def get_all_errors(artifact_dir, job_links=None): + """Extract errors from all artifact files""" + + errors = [] + + paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if p.endswith(".zip")] + for p in paths: + errors.extend(get_errors_from_single_artifact(p, job_links=job_links)) + + return errors + + +def reduce_by_error(logs, error_filter=None): + """count each error""" + + counter = Counter() + counter.update([x[1] for x in logs]) + counts = counter.most_common() + r = {} + for error, count in counts: + if error_filter is None or error not in error_filter: + r[error] = {"count": count, "failed_tests": [(x[2], x[0]) for x in logs if x[1] == error]} + + r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True)) + return r + + +def get_model(test): + """Get the model name from a test method""" + test = test.split("::")[0] + if test.startswith("tests/models/"): + test = test.split("/")[2] + else: + test = None + + return test + + +def reduce_by_model(logs, error_filter=None): + """count each error per model""" + + logs = [(x[0], x[1], get_model(x[2])) for x in logs] + logs = [x for x in logs if x[2] is not None] + tests = {x[2] for x in logs} + + r = {} + for test in tests: + counter = Counter() + # count by errors in `test` + counter.update([x[1] for x in logs if x[2] == test]) + counts = counter.most_common() + error_counts = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} + n_errors = sum(error_counts.values()) + if n_errors > 0: + r[test] = {"count": n_errors, "errors": error_counts} + + r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True)) + return r + + +def make_github_table(reduced_by_error): + header = "| no. | error | status |" + sep = "|-:|:-|:-|" + lines = [header, sep] + for error in reduced_by_error: + count = reduced_by_error[error]["count"] + line = f"| {count} | {error[:100]} | |" + lines.append(line) + + return "\n".join(lines) + + +def make_github_table_per_model(reduced_by_model): + header = "| model | no. of errors | major error | count |" + sep = "|-:|-:|-:|-:|" + lines = [header, sep] + for model in reduced_by_model: + count = reduced_by_model[model]["count"] + error, _count = list(reduced_by_model[model]["errors"].items())[0] + line = f"| {model} | {count} | {error[:60]} | {_count} |" + lines.append(line) + + return "\n".join(lines) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + parser.add_argument( + "--output_dir", + type=str, + required=True, + help="Where to store the downloaded artifacts and other result files.", + ) + parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") + args = parser.parse_args() + + os.makedirs(args.output_dir, exist_ok=True) + + _job_links = get_job_links(args.workflow_run_id, token=args.token) + job_links = {} + # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. + # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. + if _job_links: + for k, v in _job_links.items(): + # This is how GitHub actions combine job names. + if " / " in k: + index = k.find(" / ") + k = k[index + len(" / ") :] + job_links[k] = v + with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: + json.dump(job_links, fp, ensure_ascii=False, indent=4) + + artifacts = get_artifacts_links(args.workflow_run_id, token=args.token) + with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: + json.dump(artifacts, fp, ensure_ascii=False, indent=4) + + for idx, (name, url) in enumerate(artifacts.items()): + download_artifact(name, url, args.output_dir, args.token) + # Be gentle to GitHub + time.sleep(1) + + errors = get_all_errors(args.output_dir, job_links=job_links) + + # `e[1]` is the error + counter = Counter() + counter.update([e[1] for e in errors]) + + # print the top 30 most common test errors + most_common = counter.most_common(30) + for item in most_common: + print(item) + + with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: + json.dump(errors, fp, ensure_ascii=False, indent=4) + + reduced_by_error = reduce_by_error(errors) + reduced_by_model = reduce_by_model(errors) + + s1 = make_github_table(reduced_by_error) + s2 = make_github_table_per_model(reduced_by_model) + + with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: + fp.write(s1) + with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: + fp.write(s2) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_github_job_time.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_github_job_time.py new file mode 100644 index 0000000000000000000000000000000000000000..af59081ffd4645470437958410a0fff9df7c64da --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_github_job_time.py @@ -0,0 +1,71 @@ +import argparse +import math +import traceback + +import dateutil.parser as date_parser +import requests + + +def extract_time_from_single_job(job): + """Extract time info from a single job in a GitHub Actions workflow run""" + + job_info = {} + + start = job["started_at"] + end = job["completed_at"] + + start_datetime = date_parser.parse(start) + end_datetime = date_parser.parse(end) + + duration_in_min = round((end_datetime - start_datetime).total_seconds() / 60.0) + + job_info["started_at"] = start + job_info["completed_at"] = end + job_info["duration"] = duration_in_min + + return job_info + + +def get_job_time(workflow_run_id, token=None): + """Extract time info for all jobs in a GitHub Actions workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" + result = requests.get(url, headers=headers).json() + job_time = {} + + try: + job_time.update({job["name"]: extract_time_from_single_job(job) for job in result["jobs"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + job_time.update({job["name"]: extract_time_from_single_job(job) for job in result["jobs"]}) + + return job_time + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +if __name__ == "__main__": + r""" + Example: + + python get_github_job_time.py --workflow_run_id 2945609517 + """ + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + args = parser.parse_args() + + job_time = get_job_time(args.workflow_run_id) + job_time = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) + + for k, v in job_time.items(): + print(f'{k}: {v["duration"]}') diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_modified_files.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_modified_files.py new file mode 100644 index 0000000000000000000000000000000000000000..6c8bdfcdf00c835b68ed9b0eddeaf4d9d517d9cd --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_modified_files.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. + +# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: +# python ./utils/get_modified_files.py utils src tests examples +# +# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered +# since the output of this script is fed into Makefile commands it doesn't print a newline after the results + +import re +import subprocess +import sys + + +fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") +modified_files = ( + subprocess.check_output(f"git diff --diff-filter=d --name-only {fork_point_sha}".split()).decode("utf-8").split() +) + +joined_dirs = "|".join(sys.argv[1:]) +regex = re.compile(rf"^({joined_dirs}).*?\.py$") + +relevant_modified_files = [x for x in modified_files if regex.match(x)] +print(" ".join(relevant_modified_files), end="") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_previous_daily_ci.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_previous_daily_ci.py new file mode 100644 index 0000000000000000000000000000000000000000..4e4cb0a8c10d5c6ebe9ccc7db76f16e7b7936197 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_previous_daily_ci.py @@ -0,0 +1,70 @@ +import os +import zipfile + +import requests +from get_ci_error_statistics import download_artifact, get_artifacts_links + + +def get_daily_ci_runs(token, num_runs=7): + """Get the workflow runs of the scheduled (daily) CI. + + This only selects the runs triggered by the `schedule` event on the `main` branch. + """ + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + # The id of a workflow (not of a workflow run) + workflow_id = "636036" + + url = f"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs" + # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results + url += f"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}" + + result = requests.get(url, headers=headers).json() + + return result["workflow_runs"] + + +def get_last_daily_ci_runs(token): + """Get the last completed workflow run id of the scheduled (daily) CI.""" + workflow_runs = get_daily_ci_runs(token) + workflow_run_id = None + for workflow_run in workflow_runs: + if workflow_run["status"] == "completed": + workflow_run_id = workflow_run["id"] + break + + return workflow_run_id + + +def get_last_daily_ci_artifacts(artifact_names, output_dir, token): + """Get the artifacts of last completed workflow run id of the scheduled (daily) CI.""" + workflow_run_id = get_last_daily_ci_runs(token) + if workflow_run_id is not None: + artifacts_links = get_artifacts_links(worflow_run_id=workflow_run_id, token=token) + for artifact_name in artifact_names: + if artifact_name in artifacts_links: + artifact_url = artifacts_links[artifact_name] + download_artifact( + artifact_name=artifact_name, artifact_url=artifact_url, output_dir=output_dir, token=token + ) + + +def get_last_daily_ci_reports(artifact_names, output_dir, token): + """Get the artifacts' content of the last completed workflow run id of the scheduled (daily) CI.""" + get_last_daily_ci_artifacts(artifact_names, output_dir, token) + + results = {} + for artifact_name in artifact_names: + artifact_zip_path = os.path.join(output_dir, f"{artifact_name}.zip") + if os.path.isfile(artifact_zip_path): + results[artifact_name] = {} + with zipfile.ZipFile(artifact_zip_path) as z: + for filename in z.namelist(): + if not os.path.isdir(filename): + # read the file + with z.open(filename) as f: + results[artifact_name][filename] = f.read().decode("UTF-8") + + return results diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_test_info.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_test_info.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b451e71f3efa2f1b9ea7dd64bb085e848a0d11 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/get_test_info.py @@ -0,0 +1,190 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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 importlib +import os +import sys + + +# This is required to make the module import works (when the python process is running from the root of the repo) +sys.path.append(".") + + +r""" +The argument `test_file` in this file refers to a model test file. This should be a string of the from +`tests/models/*/test_modeling_*.py`. +""" + + +def get_module_path(test_file): + """Return the module path of a model test file.""" + components = test_file.split(os.path.sep) + if components[0:2] != ["tests", "models"]: + raise ValueError( + "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " + f"{test_file} instead." + ) + test_fn = components[-1] + if not test_fn.endswith("py"): + raise ValueError(f"`test_file` should be a python file. Got {test_fn} instead.") + if not test_fn.startswith("test_modeling_"): + raise ValueError( + f"`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead." + ) + + components = components[:-1] + [test_fn.replace(".py", "")] + test_module_path = ".".join(components) + + return test_module_path + + +def get_test_module(test_file): + """Get the module of a model test file.""" + test_module_path = get_module_path(test_file) + test_module = importlib.import_module(test_module_path) + + return test_module + + +def get_tester_classes(test_file): + """Get all classes in a model test file whose names ends with `ModelTester`.""" + tester_classes = [] + test_module = get_test_module(test_file) + for attr in dir(test_module): + if attr.endswith("ModelTester"): + tester_classes.append(getattr(test_module, attr)) + + # sort with class names + return sorted(tester_classes, key=lambda x: x.__name__) + + +def get_test_classes(test_file): + """Get all [test] classes in a model test file with attribute `all_model_classes` that are non-empty. + + These are usually the (model) test classes containing the (non-slow) tests to run and are subclasses of one of the + classes `ModelTesterMixin`, `TFModelTesterMixin` or `FlaxModelTesterMixin`, as well as a subclass of + `unittest.TestCase`. Exceptions include `RagTestMixin` (and its subclasses). + """ + test_classes = [] + test_module = get_test_module(test_file) + for attr in dir(test_module): + attr_value = getattr(test_module, attr) + # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking + # `all_model_classes` is not empty (which also excludes other special classes). + model_classes = getattr(attr_value, "all_model_classes", []) + if len(model_classes) > 0: + test_classes.append(attr_value) + + # sort with class names + return sorted(test_classes, key=lambda x: x.__name__) + + +def get_model_classes(test_file): + """Get all model classes that appear in `all_model_classes` attributes in a model test file.""" + test_classes = get_test_classes(test_file) + model_classes = set() + for test_class in test_classes: + model_classes.update(test_class.all_model_classes) + + # sort with class names + return sorted(model_classes, key=lambda x: x.__name__) + + +def get_model_tester_from_test_class(test_class): + """Get the model tester class of a model test class.""" + test = test_class() + if hasattr(test, "setUp"): + test.setUp() + + model_tester = None + if hasattr(test, "model_tester"): + # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. + if test.model_tester is not None: + model_tester = test.model_tester.__class__ + + return model_tester + + +def get_test_classes_for_model(test_file, model_class): + """Get all [test] classes in `test_file` that have `model_class` in their `all_model_classes`.""" + test_classes = get_test_classes(test_file) + + target_test_classes = [] + for test_class in test_classes: + if model_class in test_class.all_model_classes: + target_test_classes.append(test_class) + + # sort with class names + return sorted(target_test_classes, key=lambda x: x.__name__) + + +def get_tester_classes_for_model(test_file, model_class): + """Get all model tester classes in `test_file` that are associated to `model_class`.""" + test_classes = get_test_classes_for_model(test_file, model_class) + + tester_classes = [] + for test_class in test_classes: + tester_class = get_model_tester_from_test_class(test_class) + if tester_class is not None: + tester_classes.append(tester_class) + + # sort with class names + return sorted(tester_classes, key=lambda x: x.__name__) + + +def get_test_to_tester_mapping(test_file): + """Get a mapping from [test] classes to model tester classes in `test_file`. + + This uses `get_test_classes` which may return classes that are NOT subclasses of `unittest.TestCase`. + """ + test_classes = get_test_classes(test_file) + test_tester_mapping = {test_class: get_model_tester_from_test_class(test_class) for test_class in test_classes} + return test_tester_mapping + + +def get_model_to_test_mapping(test_file): + """Get a mapping from model classes to test classes in `test_file`.""" + model_classes = get_model_classes(test_file) + model_test_mapping = { + model_class: get_test_classes_for_model(test_file, model_class) for model_class in model_classes + } + return model_test_mapping + + +def get_model_to_tester_mapping(test_file): + """Get a mapping from model classes to model tester classes in `test_file`.""" + model_classes = get_model_classes(test_file) + model_to_tester_mapping = { + model_class: get_tester_classes_for_model(test_file, model_class) for model_class in model_classes + } + return model_to_tester_mapping + + +def to_json(o): + """Make the information succinct and easy to read. + + Avoid the full class representation like `` when + displaying the results. Instead, we use class name (`BertForMaskedLM`) for the readability. + """ + if isinstance(o, str): + return o + elif isinstance(o, type): + return o.__name__ + elif isinstance(o, (list, tuple)): + return [to_json(x) for x in o] + elif isinstance(o, dict): + return {to_json(k): to_json(v) for k, v in o.items()} + else: + return o diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/not_doctested.txt b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/not_doctested.txt new file mode 100644 index 0000000000000000000000000000000000000000..2cd16a0283e0cea6f28ec1882c0a3a6a23ca1290 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/not_doctested.txt @@ -0,0 +1,1003 @@ +docs/source/en/_config.py +docs/source/en/accelerate.md +docs/source/en/add_new_model.md +docs/source/en/add_new_pipeline.md +docs/source/en/add_tensorflow_model.md +docs/source/en/attention.md +docs/source/en/benchmarks.md +docs/source/en/bertology.md +docs/source/en/big_models.md +docs/source/en/community.md +docs/source/en/contributing.md +docs/source/en/create_a_model.md +docs/source/en/custom_models.md +docs/source/en/custom_tools.md +docs/source/en/debugging.md +docs/source/en/fast_tokenizers.md +docs/source/en/glossary.md +docs/source/en/hpo_train.md +docs/source/en/index.md +docs/source/en/installation.md +docs/source/en/internal/audio_utils.md +docs/source/en/internal/file_utils.md +docs/source/en/internal/image_processing_utils.md +docs/source/en/internal/modeling_utils.md +docs/source/en/internal/pipelines_utils.md +docs/source/en/internal/time_series_utils.md +docs/source/en/internal/tokenization_utils.md +docs/source/en/internal/trainer_utils.md +docs/source/en/llm_tutorial.md +docs/source/en/main_classes/agent.md +docs/source/en/main_classes/callback.md +docs/source/en/main_classes/configuration.md +docs/source/en/main_classes/data_collator.md +docs/source/en/main_classes/deepspeed.md +docs/source/en/main_classes/feature_extractor.md +docs/source/en/main_classes/image_processor.md +docs/source/en/main_classes/keras_callbacks.md +docs/source/en/main_classes/logging.md +docs/source/en/main_classes/model.md +docs/source/en/main_classes/onnx.md +docs/source/en/main_classes/optimizer_schedules.md +docs/source/en/main_classes/output.md +docs/source/en/main_classes/pipelines.md +docs/source/en/main_classes/processors.md +docs/source/en/main_classes/quantization.md +docs/source/en/main_classes/tokenizer.md +docs/source/en/main_classes/trainer.md +docs/source/en/model_doc/albert.md +docs/source/en/model_doc/align.md +docs/source/en/model_doc/altclip.md +docs/source/en/model_doc/audio-spectrogram-transformer.md +docs/source/en/model_doc/auto.md +docs/source/en/model_doc/autoformer.md +docs/source/en/model_doc/bark.md +docs/source/en/model_doc/bart.md +docs/source/en/model_doc/barthez.md +docs/source/en/model_doc/bartpho.md +docs/source/en/model_doc/beit.md +docs/source/en/model_doc/bert-generation.md +docs/source/en/model_doc/bert-japanese.md +docs/source/en/model_doc/bert.md +docs/source/en/model_doc/bertweet.md +docs/source/en/model_doc/big_bird.md +docs/source/en/model_doc/bigbird_pegasus.md +docs/source/en/model_doc/biogpt.md +docs/source/en/model_doc/bit.md +docs/source/en/model_doc/blenderbot-small.md +docs/source/en/model_doc/blenderbot.md +docs/source/en/model_doc/blip-2.md +docs/source/en/model_doc/blip.md +docs/source/en/model_doc/bloom.md +docs/source/en/model_doc/bort.md +docs/source/en/model_doc/bridgetower.md +docs/source/en/model_doc/camembert.md +docs/source/en/model_doc/canine.md +docs/source/en/model_doc/chinese_clip.md +docs/source/en/model_doc/clap.md +docs/source/en/model_doc/clip.md +docs/source/en/model_doc/clipseg.md +docs/source/en/model_doc/codegen.md +docs/source/en/model_doc/conditional_detr.md +docs/source/en/model_doc/convbert.md +docs/source/en/model_doc/convnext.md +docs/source/en/model_doc/convnextv2.md +docs/source/en/model_doc/cpm.md +docs/source/en/model_doc/cpmant.md +docs/source/en/model_doc/ctrl.md +docs/source/en/model_doc/cvt.md +docs/source/en/model_doc/data2vec.md +docs/source/en/model_doc/deberta-v2.md +docs/source/en/model_doc/deberta.md +docs/source/en/model_doc/decision_transformer.md +docs/source/en/model_doc/deformable_detr.md +docs/source/en/model_doc/deit.md +docs/source/en/model_doc/deplot.md +docs/source/en/model_doc/deta.md +docs/source/en/model_doc/detr.md +docs/source/en/model_doc/dialogpt.md +docs/source/en/model_doc/dinat.md +docs/source/en/model_doc/dinov2.md +docs/source/en/model_doc/distilbert.md +docs/source/en/model_doc/dit.md +docs/source/en/model_doc/dpr.md +docs/source/en/model_doc/dpt.md +docs/source/en/model_doc/efficientformer.md +docs/source/en/model_doc/efficientnet.md +docs/source/en/model_doc/electra.md +docs/source/en/model_doc/encodec.md +docs/source/en/model_doc/ernie.md +docs/source/en/model_doc/ernie_m.md +docs/source/en/model_doc/esm.md +docs/source/en/model_doc/flan-t5.md +docs/source/en/model_doc/flan-ul2.md +docs/source/en/model_doc/flaubert.md +docs/source/en/model_doc/flava.md +docs/source/en/model_doc/fnet.md +docs/source/en/model_doc/focalnet.md +docs/source/en/model_doc/fsmt.md +docs/source/en/model_doc/funnel.md +docs/source/en/model_doc/git.md +docs/source/en/model_doc/glpn.md +docs/source/en/model_doc/gpt-sw3.md +docs/source/en/model_doc/gpt2.md +docs/source/en/model_doc/gpt_bigcode.md +docs/source/en/model_doc/gpt_neo.md +docs/source/en/model_doc/gpt_neox.md +docs/source/en/model_doc/gpt_neox_japanese.md +docs/source/en/model_doc/gptj.md +docs/source/en/model_doc/gptsan-japanese.md +docs/source/en/model_doc/graphormer.md +docs/source/en/model_doc/groupvit.md +docs/source/en/model_doc/herbert.md +docs/source/en/model_doc/hubert.md +docs/source/en/model_doc/ibert.md +docs/source/en/model_doc/idefics.md +docs/source/en/model_doc/imagegpt.md +docs/source/en/model_doc/informer.md +docs/source/en/model_doc/instructblip.md +docs/source/en/model_doc/jukebox.md +docs/source/en/model_doc/layoutlm.md +docs/source/en/model_doc/layoutlmv2.md +docs/source/en/model_doc/layoutlmv3.md +docs/source/en/model_doc/layoutxlm.md +docs/source/en/model_doc/led.md +docs/source/en/model_doc/levit.md +docs/source/en/model_doc/lilt.md +docs/source/en/model_doc/llama.md +docs/source/en/model_doc/llama2.md +docs/source/en/model_doc/llava.md +docs/source/en/model_doc/longformer.md +docs/source/en/model_doc/longt5.md +docs/source/en/model_doc/luke.md +docs/source/en/model_doc/lxmert.md +docs/source/en/model_doc/m2m_100.md +docs/source/en/model_doc/madlad-400.md +docs/source/en/model_doc/marian.md +docs/source/en/model_doc/mask2former.md +docs/source/en/model_doc/maskformer.md +docs/source/en/model_doc/matcha.md +docs/source/en/model_doc/mbart.md +docs/source/en/model_doc/mctct.md +docs/source/en/model_doc/mega.md +docs/source/en/model_doc/megatron-bert.md +docs/source/en/model_doc/megatron_gpt2.md +docs/source/en/model_doc/mgp-str.md +docs/source/en/model_doc/mistral.md +docs/source/en/model_doc/mluke.md +docs/source/en/model_doc/mms.md +docs/source/en/model_doc/mobilebert.md +docs/source/en/model_doc/mobilenet_v1.md +docs/source/en/model_doc/mobilenet_v2.md +docs/source/en/model_doc/mobilevit.md +docs/source/en/model_doc/mobilevitv2.md +docs/source/en/model_doc/mpnet.md +docs/source/en/model_doc/mpt.md +docs/source/en/model_doc/mra.md +docs/source/en/model_doc/mt5.md +docs/source/en/model_doc/musicgen.md +docs/source/en/model_doc/mvp.md +docs/source/en/model_doc/nat.md +docs/source/en/model_doc/nezha.md +docs/source/en/model_doc/nllb-moe.md +docs/source/en/model_doc/nllb.md +docs/source/en/model_doc/nystromformer.md +docs/source/en/model_doc/oneformer.md +docs/source/en/model_doc/open-llama.md +docs/source/en/model_doc/openai-gpt.md +docs/source/en/model_doc/opt.md +docs/source/en/model_doc/owlvit.md +docs/source/en/model_doc/pegasus.md +docs/source/en/model_doc/pegasus_x.md +docs/source/en/model_doc/perceiver.md +docs/source/en/model_doc/phobert.md +docs/source/en/model_doc/pix2struct.md +docs/source/en/model_doc/plbart.md +docs/source/en/model_doc/poolformer.md +docs/source/en/model_doc/pop2piano.md +docs/source/en/model_doc/prophetnet.md +docs/source/en/model_doc/pvt.md +docs/source/en/model_doc/qdqbert.md +docs/source/en/model_doc/rag.md +docs/source/en/model_doc/realm.md +docs/source/en/model_doc/reformer.md +docs/source/en/model_doc/regnet.md +docs/source/en/model_doc/rembert.md +docs/source/en/model_doc/resnet.md +docs/source/en/model_doc/retribert.md +docs/source/en/model_doc/roberta-prelayernorm.md +docs/source/en/model_doc/roberta.md +docs/source/en/model_doc/roc_bert.md +docs/source/en/model_doc/roformer.md +docs/source/en/model_doc/rwkv.md +docs/source/en/model_doc/sam.md +docs/source/en/model_doc/segformer.md +docs/source/en/model_doc/sew-d.md +docs/source/en/model_doc/sew.md +docs/source/en/model_doc/speech-encoder-decoder.md +docs/source/en/model_doc/speech_to_text_2.md +docs/source/en/model_doc/speecht5.md +docs/source/en/model_doc/splinter.md +docs/source/en/model_doc/squeezebert.md +docs/source/en/model_doc/swiftformer.md +docs/source/en/model_doc/swin.md +docs/source/en/model_doc/swin2sr.md +docs/source/en/model_doc/swinv2.md +docs/source/en/model_doc/table-transformer.md +docs/source/en/model_doc/tapas.md +docs/source/en/model_doc/time_series_transformer.md +docs/source/en/model_doc/timesformer.md +docs/source/en/model_doc/trajectory_transformer.md +docs/source/en/model_doc/transfo-xl.md +docs/source/en/model_doc/trocr.md +docs/source/en/model_doc/tvlt.md +docs/source/en/model_doc/ul2.md +docs/source/en/model_doc/umt5.md +docs/source/en/model_doc/unispeech-sat.md +docs/source/en/model_doc/unispeech.md +docs/source/en/model_doc/upernet.md +docs/source/en/model_doc/van.md +docs/source/en/model_doc/videomae.md +docs/source/en/model_doc/vilt.md +docs/source/en/model_doc/vipllava.md +docs/source/en/model_doc/vision-encoder-decoder.md +docs/source/en/model_doc/vision-text-dual-encoder.md +docs/source/en/model_doc/visual_bert.md +docs/source/en/model_doc/vit.md +docs/source/en/model_doc/vit_hybrid.md +docs/source/en/model_doc/vit_mae.md +docs/source/en/model_doc/vit_msn.md +docs/source/en/model_doc/vivit.md +docs/source/en/model_doc/wav2vec2-conformer.md +docs/source/en/model_doc/wav2vec2.md +docs/source/en/model_doc/wav2vec2_phoneme.md +docs/source/en/model_doc/wavlm.md +docs/source/en/model_doc/whisper.md +docs/source/en/model_doc/xclip.md +docs/source/en/model_doc/xglm.md +docs/source/en/model_doc/xlm-prophetnet.md +docs/source/en/model_doc/xlm-roberta-xl.md +docs/source/en/model_doc/xlm-roberta.md +docs/source/en/model_doc/xlm-v.md +docs/source/en/model_doc/xlm.md +docs/source/en/model_doc/xlnet.md +docs/source/en/model_doc/xls_r.md +docs/source/en/model_doc/xlsr_wav2vec2.md +docs/source/en/model_doc/xmod.md +docs/source/en/model_doc/yolos.md +docs/source/en/model_doc/yoso.md +docs/source/en/model_memory_anatomy.md +docs/source/en/model_sharing.md +docs/source/en/model_summary.md +docs/source/en/multilingual.md +docs/source/en/notebooks.md +docs/source/en/pad_truncation.md +docs/source/en/peft.md +docs/source/en/perf_hardware.md +docs/source/en/perf_infer_cpu.md +docs/source/en/perf_infer_gpu_one.md +docs/source/en/perf_torch_compile.md +docs/source/en/perf_train_cpu.md +docs/source/en/perf_train_cpu_many.md +docs/source/en/perf_train_gpu_many.md +docs/source/en/perf_train_gpu_one.md +docs/source/en/perf_train_special.md +docs/source/en/perf_train_tpu.md +docs/source/en/perf_train_tpu_tf.md +docs/source/en/performance.md +docs/source/en/perplexity.md +docs/source/en/philosophy.md +docs/source/en/pipeline_webserver.md +docs/source/en/pr_checks.md +docs/source/en/preprocessing.md +docs/source/en/run_scripts.md +docs/source/en/sagemaker.md +docs/source/en/serialization.md +docs/source/en/tasks/asr.md +docs/source/en/tasks/audio_classification.md +docs/source/en/tasks/document_question_answering.md +docs/source/en/tasks/idefics.md +docs/source/en/tasks/image_captioning.md +docs/source/en/tasks/image_classification.md +docs/source/en/tasks/language_modeling.md +docs/source/en/tasks/masked_language_modeling.md +docs/source/en/tasks/monocular_depth_estimation.md +docs/source/en/tasks/multiple_choice.md +docs/source/en/tasks/object_detection.md +docs/source/en/tasks/question_answering.md +docs/source/en/tasks/semantic_segmentation.md +docs/source/en/tasks/sequence_classification.md +docs/source/en/tasks/summarization.md +docs/source/en/tasks/text-to-speech.md +docs/source/en/tasks/token_classification.md +docs/source/en/tasks/translation.md +docs/source/en/tasks/video_classification.md +docs/source/en/tasks/visual_question_answering.md +docs/source/en/tasks/zero_shot_image_classification.md +docs/source/en/tasks/zero_shot_object_detection.md +docs/source/en/tasks_explained.md +docs/source/en/tf_xla.md +docs/source/en/tflite.md +docs/source/en/tokenizer_summary.md +docs/source/en/torchscript.md +docs/source/en/training.md +docs/source/en/transformers_agents.md +docs/source/en/troubleshooting.md +src/transformers/activations.py +src/transformers/activations_tf.py +src/transformers/audio_utils.py +src/transformers/benchmark/benchmark.py +src/transformers/benchmark/benchmark_args.py +src/transformers/benchmark/benchmark_args_tf.py +src/transformers/benchmark/benchmark_args_utils.py +src/transformers/benchmark/benchmark_tf.py +src/transformers/benchmark/benchmark_utils.py +src/transformers/commands/add_new_model.py +src/transformers/commands/add_new_model_like.py +src/transformers/commands/convert.py +src/transformers/commands/download.py +src/transformers/commands/env.py +src/transformers/commands/lfs.py +src/transformers/commands/pt_to_tf.py +src/transformers/commands/run.py +src/transformers/commands/serving.py +src/transformers/commands/train.py +src/transformers/commands/transformers_cli.py +src/transformers/commands/user.py +src/transformers/configuration_utils.py +src/transformers/convert_graph_to_onnx.py +src/transformers/convert_pytorch_checkpoint_to_tf2.py +src/transformers/convert_slow_tokenizer.py +src/transformers/convert_slow_tokenizers_checkpoints_to_fast.py +src/transformers/convert_tf_hub_seq_to_seq_bert_to_pytorch.py +src/transformers/data/data_collator.py +src/transformers/data/datasets/glue.py +src/transformers/data/datasets/language_modeling.py +src/transformers/data/datasets/squad.py +src/transformers/data/metrics/squad_metrics.py +src/transformers/data/processors/glue.py +src/transformers/data/processors/squad.py +src/transformers/data/processors/utils.py +src/transformers/data/processors/xnli.py +src/transformers/debug_utils.py +src/transformers/deepspeed.py +src/transformers/dependency_versions_check.py +src/transformers/dependency_versions_table.py +src/transformers/dynamic_module_utils.py +src/transformers/feature_extraction_sequence_utils.py +src/transformers/feature_extraction_utils.py +src/transformers/file_utils.py +src/transformers/hf_argparser.py +src/transformers/hyperparameter_search.py +src/transformers/image_processing_utils.py +src/transformers/image_transforms.py +src/transformers/image_utils.py +src/transformers/integrations/bitsandbytes.py +src/transformers/integrations/deepspeed.py +src/transformers/integrations/integration_utils.py +src/transformers/integrations/peft.py +src/transformers/keras_callbacks.py +src/transformers/modelcard.py +src/transformers/modeling_flax_outputs.py +src/transformers/modeling_flax_pytorch_utils.py +src/transformers/modeling_flax_utils.py +src/transformers/modeling_outputs.py +src/transformers/modeling_tf_outputs.py +src/transformers/modeling_tf_pytorch_utils.py +src/transformers/modeling_tf_utils.py +src/transformers/modeling_utils.py +src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/albert/modeling_flax_albert.py +src/transformers/models/align/configuration_align.py +src/transformers/models/align/convert_align_tf_to_hf.py +src/transformers/models/align/modeling_align.py +src/transformers/models/altclip/configuration_altclip.py +src/transformers/models/altclip/modeling_altclip.py +src/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py +src/transformers/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py +src/transformers/models/auto/auto_factory.py +src/transformers/models/auto/configuration_auto.py +src/transformers/models/auto/modeling_auto.py +src/transformers/models/auto/modeling_flax_auto.py +src/transformers/models/auto/modeling_tf_auto.py +src/transformers/models/autoformer/configuration_autoformer.py +src/transformers/models/autoformer/modeling_autoformer.py +src/transformers/models/bark/convert_suno_to_hf.py +src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/bart/modeling_flax_bart.py +src/transformers/models/bart/modeling_tf_bart.py +src/transformers/models/beit/convert_beit_unilm_to_pytorch.py +src/transformers/models/beit/modeling_flax_beit.py +src/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py +src/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py +src/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py +src/transformers/models/bert/modeling_flax_bert.py +src/transformers/models/bert_generation/modeling_bert_generation.py +src/transformers/models/big_bird/convert_bigbird_original_tf_checkpoint_to_pytorch.py +src/transformers/models/big_bird/modeling_flax_big_bird.py +src/transformers/models/bigbird_pegasus/convert_bigbird_pegasus_tf_to_pytorch.py +src/transformers/models/biogpt/configuration_biogpt.py +src/transformers/models/biogpt/convert_biogpt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/biogpt/modeling_biogpt.py +src/transformers/models/bit/configuration_bit.py +src/transformers/models/bit/convert_bit_to_pytorch.py +src/transformers/models/bit/modeling_bit.py +src/transformers/models/blenderbot/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/blenderbot/modeling_flax_blenderbot.py +src/transformers/models/blenderbot/modeling_tf_blenderbot.py +src/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py +src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py +src/transformers/models/blip/configuration_blip.py +src/transformers/models/blip/convert_blip_original_pytorch_to_hf.py +src/transformers/models/blip/modeling_blip_text.py +src/transformers/models/blip/modeling_tf_blip_text.py +src/transformers/models/blip_2/configuration_blip_2.py +src/transformers/models/blip_2/convert_blip_2_original_to_pytorch.py +src/transformers/models/blip_2/modeling_blip_2.py +src/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py +src/transformers/models/bloom/modeling_bloom.py +src/transformers/models/bloom/modeling_flax_bloom.py +src/transformers/models/bridgetower/configuration_bridgetower.py +src/transformers/models/bridgetower/modeling_bridgetower.py +src/transformers/models/bros/convert_bros_to_pytorch.py +src/transformers/models/byt5/convert_byt5_original_tf_checkpoint_to_pytorch.py +src/transformers/models/camembert/modeling_camembert.py +src/transformers/models/camembert/modeling_tf_camembert.py +src/transformers/models/canine/convert_canine_original_tf_checkpoint_to_pytorch.py +src/transformers/models/chinese_clip/configuration_chinese_clip.py +src/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py +src/transformers/models/chinese_clip/modeling_chinese_clip.py +src/transformers/models/clap/convert_clap_original_pytorch_to_hf.py +src/transformers/models/clip/convert_clip_original_pytorch_to_hf.py +src/transformers/models/clip/modeling_clip.py +src/transformers/models/clip/modeling_flax_clip.py +src/transformers/models/clip/modeling_tf_clip.py +src/transformers/models/clipseg/configuration_clipseg.py +src/transformers/models/clipseg/convert_clipseg_original_pytorch_to_hf.py +src/transformers/models/codegen/modeling_codegen.py +src/transformers/models/conditional_detr/convert_conditional_detr_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py +src/transformers/models/convbert/modeling_convbert.py +src/transformers/models/convbert/modeling_tf_convbert.py +src/transformers/models/convnext/convert_convnext_to_pytorch.py +src/transformers/models/convnext/modeling_tf_convnext.py +src/transformers/models/convnextv2/configuration_convnextv2.py +src/transformers/models/convnextv2/convert_convnextv2_to_pytorch.py +src/transformers/models/convnextv2/modeling_convnextv2.py +src/transformers/models/cpmant/configuration_cpmant.py +src/transformers/models/cpmant/modeling_cpmant.py +src/transformers/models/cpmant/tokenization_cpmant.py +src/transformers/models/ctrl/modeling_tf_ctrl.py +src/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/cvt/modeling_tf_cvt.py +src/transformers/models/data2vec/convert_data2vec_audio_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/convert_data2vec_text_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/convert_data2vec_vision_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/modeling_data2vec_text.py +src/transformers/models/data2vec/modeling_tf_data2vec_vision.py +src/transformers/models/deberta/modeling_tf_deberta.py +src/transformers/models/deberta_v2/modeling_tf_deberta_v2.py +src/transformers/models/decision_transformer/modeling_decision_transformer.py +src/transformers/models/deformable_detr/convert_deformable_detr_to_pytorch.py +src/transformers/models/deformable_detr/load_custom.py +src/transformers/models/deit/convert_deit_timm_to_pytorch.py +src/transformers/models/deprecated/bort/convert_bort_original_gluonnlp_checkpoint_to_pytorch.py +src/transformers/models/deprecated/mctct/configuration_mctct.py +src/transformers/models/deprecated/mctct/feature_extraction_mctct.py +src/transformers/models/deprecated/mctct/modeling_mctct.py +src/transformers/models/deprecated/mctct/processing_mctct.py +src/transformers/models/deprecated/mmbt/configuration_mmbt.py +src/transformers/models/deprecated/mmbt/modeling_mmbt.py +src/transformers/models/deprecated/open_llama/configuration_open_llama.py +src/transformers/models/deprecated/open_llama/modeling_open_llama.py +src/transformers/models/deprecated/retribert/configuration_retribert.py +src/transformers/models/deprecated/retribert/modeling_retribert.py +src/transformers/models/deprecated/retribert/tokenization_retribert.py +src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py +src/transformers/models/deprecated/tapex/tokenization_tapex.py +src/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py +src/transformers/models/deprecated/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py +src/transformers/models/deprecated/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py +src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py +src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py +src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py +src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py +src/transformers/models/deprecated/van/configuration_van.py +src/transformers/models/deprecated/van/convert_van_to_pytorch.py +src/transformers/models/deprecated/van/modeling_van.py +src/transformers/models/deta/convert_deta_resnet_to_pytorch.py +src/transformers/models/deta/convert_deta_swin_to_pytorch.py +src/transformers/models/detr/convert_detr_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/detr/convert_detr_to_pytorch.py +src/transformers/models/dialogpt/convert_dialogpt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/dinov2/configuration_dinov2.py +src/transformers/models/dinov2/convert_dinov2_to_hf.py +src/transformers/models/dinov2/modeling_dinov2.py +src/transformers/models/distilbert/modeling_distilbert.py +src/transformers/models/distilbert/modeling_flax_distilbert.py +src/transformers/models/distilbert/modeling_tf_distilbert.py +src/transformers/models/dit/convert_dit_unilm_to_pytorch.py +src/transformers/models/donut/configuration_donut_swin.py +src/transformers/models/donut/convert_donut_to_pytorch.py +src/transformers/models/donut/modeling_donut_swin.py +src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py +src/transformers/models/dpr/modeling_dpr.py +src/transformers/models/dpr/modeling_tf_dpr.py +src/transformers/models/dpt/configuration_dpt.py +src/transformers/models/dpt/convert_dpt_hybrid_to_pytorch.py +src/transformers/models/dpt/convert_dpt_to_pytorch.py +src/transformers/models/efficientformer/configuration_efficientformer.py +src/transformers/models/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/efficientformer/modeling_efficientformer.py +src/transformers/models/efficientnet/configuration_efficientnet.py +src/transformers/models/efficientnet/convert_efficientnet_to_pytorch.py +src/transformers/models/efficientnet/modeling_efficientnet.py +src/transformers/models/electra/convert_electra_original_tf_checkpoint_to_pytorch.py +src/transformers/models/electra/modeling_flax_electra.py +src/transformers/models/encodec/configuration_encodec.py +src/transformers/models/encodec/convert_encodec_checkpoint_to_pytorch.py +src/transformers/models/encoder_decoder/modeling_encoder_decoder.py +src/transformers/models/encoder_decoder/modeling_flax_encoder_decoder.py +src/transformers/models/encoder_decoder/modeling_tf_encoder_decoder.py +src/transformers/models/ernie/modeling_ernie.py +src/transformers/models/esm/configuration_esm.py +src/transformers/models/esm/convert_esm.py +src/transformers/models/esm/modeling_esm.py +src/transformers/models/esm/modeling_esmfold.py +src/transformers/models/esm/modeling_tf_esm.py +src/transformers/models/esm/openfold_utils/chunk_utils.py +src/transformers/models/esm/openfold_utils/data_transforms.py +src/transformers/models/esm/openfold_utils/feats.py +src/transformers/models/esm/openfold_utils/loss.py +src/transformers/models/esm/openfold_utils/protein.py +src/transformers/models/esm/openfold_utils/residue_constants.py +src/transformers/models/esm/openfold_utils/rigid_utils.py +src/transformers/models/esm/openfold_utils/tensor_utils.py +src/transformers/models/falcon/configuration_falcon.py +src/transformers/models/falcon/modeling_falcon.py +src/transformers/models/flaubert/configuration_flaubert.py +src/transformers/models/flaubert/modeling_flaubert.py +src/transformers/models/flaubert/modeling_tf_flaubert.py +src/transformers/models/flava/convert_dalle_to_flava_codebook.py +src/transformers/models/flava/convert_flava_original_pytorch_to_hf.py +src/transformers/models/flava/modeling_flava.py +src/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py +src/transformers/models/fnet/modeling_fnet.py +src/transformers/models/focalnet/configuration_focalnet.py +src/transformers/models/focalnet/convert_focalnet_to_hf_format.py +src/transformers/models/focalnet/modeling_focalnet.py +src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/fsmt/modeling_fsmt.py +src/transformers/models/funnel/configuration_funnel.py +src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py +src/transformers/models/funnel/modeling_funnel.py +src/transformers/models/funnel/modeling_tf_funnel.py +src/transformers/models/fuyu/convert_fuyu_model_weights_to_hf.py +src/transformers/models/git/configuration_git.py +src/transformers/models/git/convert_git_to_pytorch.py +src/transformers/models/glpn/configuration_glpn.py +src/transformers/models/glpn/convert_glpn_to_pytorch.py +src/transformers/models/gpt2/CONVERSION.md +src/transformers/models/gpt2/convert_gpt2_original_tf_checkpoint_to_pytorch.py +src/transformers/models/gpt2/modeling_flax_gpt2.py +src/transformers/models/gpt2/modeling_tf_gpt2.py +src/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py +src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py +src/transformers/models/gpt_neo/convert_gpt_neo_mesh_tf_to_pytorch.py +src/transformers/models/gpt_neo/modeling_flax_gpt_neo.py +src/transformers/models/gpt_neo/modeling_gpt_neo.py +src/transformers/models/gpt_neox/modeling_gpt_neox.py +src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py +src/transformers/models/gpt_sw3/convert_megatron_to_pytorch.py +src/transformers/models/gptj/configuration_gptj.py +src/transformers/models/gptj/modeling_flax_gptj.py +src/transformers/models/gptj/modeling_tf_gptj.py +src/transformers/models/gptsan_japanese/configuration_gptsan_japanese.py +src/transformers/models/gptsan_japanese/convert_gptsan_tf_checkpoint_to_pytorch.py +src/transformers/models/gptsan_japanese/modeling_gptsan_japanese.py +src/transformers/models/graphormer/collating_graphormer.py +src/transformers/models/graphormer/configuration_graphormer.py +src/transformers/models/graphormer/modeling_graphormer.py +src/transformers/models/groupvit/configuration_groupvit.py +src/transformers/models/groupvit/convert_groupvit_nvlab_to_hf.py +src/transformers/models/hubert/configuration_hubert.py +src/transformers/models/hubert/convert_distilhubert_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/hubert/convert_hubert_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/hubert/convert_hubert_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/hubert/modeling_tf_hubert.py +src/transformers/models/ibert/configuration_ibert.py +src/transformers/models/ibert/modeling_ibert.py +src/transformers/models/ibert/quant_modules.py +src/transformers/models/idefics/configuration_idefics.py +src/transformers/models/idefics/image_processing_idefics.py +src/transformers/models/idefics/modeling_idefics.py +src/transformers/models/idefics/perceiver.py +src/transformers/models/idefics/processing_idefics.py +src/transformers/models/idefics/vision.py +src/transformers/models/imagegpt/convert_imagegpt_original_tf2_to_pytorch.py +src/transformers/models/informer/configuration_informer.py +src/transformers/models/informer/modeling_informer.py +src/transformers/models/instructblip/configuration_instructblip.py +src/transformers/models/instructblip/convert_instructblip_original_to_pytorch.py +src/transformers/models/instructblip/modeling_instructblip.py +src/transformers/models/instructblip/processing_instructblip.py +src/transformers/models/jukebox/configuration_jukebox.py +src/transformers/models/jukebox/convert_jukebox.py +src/transformers/models/jukebox/modeling_jukebox.py +src/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/led/configuration_led.py +src/transformers/models/led/modeling_led.py +src/transformers/models/led/modeling_tf_led.py +src/transformers/models/levit/convert_levit_timm_to_pytorch.py +src/transformers/models/levit/modeling_levit.py +src/transformers/models/lilt/configuration_lilt.py +src/transformers/models/llama/configuration_llama.py +src/transformers/models/llama/convert_llama_weights_to_hf.py +src/transformers/models/llama/modeling_llama.py +src/transformers/models/llava/configuration_llava.py +src/transformers/models/llava/modeling_llava.py +src/transformers/models/longformer/configuration_longformer.py +src/transformers/models/longformer/convert_longformer_original_pytorch_lightning_to_pytorch.py +src/transformers/models/longt5/configuration_longt5.py +src/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py +src/transformers/models/longt5/modeling_flax_longt5.py +src/transformers/models/luke/configuration_luke.py +src/transformers/models/luke/convert_luke_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/luke/modeling_luke.py +src/transformers/models/lxmert/configuration_lxmert.py +src/transformers/models/lxmert/convert_lxmert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/lxmert/modeling_lxmert.py +src/transformers/models/lxmert/modeling_tf_lxmert.py +src/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py +src/transformers/models/m2m_100/modeling_m2m_100.py +src/transformers/models/marian/configuration_marian.py +src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py +src/transformers/models/marian/convert_marian_to_pytorch.py +src/transformers/models/marian/modeling_flax_marian.py +src/transformers/models/marian/modeling_tf_marian.py +src/transformers/models/markuplm/configuration_markuplm.py +src/transformers/models/markuplm/feature_extraction_markuplm.py +src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/maskformer/configuration_maskformer_swin.py +src/transformers/models/maskformer/convert_maskformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/maskformer/convert_maskformer_resnet_to_pytorch.py +src/transformers/models/maskformer/convert_maskformer_swin_to_pytorch.py +src/transformers/models/maskformer/modeling_maskformer_swin.py +src/transformers/models/mbart/convert_mbart_original_checkpoint_to_pytorch.py +src/transformers/models/mbart/modeling_flax_mbart.py +src/transformers/models/mega/configuration_mega.py +src/transformers/models/mega/convert_mega_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/mega/modeling_mega.py +src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py +src/transformers/models/megatron_bert/modeling_megatron_bert.py +src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py +src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py +src/transformers/models/mgp_str/configuration_mgp_str.py +src/transformers/models/mgp_str/modeling_mgp_str.py +src/transformers/models/mistral/configuration_mistral.py +src/transformers/models/mistral/modeling_mistral.py +src/transformers/models/mixtral/configuration_mixtral.py +src/transformers/models/mixtral/modeling_mixtral.py +src/transformers/models/mluke/convert_mluke_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilenet_v1/configuration_mobilenet_v1.py +src/transformers/models/mobilenet_v1/convert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilenet_v2/configuration_mobilenet_v2.py +src/transformers/models/mobilenet_v2/convert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilevit/configuration_mobilevit.py +src/transformers/models/mobilevit/convert_mlcvnets_to_pytorch.py +src/transformers/models/mobilevitv2/convert_mlcvnets_to_pytorch.py +src/transformers/models/mpnet/configuration_mpnet.py +src/transformers/models/mpnet/modeling_mpnet.py +src/transformers/models/mpnet/modeling_tf_mpnet.py +src/transformers/models/mpt/configuration_mpt.py +src/transformers/models/mpt/modeling_mpt.py +src/transformers/models/mra/configuration_mra.py +src/transformers/models/mra/convert_mra_pytorch_to_pytorch.py +src/transformers/models/mra/modeling_mra.py +src/transformers/models/mt5/configuration_mt5.py +src/transformers/models/mt5/modeling_flax_mt5.py +src/transformers/models/mt5/modeling_mt5.py +src/transformers/models/mt5/modeling_tf_mt5.py +src/transformers/models/musicgen/convert_musicgen_transformers.py +src/transformers/models/mvp/modeling_mvp.py +src/transformers/models/nezha/modeling_nezha.py +src/transformers/models/nllb_moe/configuration_nllb_moe.py +src/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py +src/transformers/models/nllb_moe/modeling_nllb_moe.py +src/transformers/models/nougat/convert_nougat_to_hf.py +src/transformers/models/nystromformer/configuration_nystromformer.py +src/transformers/models/nystromformer/convert_nystromformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/nystromformer/modeling_nystromformer.py +src/transformers/models/oneformer/convert_to_hf_oneformer.py +src/transformers/models/openai/convert_openai_original_tf_checkpoint_to_pytorch.py +src/transformers/models/openai/modeling_openai.py +src/transformers/models/openai/modeling_tf_openai.py +src/transformers/models/opt/convert_opt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/opt/modeling_flax_opt.py +src/transformers/models/owlvit/configuration_owlvit.py +src/transformers/models/owlvit/convert_owlvit_original_flax_to_hf.py +src/transformers/models/pegasus/convert_pegasus_tf_to_pytorch.py +src/transformers/models/pegasus/modeling_flax_pegasus.py +src/transformers/models/pegasus/modeling_tf_pegasus.py +src/transformers/models/pegasus_x/modeling_pegasus_x.py +src/transformers/models/perceiver/configuration_perceiver.py +src/transformers/models/perceiver/convert_perceiver_haiku_to_pytorch.py +src/transformers/models/persimmon/convert_persimmon_weights_to_hf.py +src/transformers/models/persimmon/modeling_persimmon.py +src/transformers/models/pix2struct/configuration_pix2struct.py +src/transformers/models/pix2struct/convert_pix2struct_original_pytorch_to_hf.py +src/transformers/models/pix2struct/image_processing_pix2struct.py +src/transformers/models/pix2struct/processing_pix2struct.py +src/transformers/models/plbart/convert_plbart_original_checkpoint_to_torch.py +src/transformers/models/poolformer/convert_poolformer_original_to_pytorch.py +src/transformers/models/pop2piano/convert_pop2piano_weights_to_hf.py +src/transformers/models/pop2piano/feature_extraction_pop2piano.py +src/transformers/models/pop2piano/processing_pop2piano.py +src/transformers/models/pop2piano/tokenization_pop2piano.py +src/transformers/models/prophetnet/configuration_prophetnet.py +src/transformers/models/prophetnet/convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/prophetnet/modeling_prophetnet.py +src/transformers/models/pvt/configuration_pvt.py +src/transformers/models/pvt/convert_pvt_to_pytorch.py +src/transformers/models/pvt/image_processing_pvt.py +src/transformers/models/pvt/modeling_pvt.py +src/transformers/models/qdqbert/configuration_qdqbert.py +src/transformers/models/qdqbert/modeling_qdqbert.py +src/transformers/models/rag/configuration_rag.py +src/transformers/models/rag/modeling_rag.py +src/transformers/models/rag/modeling_tf_rag.py +src/transformers/models/rag/retrieval_rag.py +src/transformers/models/realm/modeling_realm.py +src/transformers/models/realm/retrieval_realm.py +src/transformers/models/reformer/convert_reformer_trax_checkpoint_to_pytorch.py +src/transformers/models/regnet/configuration_regnet.py +src/transformers/models/regnet/convert_regnet_seer_10b_to_pytorch.py +src/transformers/models/regnet/convert_regnet_to_pytorch.py +src/transformers/models/regnet/modeling_flax_regnet.py +src/transformers/models/rembert/configuration_rembert.py +src/transformers/models/rembert/convert_rembert_tf_checkpoint_to_pytorch.py +src/transformers/models/rembert/modeling_rembert.py +src/transformers/models/rembert/modeling_tf_rembert.py +src/transformers/models/resnet/convert_resnet_to_pytorch.py +src/transformers/models/resnet/modeling_flax_resnet.py +src/transformers/models/roberta/convert_roberta_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/roberta/modeling_flax_roberta.py +src/transformers/models/roberta_prelayernorm/convert_roberta_prelayernorm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/roberta_prelayernorm/modeling_flax_roberta_prelayernorm.py +src/transformers/models/roc_bert/configuration_roc_bert.py +src/transformers/models/roformer/convert_roformer_original_tf_checkpoint_to_pytorch.py +src/transformers/models/roformer/modeling_flax_roformer.py +src/transformers/models/roformer/modeling_roformer.py +src/transformers/models/roformer/modeling_tf_roformer.py +src/transformers/models/rwkv/configuration_rwkv.py +src/transformers/models/rwkv/convert_rwkv_checkpoint_to_hf.py +src/transformers/models/rwkv/modeling_rwkv.py +src/transformers/models/sam/configuration_sam.py +src/transformers/models/sam/convert_sam_original_to_hf_format.py +src/transformers/models/sam/image_processing_sam.py +src/transformers/models/sam/modeling_sam.py +src/transformers/models/sam/modeling_tf_sam.py +src/transformers/models/sam/processing_sam.py +src/transformers/models/seamless_m4t/convert_fairseq2_to_hf.py +src/transformers/models/seamless_m4t_v2/convert_fairseq2_to_hf.py +src/transformers/models/segformer/configuration_segformer.py +src/transformers/models/segformer/convert_segformer_original_to_pytorch.py +src/transformers/models/sew/convert_sew_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/sew_d/convert_sew_d_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py +src/transformers/models/speech_encoder_decoder/convert_mbart_wav2vec2_seq2seq_original_to_pytorch.py +src/transformers/models/speech_encoder_decoder/convert_speech_to_text_wav2vec2_seq2seq_original_to_pytorch.py +src/transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py +src/transformers/models/speech_to_text/convert_s2t_fairseq_to_tfms.py +src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py +src/transformers/models/speecht5/configuration_speecht5.py +src/transformers/models/speecht5/convert_hifigan.py +src/transformers/models/speecht5/convert_speecht5_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/speecht5/number_normalizer.py +src/transformers/models/splinter/configuration_splinter.py +src/transformers/models/splinter/modeling_splinter.py +src/transformers/models/squeezebert/modeling_squeezebert.py +src/transformers/models/swiftformer/configuration_swiftformer.py +src/transformers/models/swiftformer/convert_swiftformer_original_to_hf.py +src/transformers/models/swiftformer/modeling_swiftformer.py +src/transformers/models/swin/convert_swin_simmim_to_pytorch.py +src/transformers/models/swin/convert_swin_timm_to_pytorch.py +src/transformers/models/swin/modeling_tf_swin.py +src/transformers/models/swin2sr/configuration_swin2sr.py +src/transformers/models/swin2sr/convert_swin2sr_original_to_pytorch.py +src/transformers/models/swinv2/convert_swinv2_timm_to_pytorch.py +src/transformers/models/swinv2/modeling_swinv2.py +src/transformers/models/switch_transformers/configuration_switch_transformers.py +src/transformers/models/switch_transformers/convert_big_switch.py +src/transformers/models/switch_transformers/convert_switch_transformers_original_flax_checkpoint_to_pytorch.py +src/transformers/models/switch_transformers/modeling_switch_transformers.py +src/transformers/models/t5/configuration_t5.py +src/transformers/models/t5/convert_t5_original_tf_checkpoint_to_pytorch.py +src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py +src/transformers/models/t5/convert_t5x_checkpoint_to_pytorch.py +src/transformers/models/t5/modeling_flax_t5.py +src/transformers/models/t5/modeling_t5.py +src/transformers/models/t5/modeling_tf_t5.py +src/transformers/models/table_transformer/configuration_table_transformer.py +src/transformers/models/table_transformer/convert_table_transformer_to_hf.py +src/transformers/models/table_transformer/convert_table_transformer_to_hf_no_timm.py +src/transformers/models/tapas/configuration_tapas.py +src/transformers/models/tapas/convert_tapas_original_tf_checkpoint_to_pytorch.py +src/transformers/models/tapas/modeling_tapas.py +src/transformers/models/tapas/modeling_tf_tapas.py +src/transformers/models/timesformer/convert_timesformer_to_pytorch.py +src/transformers/models/timm_backbone/configuration_timm_backbone.py +src/transformers/models/timm_backbone/modeling_timm_backbone.py +src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py +src/transformers/models/tvlt/configuration_tvlt.py +src/transformers/models/tvlt/modeling_tvlt.py +src/transformers/models/umt5/configuration_umt5.py +src/transformers/models/umt5/convert_umt5_checkpoint_to_pytorch.py +src/transformers/models/umt5/modeling_umt5.py +src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/unispeech_sat/configuration_unispeech_sat.py +src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/upernet/configuration_upernet.py +src/transformers/models/upernet/convert_convnext_upernet_to_pytorch.py +src/transformers/models/upernet/convert_swin_upernet_to_pytorch.py +src/transformers/models/videomae/configuration_videomae.py +src/transformers/models/videomae/convert_videomae_to_pytorch.py +src/transformers/models/vilt/configuration_vilt.py +src/transformers/models/vilt/convert_vilt_original_to_pytorch.py +src/transformers/models/vipllava/configuration_vipllava.py +src/transformers/models/vipllava/modeling_vipllava.py +src/transformers/models/vision_encoder_decoder/modeling_flax_vision_encoder_decoder.py +src/transformers/models/vision_encoder_decoder/modeling_tf_vision_encoder_decoder.py +src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py +src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py +src/transformers/models/visual_bert/convert_visual_bert_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/visual_bert/modeling_visual_bert.py +src/transformers/models/vit/convert_dino_to_pytorch.py +src/transformers/models/vit/convert_vit_timm_to_pytorch.py +src/transformers/models/vit/modeling_flax_vit.py +src/transformers/models/vit_hybrid/configuration_vit_hybrid.py +src/transformers/models/vit_hybrid/convert_vit_hybrid_timm_to_pytorch.py +src/transformers/models/vit_hybrid/modeling_vit_hybrid.py +src/transformers/models/vit_mae/convert_vit_mae_to_pytorch.py +src/transformers/models/vit_mae/modeling_tf_vit_mae.py +src/transformers/models/vit_msn/configuration_vit_msn.py +src/transformers/models/vit_msn/convert_msn_to_pytorch.py +src/transformers/models/vivit/configuration_vivit.py +src/transformers/models/vivit/convert_vivit_flax_to_pytorch.py +src/transformers/models/vivit/image_processing_vivit.py +src/transformers/models/vivit/modeling_vivit.py +src/transformers/models/wav2vec2/convert_wav2vec2_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wav2vec2/convert_wav2vec2_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py +src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py +src/transformers/models/wav2vec2_conformer/convert_wav2vec2_conformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wavlm/convert_wavlm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wavlm/convert_wavlm_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/whisper/convert_openai_to_hf.py +src/transformers/models/whisper/english_normalizer.py +src/transformers/models/whisper/modeling_flax_whisper.py +src/transformers/models/x_clip/configuration_x_clip.py +src/transformers/models/x_clip/convert_x_clip_original_pytorch_to_hf.py +src/transformers/models/xglm/configuration_xglm.py +src/transformers/models/xglm/convert_xglm_original_ckpt_to_trfms.py +src/transformers/models/xglm/modeling_flax_xglm.py +src/transformers/models/xglm/modeling_tf_xglm.py +src/transformers/models/xglm/modeling_xglm.py +src/transformers/models/xlm/convert_xlm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/xlm/modeling_tf_xlm.py +src/transformers/models/xlm/modeling_xlm.py +src/transformers/models/xlm_prophetnet/configuration_xlm_prophetnet.py +src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.py +src/transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py +src/transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py +src/transformers/models/xlm_roberta/modeling_xlm_roberta.py +src/transformers/models/xlm_roberta_xl/convert_xlm_roberta_xl_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py +src/transformers/models/xlnet/convert_xlnet_original_tf_checkpoint_to_pytorch.py +src/transformers/models/xlnet/modeling_tf_xlnet.py +src/transformers/models/xlnet/modeling_xlnet.py +src/transformers/models/xmod/convert_xmod_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/yolos/convert_yolos_to_pytorch.py +src/transformers/models/yoso/convert_yoso_pytorch_to_pytorch.py +src/transformers/models/yoso/modeling_yoso.py +src/transformers/onnx/__main__.py +src/transformers/onnx/config.py +src/transformers/onnx/convert.py +src/transformers/onnx/features.py +src/transformers/onnx/utils.py +src/transformers/optimization.py +src/transformers/optimization_tf.py +src/transformers/pipelines/audio_classification.py +src/transformers/pipelines/audio_utils.py +src/transformers/pipelines/automatic_speech_recognition.py +src/transformers/pipelines/base.py +src/transformers/pipelines/conversational.py +src/transformers/pipelines/depth_estimation.py +src/transformers/pipelines/document_question_answering.py +src/transformers/pipelines/feature_extraction.py +src/transformers/pipelines/fill_mask.py +src/transformers/pipelines/image_classification.py +src/transformers/pipelines/image_segmentation.py +src/transformers/pipelines/image_to_text.py +src/transformers/pipelines/mask_generation.py +src/transformers/pipelines/object_detection.py +src/transformers/pipelines/pt_utils.py +src/transformers/pipelines/question_answering.py +src/transformers/pipelines/table_question_answering.py +src/transformers/pipelines/text_classification.py +src/transformers/pipelines/token_classification.py +src/transformers/pipelines/video_classification.py +src/transformers/pipelines/visual_question_answering.py +src/transformers/pipelines/zero_shot_audio_classification.py +src/transformers/pipelines/zero_shot_classification.py +src/transformers/pipelines/zero_shot_image_classification.py +src/transformers/pipelines/zero_shot_object_detection.py +src/transformers/processing_utils.py +src/transformers/pytorch_utils.py +src/transformers/sagemaker/trainer_sm.py +src/transformers/sagemaker/training_args_sm.py +src/transformers/testing_utils.py +src/transformers/tf_utils.py +src/transformers/time_series_utils.py +src/transformers/tokenization_utils.py +src/transformers/tokenization_utils_base.py +src/transformers/tokenization_utils_fast.py +src/transformers/tools/agent_types.py +src/transformers/tools/agents.py +src/transformers/tools/base.py +src/transformers/tools/document_question_answering.py +src/transformers/tools/evaluate_agent.py +src/transformers/tools/image_captioning.py +src/transformers/tools/image_question_answering.py +src/transformers/tools/image_segmentation.py +src/transformers/tools/prompts.py +src/transformers/tools/python_interpreter.py +src/transformers/tools/speech_to_text.py +src/transformers/tools/text_classification.py +src/transformers/tools/text_question_answering.py +src/transformers/tools/text_summarization.py +src/transformers/tools/text_to_speech.py +src/transformers/tools/translation.py +src/transformers/trainer.py +src/transformers/trainer_callback.py +src/transformers/trainer_pt_utils.py +src/transformers/trainer_seq2seq.py +src/transformers/trainer_tf.py +src/transformers/trainer_utils.py +src/transformers/training_args.py +src/transformers/training_args_seq2seq.py +src/transformers/training_args_tf.py +src/transformers/utils/backbone_utils.py +src/transformers/utils/bitsandbytes.py +src/transformers/utils/constants.py +src/transformers/utils/doc.py +src/transformers/utils/dummy_detectron2_objects.py +src/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py +src/transformers/utils/dummy_flax_objects.py +src/transformers/utils/dummy_keras_nlp_objects.py +src/transformers/utils/dummy_music_objects.py +src/transformers/utils/dummy_pt_objects.py +src/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py +src/transformers/utils/dummy_sentencepiece_objects.py +src/transformers/utils/dummy_speech_objects.py +src/transformers/utils/dummy_tensorflow_text_objects.py +src/transformers/utils/dummy_tf_objects.py +src/transformers/utils/dummy_tokenizers_objects.py +src/transformers/utils/dummy_vision_objects.py +src/transformers/utils/fx.py +src/transformers/utils/generic.py +src/transformers/utils/hp_naming.py +src/transformers/utils/hub.py +src/transformers/utils/import_utils.py +src/transformers/utils/logging.py +src/transformers/utils/model_parallel_utils.py +src/transformers/utils/notebook.py +src/transformers/utils/peft_utils.py +src/transformers/utils/quantization_config.py +src/transformers/utils/sentencepiece_model_pb2.py +src/transformers/utils/sentencepiece_model_pb2_new.py +src/transformers/utils/versions.py diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/notification_service.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/notification_service.py new file mode 100644 index 0000000000000000000000000000000000000000..969107b3f88481376308b8e4749bd8173440f945 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/notification_service.py @@ -0,0 +1,1153 @@ +# 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 ast +import collections +import functools +import json +import operator +import os +import re +import sys +import time +from typing import Dict, List, Optional, Union + +import requests +from get_ci_error_statistics import get_job_links +from get_previous_daily_ci import get_last_daily_ci_reports +from slack_sdk import WebClient + + +client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) + +NON_MODEL_TEST_MODULES = [ + "benchmark", + "deepspeed", + "extended", + "fixtures", + "generation", + "onnx", + "optimization", + "pipelines", + "sagemaker", + "trainer", + "utils", +] + + +def handle_test_results(test_results): + expressions = test_results.split(" ") + + failed = 0 + success = 0 + + # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" + # When it is too long, those signs are not present. + time_spent = expressions[-2] if "=" in expressions[-1] else expressions[-1] + + for i, expression in enumerate(expressions): + if "failed" in expression: + failed += int(expressions[i - 1]) + if "passed" in expression: + success += int(expressions[i - 1]) + + return failed, success, time_spent + + +def handle_stacktraces(test_results): + # These files should follow the following architecture: + # === FAILURES === + # :: Error ... + # :: Error ... + # + + total_stacktraces = test_results.split("\n")[1:-1] + stacktraces = [] + for stacktrace in total_stacktraces: + try: + line = stacktrace[: stacktrace.index(" ")].split(":")[-2] + error_message = stacktrace[stacktrace.index(" ") :] + + stacktraces.append(f"(line {line}) {error_message}") + except Exception: + stacktraces.append("Cannot retrieve error message.") + + return stacktraces + + +def dicts_to_sum(objects: Union[Dict[str, Dict], List[dict]]): + if isinstance(objects, dict): + lists = objects.values() + else: + lists = objects + + # Convert each dictionary to counter + counters = map(collections.Counter, lists) + # Sum all the counters + return functools.reduce(operator.add, counters) + + +class Message: + def __init__( + self, + title: str, + ci_title: str, + model_results: Dict, + additional_results: Dict, + selected_warnings: List = None, + prev_ci_artifacts=None, + ): + self.title = title + self.ci_title = ci_title + + # Failures and success of the modeling tests + self.n_model_success = sum(r["success"] for r in model_results.values()) + self.n_model_single_gpu_failures = sum(dicts_to_sum(r["failed"])["single"] for r in model_results.values()) + self.n_model_multi_gpu_failures = sum(dicts_to_sum(r["failed"])["multi"] for r in model_results.values()) + + # Some suites do not have a distinction between single and multi GPU. + self.n_model_unknown_failures = sum(dicts_to_sum(r["failed"])["unclassified"] for r in model_results.values()) + self.n_model_failures = ( + self.n_model_single_gpu_failures + self.n_model_multi_gpu_failures + self.n_model_unknown_failures + ) + + # Failures and success of the additional tests + self.n_additional_success = sum(r["success"] for r in additional_results.values()) + + if len(additional_results) > 0: + # `dicts_to_sum` uses `dicts_to_sum` which requires a non empty dictionary. Let's just add an empty entry. + all_additional_failures = dicts_to_sum([r["failed"] for r in additional_results.values()]) + self.n_additional_single_gpu_failures = all_additional_failures["single"] + self.n_additional_multi_gpu_failures = all_additional_failures["multi"] + self.n_additional_unknown_gpu_failures = all_additional_failures["unclassified"] + else: + self.n_additional_single_gpu_failures = 0 + self.n_additional_multi_gpu_failures = 0 + self.n_additional_unknown_gpu_failures = 0 + + self.n_additional_failures = ( + self.n_additional_single_gpu_failures + + self.n_additional_multi_gpu_failures + + self.n_additional_unknown_gpu_failures + ) + + # Results + self.n_failures = self.n_model_failures + self.n_additional_failures + self.n_success = self.n_model_success + self.n_additional_success + self.n_tests = self.n_failures + self.n_success + + self.model_results = model_results + self.additional_results = additional_results + + self.thread_ts = None + + if selected_warnings is None: + selected_warnings = [] + self.selected_warnings = selected_warnings + + self.prev_ci_artifacts = prev_ci_artifacts + + @property + def time(self) -> str: + all_results = [*self.model_results.values(), *self.additional_results.values()] + time_spent = [r["time_spent"].split(", ")[0] for r in all_results if len(r["time_spent"])] + total_secs = 0 + + for time in time_spent: + time_parts = time.split(":") + + # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. + if len(time_parts) == 1: + time_parts = [0, 0, time_parts[0]] + + hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) + total_secs += hours * 3600 + minutes * 60 + seconds + + hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 + return f"{int(hours)}h{int(minutes)}m{int(seconds)}s" + + @property + def header(self) -> Dict: + return {"type": "header", "text": {"type": "plain_text", "text": self.title}} + + @property + def ci_title_section(self) -> Dict: + return {"type": "section", "text": {"type": "mrkdwn", "text": self.ci_title}} + + @property + def no_failures(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def failures(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": ( + f"There were {self.n_failures} failures, out of {self.n_tests} tests.\n" + f"Number of model failures: {self.n_model_failures}.\n" + f"The suite ran in {self.time}." + ), + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def warnings(self) -> Dict: + # If something goes wrong, let's avoid the CI report failing to be sent. + button_text = "Check warnings (Link not found)" + # Use the workflow run link + job_link = f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}" + if "Extract warnings in CI artifacts" in github_actions_job_links: + button_text = "Check warnings" + # Use the actual job link + job_link = f"{github_actions_job_links['Extract warnings in CI artifacts']}" + + huggingface_hub_warnings = [x for x in self.selected_warnings if "huggingface_hub" in x] + text = f"There are {len(self.selected_warnings)} warnings being selected." + text += f"\n{len(huggingface_hub_warnings)} of them are from `huggingface_hub`." + + return { + "type": "section", + "text": { + "type": "plain_text", + "text": text, + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": button_text, "emoji": True}, + "url": job_link, + }, + } + + @staticmethod + def get_device_report(report, rjust=6): + if "single" in report and "multi" in report: + return f"{str(report['single']).rjust(rjust)} | {str(report['multi']).rjust(rjust)} | " + elif "single" in report: + return f"{str(report['single']).rjust(rjust)} | {'0'.rjust(rjust)} | " + elif "multi" in report: + return f"{'0'.rjust(rjust)} | {str(report['multi']).rjust(rjust)} | " + + @property + def category_failures(self) -> Dict: + model_failures = [v["failed"] for v in self.model_results.values()] + + category_failures = {} + + for model_failure in model_failures: + for key, value in model_failure.items(): + if key not in category_failures: + category_failures[key] = dict(value) + else: + category_failures[key]["unclassified"] += value["unclassified"] + category_failures[key]["single"] += value["single"] + category_failures[key]["multi"] += value["multi"] + + individual_reports = [] + for key, value in category_failures.items(): + device_report = self.get_device_report(value) + + if sum(value.values()): + if device_report: + individual_reports.append(f"{device_report}{key}") + else: + individual_reports.append(key) + + header = "Single | Multi | Category\n" + category_failures_report = prepare_reports( + title="The following modeling categories had failures", header=header, reports=individual_reports + ) + + return {"type": "section", "text": {"type": "mrkdwn", "text": category_failures_report}} + + def compute_diff_for_failure_reports(self, curr_failure_report, prev_failure_report): # noqa + # Remove the leading and training parts that don't contain failure count information. + model_failures = curr_failure_report.split("\n")[3:-2] + prev_model_failures = prev_failure_report.split("\n")[3:-2] + entries_changed = set(model_failures).difference(prev_model_failures) + + prev_map = {} + for f in prev_model_failures: + items = [x.strip() for x in f.split("| ")] + prev_map[items[-1]] = [int(x) for x in items[:-1]] + + curr_map = {} + for f in entries_changed: + items = [x.strip() for x in f.split("| ")] + curr_map[items[-1]] = [int(x) for x in items[:-1]] + + diff_map = {} + for k, v in curr_map.items(): + if k not in prev_map: + diff_map[k] = v + else: + diff = [x - y for x, y in zip(v, prev_map[k])] + if max(diff) > 0: + diff_map[k] = diff + + entries_changed = [] + for model_name, diff_values in diff_map.items(): + diff = [str(x) for x in diff_values] + diff = [f"+{x}" if (x != "0" and not x.startswith("-")) else x for x in diff] + diff = [x.rjust(9) for x in diff] + device_report = " | ".join(diff) + " | " + report = f"{device_report}{model_name}" + entries_changed.append(report) + entries_changed = sorted(entries_changed, key=lambda s: s.split("| ")[-1]) + + return entries_changed + + @property + def model_failures(self) -> List[Dict]: + # Obtain per-model failures + def per_model_sum(model_category_dict): + return dicts_to_sum(model_category_dict["failed"].values()) + + failures = {} + non_model_failures = { + k: per_model_sum(v) for k, v in self.model_results.items() if sum(per_model_sum(v).values()) + } + + for k, v in self.model_results.items(): + if k in NON_MODEL_TEST_MODULES: + pass + + if sum(per_model_sum(v).values()): + dict_failed = dict(v["failed"]) + pytorch_specific_failures = dict_failed.pop("PyTorch") + tensorflow_specific_failures = dict_failed.pop("TensorFlow") + other_failures = dicts_to_sum(dict_failed.values()) + + failures[k] = { + "PyTorch": pytorch_specific_failures, + "TensorFlow": tensorflow_specific_failures, + "other": other_failures, + } + + model_reports = [] + other_module_reports = [] + + for key, value in non_model_failures.items(): + if key in NON_MODEL_TEST_MODULES: + device_report = self.get_device_report(value) + + if sum(value.values()): + if device_report: + report = f"{device_report}{key}" + else: + report = key + + other_module_reports.append(report) + + for key, value in failures.items(): + device_report_values = [ + value["PyTorch"]["single"], + value["PyTorch"]["multi"], + value["TensorFlow"]["single"], + value["TensorFlow"]["multi"], + sum(value["other"].values()), + ] + + if sum(device_report_values): + device_report = " | ".join([str(x).rjust(9) for x in device_report_values]) + " | " + report = f"{device_report}{key}" + + model_reports.append(report) + + # (Possibly truncated) reports for the current workflow run - to be sent to Slack channels + model_header = "Single PT | Multi PT | Single TF | Multi TF | Other | Category\n" + sorted_model_reports = sorted(model_reports, key=lambda s: s.split("| ")[-1]) + model_failures_report = prepare_reports( + title="These following model modules had failures", header=model_header, reports=sorted_model_reports + ) + + module_header = "Single | Multi | Category\n" + sorted_module_reports = sorted(other_module_reports, key=lambda s: s.split("| ")[-1]) + module_failures_report = prepare_reports( + title="The following non-model modules had failures", header=module_header, reports=sorted_module_reports + ) + + # To be sent to Slack channels + model_failure_sections = [ + {"type": "section", "text": {"type": "mrkdwn", "text": model_failures_report}}, + {"type": "section", "text": {"type": "mrkdwn", "text": module_failures_report}}, + ] + + # Save the complete (i.e. no truncation) failure tables (of the current workflow run) + # (to be uploaded as artifacts) + + model_failures_report = prepare_reports( + title="These following model modules had failures", + header=model_header, + reports=sorted_model_reports, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), "prev_ci_results/model_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(model_failures_report) + + module_failures_report = prepare_reports( + title="The following non-model modules had failures", + header=module_header, + reports=sorted_module_reports, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), "prev_ci_results/module_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(module_failures_report) + + if self.prev_ci_artifacts is not None: + # if the last run produces artifact named `prev_ci_results` + if ( + "prev_ci_results" in self.prev_ci_artifacts + and "model_failures_report.txt" in self.prev_ci_artifacts["prev_ci_results"] + ): + # Compute the difference of the previous/current (model failure) table + prev_model_failures = self.prev_ci_artifacts["prev_ci_results"]["model_failures_report.txt"] + entries_changed = self.compute_diff_for_failure_reports(model_failures_report, prev_model_failures) + if len(entries_changed) > 0: + # Save the complete difference + diff_report = prepare_reports( + title="Changed model modules failures", + header=model_header, + reports=entries_changed, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), "prev_ci_results/changed_model_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(diff_report) + + # To be sent to Slack channels + diff_report = prepare_reports( + title="*Changed model modules failures*", + header=model_header, + reports=entries_changed, + ) + model_failure_sections.append( + {"type": "section", "text": {"type": "mrkdwn", "text": diff_report}}, + ) + + return model_failure_sections + + @property + def additional_failures(self) -> Dict: + failures = {k: v["failed"] for k, v in self.additional_results.items()} + errors = {k: v["error"] for k, v in self.additional_results.items()} + + individual_reports = [] + for key, value in failures.items(): + device_report = self.get_device_report(value) + + if sum(value.values()) or errors[key]: + report = f"{key}" + if errors[key]: + report = f"[Errored out] {report}" + if device_report: + report = f"{device_report}{report}" + + individual_reports.append(report) + + header = "Single | Multi | Category\n" + failures_report = prepare_reports( + title="The following non-modeling tests had failures", header=header, reports=individual_reports + ) + + return {"type": "section", "text": {"type": "mrkdwn", "text": failures_report}} + + @property + def payload(self) -> str: + blocks = [self.header] + + if self.ci_title: + blocks.append(self.ci_title_section) + + if self.n_model_failures > 0 or self.n_additional_failures > 0: + blocks.append(self.failures) + + if self.n_model_failures > 0: + blocks.append(self.category_failures) + for block in self.model_failures: + if block["text"]["text"]: + blocks.append(block) + + if self.n_additional_failures > 0: + blocks.append(self.additional_failures) + + if self.n_model_failures == 0 and self.n_additional_failures == 0: + blocks.append(self.no_failures) + + if len(self.selected_warnings) > 0: + blocks.append(self.warnings) + + new_failure_blocks = self.get_new_model_failure_blocks(with_header=False) + if len(new_failure_blocks) > 0: + blocks.extend(new_failure_blocks) + + return json.dumps(blocks) + + @staticmethod + def error_out(title, ci_title="", runner_not_available=False, runner_failed=False, setup_failed=False): + blocks = [] + title_block = {"type": "header", "text": {"type": "plain_text", "text": title}} + blocks.append(title_block) + + if ci_title: + ci_title_block = {"type": "section", "text": {"type": "mrkdwn", "text": ci_title}} + blocks.append(ci_title_block) + + offline_runners = [] + if runner_not_available: + text = "💔 CI runners are not available! Tests are not run. 😭" + result = os.environ.get("OFFLINE_RUNNERS") + if result is not None: + offline_runners = json.loads(result) + elif runner_failed: + text = "💔 CI runners have problems! Tests are not run. 😭" + elif setup_failed: + text = "💔 Setup job failed. Tests are not run. 😭" + else: + text = "💔 There was an issue running the tests. 😭" + + error_block_1 = { + "type": "header", + "text": { + "type": "plain_text", + "text": text, + }, + } + + text = "" + if len(offline_runners) > 0: + text = "\n • " + "\n • ".join(offline_runners) + text = f"The following runners are offline:\n{text}\n\n" + text += "🙏 Let's fix it ASAP! 🙏" + + error_block_2 = { + "type": "section", + "text": { + "type": "plain_text", + "text": text, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + blocks.extend([error_block_1, error_block_2]) + + payload = json.dumps(blocks) + + print("Sending the following payload") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=os.environ["CI_SLACK_REPORT_CHANNEL_ID"], + text=text, + blocks=payload, + ) + + def post(self): + payload = self.payload + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(payload)})) + + text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." + + self.thread_ts = client.chat_postMessage( + channel=os.environ["CI_SLACK_REPORT_CHANNEL_ID"], + blocks=payload, + text=text, + ) + + def get_reply_blocks(self, job_name, job_result, failures, device, text): + """ + failures: A list with elements of the form {"line": full test name, "trace": error trace} + """ + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + + failure_text = "" + for idx, error in enumerate(failures): + new_text = failure_text + f'*{error["line"]}*\n_{error["trace"]}_\n\n' + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + title = job_name + if device is not None: + title += f" ({device}-gpu)" + + content = {"type": "section", "text": {"type": "mrkdwn", "text": text}} + + # TODO: Make sure we always have a valid job link (or at least a way not to break the report sending) + # Currently we get the device from a job's artifact name. + # If a device is found, the job name should contain the device type, for example, `XXX (single-gpu)`. + # This could be done by adding `machine_type` in a job's `strategy`. + # (If `job_result["job_link"][device]` is `None`, we get an error: `... [ERROR] must provide a string ...`) + if job_result["job_link"] is not None and job_result["job_link"][device] is not None: + content["accessory"] = { + "type": "button", + "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, + "url": job_result["job_link"][device], + } + + return [ + {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, + content, + {"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}, + ] + + def get_new_model_failure_blocks(self, with_header=True): + if self.prev_ci_artifacts is None: + return {} + + sorted_dict = sorted(self.model_results.items(), key=lambda t: t[0]) + + prev_model_results = {} + if ( + "prev_ci_results" in self.prev_ci_artifacts + and "model_results.json" in self.prev_ci_artifacts["prev_ci_results"] + ): + prev_model_results = json.loads(self.prev_ci_artifacts["prev_ci_results"]["model_results.json"]) + + all_failure_lines = {} + for job, job_result in sorted_dict: + if len(job_result["failures"]): + devices = sorted(job_result["failures"].keys(), reverse=True) + for device in devices: + failures = job_result["failures"][device] + prev_error_lines = {} + if job in prev_model_results and device in prev_model_results[job]["failures"]: + prev_error_lines = {error["line"] for error in prev_model_results[job]["failures"][device]} + + url = None + if job_result["job_link"] is not None and job_result["job_link"][device] is not None: + url = job_result["job_link"][device] + + for idx, error in enumerate(failures): + if error["line"] in prev_error_lines: + continue + + new_text = f'{error["line"]}\n\n' + + if new_text not in all_failure_lines: + all_failure_lines[new_text] = [] + + all_failure_lines[new_text].append(f"<{url}|{device}>" if url is not None else device) + + MAX_ERROR_TEXT = 3000 - len("[Truncated]") - len("```New model failures```\n\n") + failure_text = "" + for line, devices in all_failure_lines.items(): + new_text = failure_text + f"{'|'.join(devices)} gpu\n{line}" + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + blocks = [] + if failure_text: + if with_header: + blocks.append( + {"type": "header", "text": {"type": "plain_text", "text": "New model failures", "emoji": True}} + ) + else: + failure_text = f"*New model failures*\n\n{failure_text}" + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}) + + return blocks + + def post_reply(self): + if self.thread_ts is None: + raise ValueError("Can only post reply if a post has been made.") + + sorted_dict = sorted(self.model_results.items(), key=lambda t: t[0]) + for job, job_result in sorted_dict: + if len(job_result["failures"]): + for device, failures in job_result["failures"].items(): + text = "\n".join( + sorted([f"*{k}*: {v[device]}" for k, v in job_result["failed"].items() if v[device]]) + ) + + blocks = self.get_reply_blocks(job, job_result, failures, device, text=text) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=os.environ["CI_SLACK_REPORT_CHANNEL_ID"], + text=f"Results for {job}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + for job, job_result in self.additional_results.items(): + if len(job_result["failures"]): + for device, failures in job_result["failures"].items(): + blocks = self.get_reply_blocks( + job, + job_result, + failures, + device, + text=f'Number of failures: {job_result["failed"][device]}', + ) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=os.environ["CI_SLACK_REPORT_CHANNEL_ID"], + text=f"Results for {job}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + blocks = self.get_new_model_failure_blocks() + if blocks: + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=os.environ["CI_SLACK_REPORT_CHANNEL_ID"], + text="Results for new failures", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + +def retrieve_artifact(artifact_path: str, gpu: Optional[str]): + if gpu not in [None, "single", "multi"]: + raise ValueError(f"Invalid GPU for artifact. Passed GPU: `{gpu}`.") + + _artifact = {} + + if os.path.exists(artifact_path): + files = os.listdir(artifact_path) + for file in files: + try: + with open(os.path.join(artifact_path, file)) as f: + _artifact[file.split(".")[0]] = f.read() + except UnicodeDecodeError as e: + raise ValueError(f"Could not open {os.path.join(artifact_path, file)}.") from e + + return _artifact + + +def retrieve_available_artifacts(): + class Artifact: + def __init__(self, name: str, single_gpu: bool = False, multi_gpu: bool = False): + self.name = name + self.single_gpu = single_gpu + self.multi_gpu = multi_gpu + self.paths = [] + + def __str__(self): + return self.name + + def add_path(self, path: str, gpu: str = None): + self.paths.append({"name": self.name, "path": path, "gpu": gpu}) + + _available_artifacts: Dict[str, Artifact] = {} + + directories = filter(os.path.isdir, os.listdir()) + for directory in directories: + artifact_name = directory + + name_parts = artifact_name.split("_postfix_") + if len(name_parts) > 1: + artifact_name = name_parts[0] + + if artifact_name.startswith("single-gpu"): + artifact_name = artifact_name[len("single-gpu") + 1 :] + + if artifact_name in _available_artifacts: + _available_artifacts[artifact_name].single_gpu = True + else: + _available_artifacts[artifact_name] = Artifact(artifact_name, single_gpu=True) + + _available_artifacts[artifact_name].add_path(directory, gpu="single") + + elif artifact_name.startswith("multi-gpu"): + artifact_name = artifact_name[len("multi-gpu") + 1 :] + + if artifact_name in _available_artifacts: + _available_artifacts[artifact_name].multi_gpu = True + else: + _available_artifacts[artifact_name] = Artifact(artifact_name, multi_gpu=True) + + _available_artifacts[artifact_name].add_path(directory, gpu="multi") + else: + if artifact_name not in _available_artifacts: + _available_artifacts[artifact_name] = Artifact(artifact_name) + + _available_artifacts[artifact_name].add_path(directory) + + return _available_artifacts + + +def prepare_reports(title, header, reports, to_truncate=True): + report = "" + + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + if not to_truncate: + MAX_ERROR_TEXT = float("inf") + + if len(reports) > 0: + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + + for idx in range(len(reports)): + _report = header + "\n".join(reports[: idx + 1]) + new_report = f"{title}:\n```\n{_report}\n```\n" + if len(new_report) > MAX_ERROR_TEXT: + # `report` here has length <= 3000 + report = report + "[Truncated]" + break + report = new_report + + return report + + +if __name__ == "__main__": + # runner_status = os.environ.get("RUNNER_STATUS") + # runner_env_status = os.environ.get("RUNNER_ENV_STATUS") + setup_status = os.environ.get("SETUP_STATUS") + + # runner_not_available = True if runner_status is not None and runner_status != "success" else False + # runner_failed = True if runner_env_status is not None and runner_env_status != "success" else False + # Let's keep the lines regardig runners' status (we might be able to use them again in the future) + runner_not_available = False + runner_failed = False + setup_failed = True if setup_status is not None and setup_status != "success" else False + + org = "huggingface" + repo = "transformers" + repository_full_name = f"{org}/{repo}" + + # This env. variable is set in workflow file (under the job `send_results`). + ci_event = os.environ["CI_EVENT"] + + # To find the PR number in a commit title, for example, `Add AwesomeFormer model (#99999)` + pr_number_re = re.compile(r"\(#(\d+)\)$") + + title = f"🤗 Results of the {ci_event} tests." + # Add Commit/PR title with a link for push CI + # (check the title in 2 env. variables - depending on the CI is triggered via `push` or `workflow_run` event) + ci_title_push = os.environ.get("CI_TITLE_PUSH") + ci_title_workflow_run = os.environ.get("CI_TITLE_WORKFLOW_RUN") + ci_title = ci_title_push if ci_title_push else ci_title_workflow_run + + ci_sha = os.environ.get("CI_SHA") + + ci_url = None + if ci_sha: + ci_url = f"https://github.com/{repository_full_name}/commit/{ci_sha}" + + if ci_title is not None: + if ci_url is None: + raise ValueError( + "When a title is found (`ci_title`), it means a `push` event or a `workflow_run` even (triggered by " + "another `push` event), and the commit SHA has to be provided in order to create the URL to the " + "commit page." + ) + ci_title = ci_title.strip().split("\n")[0].strip() + + # Retrieve the PR title and author login to complete the report + commit_number = ci_url.split("/")[-1] + ci_detail_url = f"https://api.github.com/repos/{repository_full_name}/commits/{commit_number}" + ci_details = requests.get(ci_detail_url).json() + ci_author = ci_details["author"]["login"] + + merged_by = None + # Find the PR number (if any) and change the url to the actual PR page. + numbers = pr_number_re.findall(ci_title) + if len(numbers) > 0: + pr_number = numbers[0] + ci_detail_url = f"https://api.github.com/repos/{repository_full_name}/pulls/{pr_number}" + ci_details = requests.get(ci_detail_url).json() + + ci_author = ci_details["user"]["login"] + ci_url = f"https://github.com/{repository_full_name}/pull/{pr_number}" + + merged_by = ci_details["merged_by"]["login"] + + if merged_by is None: + ci_title = f"<{ci_url}|{ci_title}>\nAuthor: {ci_author}" + else: + ci_title = f"<{ci_url}|{ci_title}>\nAuthor: {ci_author} | Merged by: {merged_by}" + + elif ci_sha: + ci_title = f"<{ci_url}|commit: {ci_sha}>" + + else: + ci_title = "" + + if runner_not_available or runner_failed or setup_failed: + Message.error_out(title, ci_title, runner_not_available, runner_failed, setup_failed) + exit(0) + + arguments = sys.argv[1:][0] + try: + models = ast.literal_eval(arguments) + # Need to change from elements like `models/bert` to `models_bert` (the ones used as artifact names). + models = [x.replace("models/", "models_") for x in models] + except SyntaxError: + Message.error_out(title, ci_title) + raise ValueError("Errored out.") + + github_actions_job_links = get_job_links( + workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"] + ) + available_artifacts = retrieve_available_artifacts() + + modeling_categories = [ + "PyTorch", + "TensorFlow", + "Flax", + "Tokenizers", + "Pipelines", + "Trainer", + "ONNX", + "Auto", + "Unclassified", + ] + + # This dict will contain all the information relative to each model: + # - Failures: the total, as well as the number of failures per-category defined above + # - Success: total + # - Time spent: as a comma-separated list of elapsed time + # - Failures: as a line-break separated list of errors + model_results = { + model: { + "failed": {m: {"unclassified": 0, "single": 0, "multi": 0} for m in modeling_categories}, + "success": 0, + "time_spent": "", + "failures": {}, + "job_link": {}, + } + for model in models + if f"run_all_tests_gpu_{model}_test_reports" in available_artifacts + } + + unclassified_model_failures = [] + + # This prefix is used to get job links below. For past CI, we use `workflow_call`, which changes the job names from + # `Model tests (...)` to `PyTorch 1.5 / Model tests (...)` for example. + job_name_prefix = "" + if ci_event.startswith("Past CI - "): + framework, version = ci_event.replace("Past CI - ", "").split("-") + framework = "PyTorch" if framework == "pytorch" else "TensorFlow" + job_name_prefix = f"{framework} {version}" + elif ci_event.startswith("Nightly CI"): + job_name_prefix = "Nightly CI" + elif ci_event.startswith("Push CI (AMD) - "): + flavor = ci_event.replace("Push CI (AMD) - ", "") + job_name_prefix = f"AMD {flavor}" + elif ci_event.startswith("Scheduled CI (AMD) - "): + flavor = ci_event.replace("Scheduled CI (AMD) - ", "") + job_name_prefix = f"AMD {flavor}" + + for model in model_results.keys(): + for artifact_path in available_artifacts[f"run_all_tests_gpu_{model}_test_reports"].paths: + artifact = retrieve_artifact(artifact_path["path"], artifact_path["gpu"]) + if "stats" in artifact: + # Link to the GitHub Action job + # The job names use `matrix.folder` which contain things like `models/bert` instead of `models_bert` + job_name = f"Model tests ({model.replace('models_', 'models/')}, {artifact_path['gpu']}-gpu)" + if job_name_prefix: + job_name = f"{job_name_prefix} / {job_name}" + model_results[model]["job_link"][artifact_path["gpu"]] = github_actions_job_links.get(job_name) + failed, success, time_spent = handle_test_results(artifact["stats"]) + model_results[model]["success"] += success + model_results[model]["time_spent"] += time_spent[1:-1] + ", " + + stacktraces = handle_stacktraces(artifact["failures_line"]) + + for line in artifact["summary_short"].split("\n"): + if line.startswith("FAILED "): + line = line[len("FAILED ") :] + line = line.split()[0].replace("\n", "") + + if artifact_path["gpu"] not in model_results[model]["failures"]: + model_results[model]["failures"][artifact_path["gpu"]] = [] + + model_results[model]["failures"][artifact_path["gpu"]].append( + {"line": line, "trace": stacktraces.pop(0)} + ) + + if re.search("test_modeling_tf_", line): + model_results[model]["failed"]["TensorFlow"][artifact_path["gpu"]] += 1 + + elif re.search("test_modeling_flax_", line): + model_results[model]["failed"]["Flax"][artifact_path["gpu"]] += 1 + + elif re.search("test_modeling", line): + model_results[model]["failed"]["PyTorch"][artifact_path["gpu"]] += 1 + + elif re.search("test_tokenization", line): + model_results[model]["failed"]["Tokenizers"][artifact_path["gpu"]] += 1 + + elif re.search("test_pipelines", line): + model_results[model]["failed"]["Pipelines"][artifact_path["gpu"]] += 1 + + elif re.search("test_trainer", line): + model_results[model]["failed"]["Trainer"][artifact_path["gpu"]] += 1 + + elif re.search("onnx", line): + model_results[model]["failed"]["ONNX"][artifact_path["gpu"]] += 1 + + elif re.search("auto", line): + model_results[model]["failed"]["Auto"][artifact_path["gpu"]] += 1 + + else: + model_results[model]["failed"]["Unclassified"][artifact_path["gpu"]] += 1 + unclassified_model_failures.append(line) + + # Additional runs + additional_files = { + "Examples directory": "run_examples_gpu", + "PyTorch pipelines": "run_tests_torch_pipeline_gpu", + "TensorFlow pipelines": "run_tests_tf_pipeline_gpu", + "Torch CUDA extension tests": "run_tests_torch_cuda_extensions_gpu_test_reports", + } + + if ci_event in ["push", "Nightly CI"] or ci_event.startswith("Past CI"): + del additional_files["Examples directory"] + del additional_files["PyTorch pipelines"] + del additional_files["TensorFlow pipelines"] + elif ci_event.startswith("Scheduled CI (AMD)"): + del additional_files["TensorFlow pipelines"] + del additional_files["Torch CUDA extension tests"] + elif ci_event.startswith("Push CI (AMD)"): + additional_files = {} + + additional_results = { + key: { + "failed": {"unclassified": 0, "single": 0, "multi": 0}, + "success": 0, + "time_spent": "", + "error": False, + "failures": {}, + "job_link": {}, + } + for key in additional_files.keys() + } + + for key in additional_results.keys(): + # If a whole suite of test fails, the artifact isn't available. + if additional_files[key] not in available_artifacts: + additional_results[key]["error"] = True + continue + + for artifact_path in available_artifacts[additional_files[key]].paths: + # Link to the GitHub Action job + job_name = key + if artifact_path["gpu"] is not None: + job_name = f"{key} ({artifact_path['gpu']}-gpu)" + if job_name_prefix: + job_name = f"{job_name_prefix} / {job_name}" + additional_results[key]["job_link"][artifact_path["gpu"]] = github_actions_job_links.get(job_name) + + artifact = retrieve_artifact(artifact_path["path"], artifact_path["gpu"]) + stacktraces = handle_stacktraces(artifact["failures_line"]) + + failed, success, time_spent = handle_test_results(artifact["stats"]) + additional_results[key]["failed"][artifact_path["gpu"] or "unclassified"] += failed + additional_results[key]["success"] += success + additional_results[key]["time_spent"] += time_spent[1:-1] + ", " + + if len(artifact["errors"]): + additional_results[key]["error"] = True + + if failed: + for line in artifact["summary_short"].split("\n"): + if line.startswith("FAILED "): + line = line[len("FAILED ") :] + line = line.split()[0].replace("\n", "") + + if artifact_path["gpu"] not in additional_results[key]["failures"]: + additional_results[key]["failures"][artifact_path["gpu"]] = [] + + additional_results[key]["failures"][artifact_path["gpu"]].append( + {"line": line, "trace": stacktraces.pop(0)} + ) + + selected_warnings = [] + if "warnings_in_ci" in available_artifacts: + directory = available_artifacts["warnings_in_ci"].paths[0]["path"] + with open(os.path.join(directory, "selected_warnings.json")) as fp: + selected_warnings = json.load(fp) + + if not os.path.isdir(os.path.join(os.getcwd(), "prev_ci_results")): + os.makedirs(os.path.join(os.getcwd(), "prev_ci_results")) + + with open("prev_ci_results/model_results.json", "w", encoding="UTF-8") as fp: + json.dump(model_results, fp, indent=4, ensure_ascii=False) + + prev_ci_artifacts = None + target_workflow = "huggingface/transformers/.github/workflows/self-scheduled.yml@refs/heads/main" + if os.environ.get("CI_WORKFLOW_REF") == target_workflow: + # Get the last previously completed CI's failure tables + artifact_names = ["prev_ci_results"] + output_dir = os.path.join(os.getcwd(), "previous_reports") + os.makedirs(output_dir, exist_ok=True) + prev_ci_artifacts = get_last_daily_ci_reports( + artifact_names=artifact_names, output_dir=output_dir, token=os.environ["ACCESS_REPO_INFO_TOKEN"] + ) + + message = Message( + title, + ci_title, + model_results, + additional_results, + selected_warnings=selected_warnings, + prev_ci_artifacts=prev_ci_artifacts, + ) + + # send report only if there is any failure (for push CI) + if message.n_failures or (ci_event != "push" and not ci_event.startswith("Push CI (AMD)")): + message.post() + message.post_reply() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/notification_service_doc_tests.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/notification_service_doc_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..c516963be1d71c10ee558564b84d184f40187204 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/notification_service_doc_tests.py @@ -0,0 +1,401 @@ +# Copyright 2022 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 collections +import json +import math +import os +import re +import time +from fnmatch import fnmatch +from typing import Dict, List + +import requests +from slack_sdk import WebClient + + +client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) + + +def handle_test_results(test_results): + expressions = test_results.split(" ") + + failed = 0 + success = 0 + + # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" + # When it is too long, those signs are not present. + time_spent = expressions[-2] if "=" in expressions[-1] else expressions[-1] + + for i, expression in enumerate(expressions): + if "failed" in expression: + failed += int(expressions[i - 1]) + if "passed" in expression: + success += int(expressions[i - 1]) + + return failed, success, time_spent + + +def extract_first_line_failure(failures_short_lines): + failures = {} + file = None + in_error = False + for line in failures_short_lines.split("\n"): + if re.search(r"_ \[doctest\]", line): + in_error = True + file = line.split(" ")[2] + elif in_error and not line.split(" ")[0].isdigit(): + failures[file] = line + in_error = False + + return failures + + +class Message: + def __init__(self, title: str, doc_test_results: Dict): + self.title = title + + self._time_spent = doc_test_results["time_spent"].split(",")[0] + self.n_success = doc_test_results["success"] + self.n_failures = doc_test_results["failures"] + self.n_tests = self.n_success + self.n_failures + + # Failures and success of the modeling tests + self.doc_test_results = doc_test_results + + @property + def time(self) -> str: + time_spent = [self._time_spent] + total_secs = 0 + + for time in time_spent: + time_parts = time.split(":") + + # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. + if len(time_parts) == 1: + time_parts = [0, 0, time_parts[0]] + + hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) + total_secs += hours * 3600 + minutes * 60 + seconds + + hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 + return f"{int(hours)}h{int(minutes)}m{int(seconds)}s" + + @property + def header(self) -> Dict: + return {"type": "header", "text": {"type": "plain_text", "text": self.title}} + + @property + def no_failures(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def failures(self) -> Dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": ( + f"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" + f" {self.time}." + ), + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def category_failures(self) -> List[Dict]: + failure_blocks = [] + + MAX_ERROR_TEXT = 3000 - len("The following examples had failures:\n\n\n\n") - len("[Truncated]\n") + line_length = 40 + category_failures = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(v, dict)} + + def single_category_failures(category, failures): + text = "" + if len(failures) == 0: + return "" + text += f"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n" + + for idx, failure in enumerate(failures): + new_text = text + f"`{failure}`\n" + if len(new_text) > MAX_ERROR_TEXT: + text = text + "[Truncated]\n" + break + text = new_text + + return text + + for category, failures in category_failures.items(): + report = single_category_failures(category, failures) + if len(report) == 0: + continue + block = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": f"The following examples had failures:\n\n\n{report}\n", + }, + } + failure_blocks.append(block) + + return failure_blocks + + @property + def payload(self) -> str: + blocks = [self.header] + + if self.n_failures > 0: + blocks.append(self.failures) + + if self.n_failures > 0: + blocks.extend(self.category_failures) + + if self.n_failures == 0: + blocks.append(self.no_failures) + + return json.dumps(blocks) + + @staticmethod + def error_out(): + payload = [ + { + "type": "section", + "text": { + "type": "plain_text", + "text": "There was an issue running the tests.", + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + ] + + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(payload)})) + + client.chat_postMessage( + channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"], + text="There was an issue running the tests.", + blocks=payload, + ) + + def post(self): + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(self.payload)})) + + text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." + + self.thread_ts = client.chat_postMessage( + channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"], + blocks=self.payload, + text=text, + ) + + def get_reply_blocks(self, job_name, job_link, failures, text): + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + + failure_text = "" + for key, value in failures.items(): + new_text = failure_text + f"*{key}*\n_{value}_\n\n" + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + title = job_name + content = {"type": "section", "text": {"type": "mrkdwn", "text": text}} + + if job_link is not None: + content["accessory"] = { + "type": "button", + "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, + "url": job_link, + } + + return [ + {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, + content, + {"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}, + ] + + def post_reply(self): + if self.thread_ts is None: + raise ValueError("Can only post reply if a post has been made.") + + job_link = self.doc_test_results.pop("job_link") + self.doc_test_results.pop("failures") + self.doc_test_results.pop("success") + self.doc_test_results.pop("time_spent") + + sorted_dict = sorted(self.doc_test_results.items(), key=lambda t: t[0]) + for job, job_result in sorted_dict: + if len(job_result["failures"]): + text = f"*Num failures* :{len(job_result['failed'])} \n" + failures = job_result["failures"] + blocks = self.get_reply_blocks(job, job_link, failures, text=text) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"], + text=f"Results for {job}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + +def get_job_links(): + run_id = os.environ["GITHUB_RUN_ID"] + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100" + result = requests.get(url).json() + jobs = {} + + try: + jobs.update({job["name"]: job["html_url"] for job in result["jobs"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}").json() + jobs.update({job["name"]: job["html_url"] for job in result["jobs"]}) + + return jobs + except Exception as e: + print("Unknown error, could not fetch links.", e) + + return {} + + +def retrieve_artifact(name: str): + _artifact = {} + + if os.path.exists(name): + files = os.listdir(name) + for file in files: + try: + with open(os.path.join(name, file), encoding="utf-8") as f: + _artifact[file.split(".")[0]] = f.read() + except UnicodeDecodeError as e: + raise ValueError(f"Could not open {os.path.join(name, file)}.") from e + + return _artifact + + +def retrieve_available_artifacts(): + class Artifact: + def __init__(self, name: str): + self.name = name + self.paths = [] + + def __str__(self): + return self.name + + def add_path(self, path: str): + self.paths.append({"name": self.name, "path": path}) + + _available_artifacts: Dict[str, Artifact] = {} + + directories = filter(os.path.isdir, os.listdir()) + for directory in directories: + artifact_name = directory + if artifact_name not in _available_artifacts: + _available_artifacts[artifact_name] = Artifact(artifact_name) + + _available_artifacts[artifact_name].add_path(directory) + + return _available_artifacts + + +if __name__ == "__main__": + github_actions_job_links = get_job_links() + available_artifacts = retrieve_available_artifacts() + + docs = collections.OrderedDict( + [ + ("*.py", "API Examples"), + ("*.md", "MD Examples"), + ] + ) + + # This dict will contain all the information relative to each doc test category: + # - failed: list of failed tests + # - failures: dict in the format 'test': 'error_message' + doc_test_results = { + v: { + "failed": [], + "failures": {}, + } + for v in docs.values() + } + + # Link to the GitHub Action job + doc_test_results["job_link"] = github_actions_job_links.get("run_doctests") + + artifact_path = available_artifacts["doc_tests_gpu_test_reports"].paths[0] + artifact = retrieve_artifact(artifact_path["name"]) + if "stats" in artifact: + failed, success, time_spent = handle_test_results(artifact["stats"]) + doc_test_results["failures"] = failed + doc_test_results["success"] = success + doc_test_results["time_spent"] = time_spent[1:-1] + ", " + + all_failures = extract_first_line_failure(artifact["failures_short"]) + for line in artifact["summary_short"].split("\n"): + if re.search("FAILED", line): + line = line.replace("FAILED ", "") + line = line.split()[0].replace("\n", "") + + if "::" in line: + file_path, test = line.split("::") + else: + file_path, test = line, line + + for file_regex in docs.keys(): + if fnmatch(file_path, file_regex): + category = docs[file_regex] + doc_test_results[category]["failed"].append(test) + + failure = all_failures[test] if test in all_failures else "N/A" + doc_test_results[category]["failures"][test] = failure + break + + message = Message("🤗 Results of the doc tests.", doc_test_results) + message.post() + message.post_reply() diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/past_ci_versions.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/past_ci_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..61495ab2a46fcd39801614b67d5734e9fd159a90 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/past_ci_versions.py @@ -0,0 +1,126 @@ +import argparse +import os + + +past_versions_testing = { + "pytorch": { + "1.13": { + "torch": "1.13.1", + "torchvision": "0.14.1", + "torchaudio": "0.13.1", + "python": 3.9, + "cuda": "cu116", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1" + " --extra-index-url https://download.pytorch.org/whl/cu116" + ), + "base_image": "nvidia/cuda:11.6.2-cudnn8-devel-ubuntu20.04", + }, + "1.12": { + "torch": "1.12.1", + "torchvision": "0.13.1", + "torchaudio": "0.12.1", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "1.11": { + "torch": "1.11.0", + "torchvision": "0.12.0", + "torchaudio": "0.11.0", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.11.0 torchvision==0.12.0 torchaudio==0.11.0" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "1.10": { + "torch": "1.10.2", + "torchvision": "0.11.3", + "torchaudio": "0.10.2", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.10.2 torchvision==0.11.3 torchaudio==0.10.2" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + # torchaudio < 0.10 has no CUDA-enabled binary distributions + "1.9": { + "torch": "1.9.1", + "torchvision": "0.10.1", + "torchaudio": "0.9.1", + "python": 3.9, + "cuda": "cu111", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.9.1 torchvision==0.10.1 torchaudio==0.9.1" + " --extra-index-url https://download.pytorch.org/whl/cu111" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + }, + "tensorflow": { + "2.11": { + "tensorflow": "2.11.1", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.11.1", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.10": { + "tensorflow": "2.10.1", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.10.1", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.9": { + "tensorflow": "2.9.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.9.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.8": { + "tensorflow": "2.8.2", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.8.2", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.7": { + "tensorflow": "2.7.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.7.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.6": { + "tensorflow": "2.6.5", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.6.5", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.5": { + "tensorflow": "2.5.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.5.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + }, +} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser("Choose the framework and version to install") + parser.add_argument( + "--framework", help="The framework to install. Should be `torch` or `tensorflow`", type=str, required=True + ) + parser.add_argument("--version", help="The version of the framework to install.", type=str, required=True) + args = parser.parse_args() + + info = past_versions_testing[args.framework][args.version] + + os.system(f'echo "export INSTALL_CMD=\'{info["install"]}\'" >> ~/.profile') + print(f'echo "export INSTALL_CMD=\'{info["install"]}\'" >> ~/.profile') + + cuda = "" + if args.framework == "pytorch": + cuda = info["cuda"] + os.system(f"echo \"export CUDA='{cuda}'\" >> ~/.profile") + print(f"echo \"export CUDA='{cuda}'\" >> ~/.profile") diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/print_env.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/print_env.py new file mode 100644 index 0000000000000000000000000000000000000000..443ed6eab6c4b95bf82f8ae6a43da24852ad60b3 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/print_env.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 + +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. + +# this script dumps information about the environment + +import os +import sys + +import transformers + + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + +print("Python version:", sys.version) +print("transformers version:", transformers.__version__) + +try: + import torch + + print("Torch version:", torch.__version__) + print("Cuda available:", torch.cuda.is_available()) + print("Cuda version:", torch.version.cuda) + print("CuDNN version:", torch.backends.cudnn.version()) + print("Number of GPUs available:", torch.cuda.device_count()) + print("NCCL version:", torch.cuda.nccl.version()) +except ImportError: + print("Torch version:", None) + +try: + import deepspeed + + print("DeepSpeed version:", deepspeed.__version__) +except ImportError: + print("DeepSpeed version:", None) + +try: + import tensorflow as tf + + print("TensorFlow version:", tf.__version__) + print("TF GPUs available:", bool(tf.config.list_physical_devices("GPU"))) + print("Number of TF GPUs available:", len(tf.config.list_physical_devices("GPU"))) +except ImportError: + print("TensorFlow version:", None) diff --git a/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/release.py b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/release.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba0ead7c6ceda99846f38664cb0f641b613e930 --- /dev/null +++ b/docs/development-artifacts/implicit-reasoning-paper-reproduction-v1/training-upstream/transformers/utils/release.py @@ -0,0 +1,225 @@ +# coding=utf-8 +# Copyright 2021 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. +""" +Utility that prepares the repository for releases (or patches) by updating all versions in the relevant places. It +also performs some post-release cleanup, by updating the links in the main README to respective model doc pages (from +main to stable). + +To prepare for a release, use from the root of the repo on the release branch with: + +```bash +python release.py +``` + +or use `make pre-release`. + +To prepare for a patch release, use from the root of the repo on the release branch with: + +```bash +python release.py --patch +``` + +or use `make pre-patch`. + +To do the post-release cleanup, use from the root of the repo on the main branch with: + +```bash +python release.py --post_release +``` + +or use `make post-release`. +""" +import argparse +import os +import re + +import packaging.version + + +# All paths are defined with the intent that this script should be run from the root of the repo. +PATH_TO_EXAMPLES = "examples/" +# This maps a type of file to the pattern to look for when searching where the version is defined, as well as the +# template to follow when replacing it with the new version. +REPLACE_PATTERNS = { + "examples": (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), + "init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'), + "setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'), +} +# This maps a type of file to its path in Transformers +REPLACE_FILES = { + "init": "src/transformers/__init__.py", + "setup": "setup.py", +} +README_FILE = "README.md" + + +def update_version_in_file(fname: str, version: str, file_type: str): + """ + Update the version of Transformers in one file. + + Args: + fname (`str`): The path to the file where we want to update the version. + version (`str`): The new version to set in the file. + file_type (`str`): The type of the file (should be a key in `REPLACE_PATTERNS`). + """ + with open(fname, "r", encoding="utf-8", newline="\n") as f: + code = f.read() + re_pattern, replace = REPLACE_PATTERNS[file_type] + replace = replace.replace("VERSION", version) + code = re_pattern.sub(replace, code) + with open(fname, "w", encoding="utf-8", newline="\n") as f: + f.write(code) + + +def update_version_in_examples(version: str): + """ + Update the version in all examples files. + + Args: + version (`str`): The new version to set in the examples. + """ + for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES): + # Removing some of the folders with non-actively maintained examples from the walk + if "research_projects" in directories: + directories.remove("research_projects") + if "legacy" in directories: + directories.remove("legacy") + for fname in fnames: + if fname.endswith(".py"): + update_version_in_file(os.path.join(folder, fname), version, file_type="examples") + + +def global_version_update(version: str, patch: bool = False): + """ + Update the version in all needed files. + + Args: + version (`str`): The new version to set everywhere. + patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release. + """ + for pattern, fname in REPLACE_FILES.items(): + update_version_in_file(fname, version, pattern) + if not patch: + # We don't update the version in the examples for patch releases. + update_version_in_examples(version) + + +def clean_main_ref_in_model_list(): + """ + Replace the links from main doc to stable doc in the model list of the README. + """ + # If the introduction or the conclusion of the list change, the prompts may need to be updated. + _start_prompt = "🤗 Transformers currently provides the following architectures" + _end_prompt = "1. Want to contribute a new model?" + with open(README_FILE, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Find the start of the list. + start_index = 0 + while not lines[start_index].startswith(_start_prompt): + start_index += 1 + start_index += 1 + + index = start_index + # Update the lines in the model list. + while not lines[index].startswith(_end_prompt): + if lines[index].startswith("1."): + lines[index] = lines[index].replace( + "https://huggingface.co/docs/transformers/main/model_doc", + "https://huggingface.co/docs/transformers/model_doc", + ) + index += 1 + + with open(README_FILE, "w", encoding="utf-8", newline="\n") as f: + f.writelines(lines) + + +def get_version() -> packaging.version.Version: + """ + Reads the current version in the main __init__. + """ + with open(REPLACE_FILES["init"], "r") as f: + code = f.read() + default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0] + return packaging.version.parse(default_version) + + +def pre_release_work(patch: bool = False): + """ + Do all the necessary pre-release steps: + - figure out the next minor release version and ask confirmation + - update the version eveywhere + - clean-up the model list in the main README + + Args: + patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release. + """ + # First let's get the default version: base version if we are in dev, bump minor otherwise. + default_version = get_version() + if patch and default_version.is_devrelease: + raise ValueError("Can't create a patch version from the dev branch, checkout a released version!") + if default_version.is_devrelease: + default_version = default_version.base_version + elif patch: + default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" + else: + default_version = f"{default_version.major}.{default_version.minor + 1}.0" + + # Now let's ask nicely if we have found the right version. + version = input(f"Which version are you releasing? [{default_version}]") + if len(version) == 0: + version = default_version + + print(f"Updating version to {version}.") + global_version_update(version, patch=patch) + if not patch: + print("Cleaning main README, don't forget to run `make fix-copies`.") + clean_main_ref_in_model_list() + + +def post_release_work(): + """ + Do all the necesarry post-release steps: + - figure out the next dev version and ask confirmation + - update the version eveywhere + - clean-up the model list in the main README + """ + # First let's get the current version + current_version = get_version() + dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0" + current_version = current_version.base_version + + # Check with the user we got that right. + version = input(f"Which version are we developing now? [{dev_version}]") + if len(version) == 0: + version = dev_version + + print(f"Updating version to {version}.") + global_version_update(version) + print("Cleaning main README, don't forget to run `make fix-copies`.") + clean_main_ref_in_model_list() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") + parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") + args = parser.parse_args() + if not args.post_release: + pre_release_work(patch=args.patch) + elif args.patch: + print("Nothing to do after a patch :-)") + else: + post_release_work()